1use std::{
2 cmp,
3 ops::{ControlFlow, Range},
4 sync::Arc,
5 time::Duration,
6};
7
8use crate::{
9 display_map::Inlay, Anchor, Editor, ExcerptId, InlayId, MultiBuffer, MultiBufferSnapshot,
10};
11use anyhow::Context;
12use clock::Global;
13use futures::future;
14use gpui::{Model, ModelContext, Task, ViewContext};
15use language::{language_settings::InlayHintKind, Buffer, BufferSnapshot};
16use parking_lot::RwLock;
17use project::{InlayHint, ResolveState};
18
19use collections::{hash_map, HashMap, HashSet};
20use language::language_settings::InlayHintSettings;
21use smol::lock::Semaphore;
22use sum_tree::Bias;
23use text::{ToOffset, ToPoint};
24use util::post_inc;
25
26pub struct InlayHintCache {
27 hints: HashMap<ExcerptId, Arc<RwLock<CachedExcerptHints>>>,
28 allowed_hint_kinds: HashSet<Option<InlayHintKind>>,
29 version: usize,
30 pub(super) enabled: bool,
31 update_tasks: HashMap<ExcerptId, TasksForRanges>,
32 lsp_request_limiter: Arc<Semaphore>,
33}
34
35#[derive(Debug)]
36struct TasksForRanges {
37 tasks: Vec<Task<()>>,
38 sorted_ranges: Vec<Range<language::Anchor>>,
39}
40
41#[derive(Debug)]
42pub struct CachedExcerptHints {
43 version: usize,
44 buffer_version: Global,
45 buffer_id: u64,
46 ordered_hints: Vec<InlayId>,
47 hints_by_id: HashMap<InlayId, InlayHint>,
48}
49
50#[derive(Debug, Clone, Copy)]
51pub enum InvalidationStrategy {
52 RefreshRequested,
53 BufferEdited,
54 None,
55}
56
57#[derive(Debug, Default)]
58pub struct InlaySplice {
59 pub to_remove: Vec<InlayId>,
60 pub to_insert: Vec<Inlay>,
61}
62
63#[derive(Debug)]
64struct ExcerptHintsUpdate {
65 excerpt_id: ExcerptId,
66 remove_from_visible: Vec<InlayId>,
67 remove_from_cache: HashSet<InlayId>,
68 add_to_cache: Vec<InlayHint>,
69}
70
71#[derive(Debug, Clone, Copy)]
72struct ExcerptQuery {
73 buffer_id: u64,
74 excerpt_id: ExcerptId,
75 cache_version: usize,
76 invalidate: InvalidationStrategy,
77 reason: &'static str,
78}
79
80impl InvalidationStrategy {
81 fn should_invalidate(&self) -> bool {
82 matches!(
83 self,
84 InvalidationStrategy::RefreshRequested | InvalidationStrategy::BufferEdited
85 )
86 }
87}
88
89impl TasksForRanges {
90 fn new(query_ranges: QueryRanges, task: Task<()>) -> Self {
91 let mut sorted_ranges = Vec::new();
92 sorted_ranges.extend(query_ranges.before_visible);
93 sorted_ranges.extend(query_ranges.visible);
94 sorted_ranges.extend(query_ranges.after_visible);
95 Self {
96 tasks: vec![task],
97 sorted_ranges,
98 }
99 }
100
101 fn update_cached_tasks(
102 &mut self,
103 buffer_snapshot: &BufferSnapshot,
104 query_ranges: QueryRanges,
105 invalidate: InvalidationStrategy,
106 spawn_task: impl FnOnce(QueryRanges) -> Task<()>,
107 ) {
108 let query_ranges = if invalidate.should_invalidate() {
109 self.tasks.clear();
110 self.sorted_ranges.clear();
111 query_ranges
112 } else {
113 let mut non_cached_query_ranges = query_ranges;
114 non_cached_query_ranges.before_visible = non_cached_query_ranges
115 .before_visible
116 .into_iter()
117 .flat_map(|query_range| {
118 self.remove_cached_ranges_from_query(buffer_snapshot, query_range)
119 })
120 .collect();
121 non_cached_query_ranges.visible = non_cached_query_ranges
122 .visible
123 .into_iter()
124 .flat_map(|query_range| {
125 self.remove_cached_ranges_from_query(buffer_snapshot, query_range)
126 })
127 .collect();
128 non_cached_query_ranges.after_visible = non_cached_query_ranges
129 .after_visible
130 .into_iter()
131 .flat_map(|query_range| {
132 self.remove_cached_ranges_from_query(buffer_snapshot, query_range)
133 })
134 .collect();
135 non_cached_query_ranges
136 };
137
138 if !query_ranges.is_empty() {
139 self.tasks.push(spawn_task(query_ranges));
140 }
141 }
142
143 fn remove_cached_ranges_from_query(
144 &mut self,
145 buffer_snapshot: &BufferSnapshot,
146 query_range: Range<language::Anchor>,
147 ) -> Vec<Range<language::Anchor>> {
148 let mut ranges_to_query = Vec::new();
149 let mut latest_cached_range = None::<&mut Range<language::Anchor>>;
150 for cached_range in self
151 .sorted_ranges
152 .iter_mut()
153 .skip_while(|cached_range| {
154 cached_range
155 .end
156 .cmp(&query_range.start, buffer_snapshot)
157 .is_lt()
158 })
159 .take_while(|cached_range| {
160 cached_range
161 .start
162 .cmp(&query_range.end, buffer_snapshot)
163 .is_le()
164 })
165 {
166 match latest_cached_range {
167 Some(latest_cached_range) => {
168 if latest_cached_range.end.offset.saturating_add(1) < cached_range.start.offset
169 {
170 ranges_to_query.push(latest_cached_range.end..cached_range.start);
171 cached_range.start = latest_cached_range.end;
172 }
173 }
174 None => {
175 if query_range
176 .start
177 .cmp(&cached_range.start, buffer_snapshot)
178 .is_lt()
179 {
180 ranges_to_query.push(query_range.start..cached_range.start);
181 cached_range.start = query_range.start;
182 }
183 }
184 }
185 latest_cached_range = Some(cached_range);
186 }
187
188 match latest_cached_range {
189 Some(latest_cached_range) => {
190 if latest_cached_range.end.offset.saturating_add(1) < query_range.end.offset {
191 ranges_to_query.push(latest_cached_range.end..query_range.end);
192 latest_cached_range.end = query_range.end;
193 }
194 }
195 None => {
196 ranges_to_query.push(query_range.clone());
197 self.sorted_ranges.push(query_range);
198 self.sorted_ranges
199 .sort_by(|range_a, range_b| range_a.start.cmp(&range_b.start, buffer_snapshot));
200 }
201 }
202
203 ranges_to_query
204 }
205
206 fn invalidate_range(&mut self, buffer: &BufferSnapshot, range: &Range<language::Anchor>) {
207 self.sorted_ranges = self
208 .sorted_ranges
209 .drain(..)
210 .filter_map(|mut cached_range| {
211 if cached_range.start.cmp(&range.end, buffer).is_gt()
212 || cached_range.end.cmp(&range.start, buffer).is_lt()
213 {
214 Some(vec![cached_range])
215 } else if cached_range.start.cmp(&range.start, buffer).is_ge()
216 && cached_range.end.cmp(&range.end, buffer).is_le()
217 {
218 None
219 } else if range.start.cmp(&cached_range.start, buffer).is_ge()
220 && range.end.cmp(&cached_range.end, buffer).is_le()
221 {
222 Some(vec![
223 cached_range.start..range.start,
224 range.end..cached_range.end,
225 ])
226 } else if cached_range.start.cmp(&range.start, buffer).is_ge() {
227 cached_range.start = range.end;
228 Some(vec![cached_range])
229 } else {
230 cached_range.end = range.start;
231 Some(vec![cached_range])
232 }
233 })
234 .flatten()
235 .collect();
236 }
237}
238
239impl InlayHintCache {
240 pub fn new(inlay_hint_settings: InlayHintSettings) -> Self {
241 Self {
242 allowed_hint_kinds: inlay_hint_settings.enabled_inlay_hint_kinds(),
243 enabled: inlay_hint_settings.enabled,
244 hints: HashMap::default(),
245 update_tasks: HashMap::default(),
246 version: 0,
247 lsp_request_limiter: Arc::new(Semaphore::new(MAX_CONCURRENT_LSP_REQUESTS)),
248 }
249 }
250
251 pub fn update_settings(
252 &mut self,
253 multi_buffer: &Model<MultiBuffer>,
254 new_hint_settings: InlayHintSettings,
255 visible_hints: Vec<Inlay>,
256 cx: &mut ViewContext<Editor>,
257 ) -> ControlFlow<Option<InlaySplice>> {
258 let new_allowed_hint_kinds = new_hint_settings.enabled_inlay_hint_kinds();
259 match (self.enabled, new_hint_settings.enabled) {
260 (false, false) => {
261 self.allowed_hint_kinds = new_allowed_hint_kinds;
262 ControlFlow::Break(None)
263 }
264 (true, true) => {
265 if new_allowed_hint_kinds == self.allowed_hint_kinds {
266 ControlFlow::Break(None)
267 } else {
268 let new_splice = self.new_allowed_hint_kinds_splice(
269 multi_buffer,
270 &visible_hints,
271 &new_allowed_hint_kinds,
272 cx,
273 );
274 if new_splice.is_some() {
275 self.version += 1;
276 self.allowed_hint_kinds = new_allowed_hint_kinds;
277 }
278 ControlFlow::Break(new_splice)
279 }
280 }
281 (true, false) => {
282 self.enabled = new_hint_settings.enabled;
283 self.allowed_hint_kinds = new_allowed_hint_kinds;
284 if self.hints.is_empty() {
285 ControlFlow::Break(None)
286 } else {
287 self.clear();
288 ControlFlow::Break(Some(InlaySplice {
289 to_remove: visible_hints.iter().map(|inlay| inlay.id).collect(),
290 to_insert: Vec::new(),
291 }))
292 }
293 }
294 (false, true) => {
295 self.enabled = new_hint_settings.enabled;
296 self.allowed_hint_kinds = new_allowed_hint_kinds;
297 ControlFlow::Continue(())
298 }
299 }
300 }
301
302 pub fn spawn_hint_refresh(
303 &mut self,
304 reason: &'static str,
305 excerpts_to_query: HashMap<ExcerptId, (Model<Buffer>, Global, Range<usize>)>,
306 invalidate: InvalidationStrategy,
307 cx: &mut ViewContext<Editor>,
308 ) -> Option<InlaySplice> {
309 if !self.enabled {
310 return None;
311 }
312
313 let mut invalidated_hints = Vec::new();
314 if invalidate.should_invalidate() {
315 self.update_tasks
316 .retain(|task_excerpt_id, _| excerpts_to_query.contains_key(task_excerpt_id));
317 self.hints.retain(|cached_excerpt, cached_hints| {
318 let retain = excerpts_to_query.contains_key(cached_excerpt);
319 if !retain {
320 invalidated_hints.extend(cached_hints.read().ordered_hints.iter().copied());
321 }
322 retain
323 });
324 }
325 if excerpts_to_query.is_empty() && invalidated_hints.is_empty() {
326 return None;
327 }
328
329 let cache_version = self.version + 1;
330 cx.spawn(|editor, mut cx| async move {
331 editor
332 .update(&mut cx, |editor, cx| {
333 spawn_new_update_tasks(
334 editor,
335 reason,
336 excerpts_to_query,
337 invalidate,
338 cache_version,
339 cx,
340 )
341 })
342 .ok();
343 })
344 .detach();
345
346 if invalidated_hints.is_empty() {
347 None
348 } else {
349 Some(InlaySplice {
350 to_remove: invalidated_hints,
351 to_insert: Vec::new(),
352 })
353 }
354 }
355
356 fn new_allowed_hint_kinds_splice(
357 &self,
358 multi_buffer: &Model<MultiBuffer>,
359 visible_hints: &[Inlay],
360 new_kinds: &HashSet<Option<InlayHintKind>>,
361 cx: &mut ViewContext<Editor>,
362 ) -> Option<InlaySplice> {
363 let old_kinds = &self.allowed_hint_kinds;
364 if new_kinds == old_kinds {
365 return None;
366 }
367
368 let mut to_remove = Vec::new();
369 let mut to_insert = Vec::new();
370 let mut shown_hints_to_remove = visible_hints.iter().fold(
371 HashMap::<ExcerptId, Vec<(Anchor, InlayId)>>::default(),
372 |mut current_hints, inlay| {
373 current_hints
374 .entry(inlay.position.excerpt_id)
375 .or_default()
376 .push((inlay.position, inlay.id));
377 current_hints
378 },
379 );
380
381 let multi_buffer = multi_buffer.read(cx);
382 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
383
384 for (excerpt_id, excerpt_cached_hints) in &self.hints {
385 let shown_excerpt_hints_to_remove =
386 shown_hints_to_remove.entry(*excerpt_id).or_default();
387 let excerpt_cached_hints = excerpt_cached_hints.read();
388 let mut excerpt_cache = excerpt_cached_hints.ordered_hints.iter().fuse().peekable();
389 shown_excerpt_hints_to_remove.retain(|(shown_anchor, shown_hint_id)| {
390 let Some(buffer) = shown_anchor
391 .buffer_id
392 .and_then(|buffer_id| multi_buffer.buffer(buffer_id))
393 else {
394 return false;
395 };
396 let buffer_snapshot = buffer.read(cx).snapshot();
397 loop {
398 match excerpt_cache.peek() {
399 Some(&cached_hint_id) => {
400 let cached_hint = &excerpt_cached_hints.hints_by_id[cached_hint_id];
401 if cached_hint_id == shown_hint_id {
402 excerpt_cache.next();
403 return !new_kinds.contains(&cached_hint.kind);
404 }
405
406 match cached_hint
407 .position
408 .cmp(&shown_anchor.text_anchor, &buffer_snapshot)
409 {
410 cmp::Ordering::Less | cmp::Ordering::Equal => {
411 if !old_kinds.contains(&cached_hint.kind)
412 && new_kinds.contains(&cached_hint.kind)
413 {
414 to_insert.push(Inlay::hint(
415 cached_hint_id.id(),
416 multi_buffer_snapshot.anchor_in_excerpt(
417 *excerpt_id,
418 cached_hint.position,
419 ),
420 &cached_hint,
421 ));
422 }
423 excerpt_cache.next();
424 }
425 cmp::Ordering::Greater => return true,
426 }
427 }
428 None => return true,
429 }
430 }
431 });
432
433 for cached_hint_id in excerpt_cache {
434 let maybe_missed_cached_hint = &excerpt_cached_hints.hints_by_id[cached_hint_id];
435 let cached_hint_kind = maybe_missed_cached_hint.kind;
436 if !old_kinds.contains(&cached_hint_kind) && new_kinds.contains(&cached_hint_kind) {
437 to_insert.push(Inlay::hint(
438 cached_hint_id.id(),
439 multi_buffer_snapshot
440 .anchor_in_excerpt(*excerpt_id, maybe_missed_cached_hint.position),
441 &maybe_missed_cached_hint,
442 ));
443 }
444 }
445 }
446
447 to_remove.extend(
448 shown_hints_to_remove
449 .into_values()
450 .flatten()
451 .map(|(_, hint_id)| hint_id),
452 );
453 if to_remove.is_empty() && to_insert.is_empty() {
454 None
455 } else {
456 Some(InlaySplice {
457 to_remove,
458 to_insert,
459 })
460 }
461 }
462
463 pub fn remove_excerpts(&mut self, excerpts_removed: Vec<ExcerptId>) -> Option<InlaySplice> {
464 let mut to_remove = Vec::new();
465 for excerpt_to_remove in excerpts_removed {
466 self.update_tasks.remove(&excerpt_to_remove);
467 if let Some(cached_hints) = self.hints.remove(&excerpt_to_remove) {
468 let cached_hints = cached_hints.read();
469 to_remove.extend(cached_hints.ordered_hints.iter().copied());
470 }
471 }
472 if to_remove.is_empty() {
473 None
474 } else {
475 self.version += 1;
476 Some(InlaySplice {
477 to_remove,
478 to_insert: Vec::new(),
479 })
480 }
481 }
482
483 pub fn clear(&mut self) {
484 if !self.update_tasks.is_empty() || !self.hints.is_empty() {
485 self.version += 1;
486 }
487 self.update_tasks.clear();
488 self.hints.clear();
489 }
490
491 pub fn hint_by_id(&self, excerpt_id: ExcerptId, hint_id: InlayId) -> Option<InlayHint> {
492 self.hints
493 .get(&excerpt_id)?
494 .read()
495 .hints_by_id
496 .get(&hint_id)
497 .cloned()
498 }
499
500 pub fn hints(&self) -> Vec<InlayHint> {
501 let mut hints = Vec::new();
502 for excerpt_hints in self.hints.values() {
503 let excerpt_hints = excerpt_hints.read();
504 hints.extend(
505 excerpt_hints
506 .ordered_hints
507 .iter()
508 .map(|id| &excerpt_hints.hints_by_id[id])
509 .cloned(),
510 );
511 }
512 hints
513 }
514
515 pub fn version(&self) -> usize {
516 self.version
517 }
518
519 pub fn spawn_hint_resolve(
520 &self,
521 buffer_id: u64,
522 excerpt_id: ExcerptId,
523 id: InlayId,
524 cx: &mut ViewContext<'_, Editor>,
525 ) {
526 if let Some(excerpt_hints) = self.hints.get(&excerpt_id) {
527 let mut guard = excerpt_hints.write();
528 if let Some(cached_hint) = guard.hints_by_id.get_mut(&id) {
529 if let ResolveState::CanResolve(server_id, _) = &cached_hint.resolve_state {
530 let hint_to_resolve = cached_hint.clone();
531 let server_id = *server_id;
532 cached_hint.resolve_state = ResolveState::Resolving;
533 drop(guard);
534 cx.spawn(|editor, mut cx| async move {
535 let resolved_hint_task = editor.update(&mut cx, |editor, cx| {
536 editor
537 .buffer()
538 .read(cx)
539 .buffer(buffer_id)
540 .and_then(|buffer| {
541 let project = editor.project.as_ref()?;
542 Some(project.update(cx, |project, cx| {
543 project.resolve_inlay_hint(
544 hint_to_resolve,
545 buffer,
546 server_id,
547 cx,
548 )
549 }))
550 })
551 })?;
552 if let Some(resolved_hint_task) = resolved_hint_task {
553 let mut resolved_hint =
554 resolved_hint_task.await.context("hint resolve task")?;
555 editor.update(&mut cx, |editor, _| {
556 if let Some(excerpt_hints) =
557 editor.inlay_hint_cache.hints.get(&excerpt_id)
558 {
559 let mut guard = excerpt_hints.write();
560 if let Some(cached_hint) = guard.hints_by_id.get_mut(&id) {
561 if cached_hint.resolve_state == ResolveState::Resolving {
562 resolved_hint.resolve_state = ResolveState::Resolved;
563 *cached_hint = resolved_hint;
564 }
565 }
566 }
567 })?;
568 }
569
570 anyhow::Ok(())
571 })
572 .detach_and_log_err(cx);
573 }
574 }
575 }
576 }
577}
578
579fn spawn_new_update_tasks(
580 editor: &mut Editor,
581 reason: &'static str,
582 excerpts_to_query: HashMap<ExcerptId, (Model<Buffer>, Global, Range<usize>)>,
583 invalidate: InvalidationStrategy,
584 update_cache_version: usize,
585 cx: &mut ViewContext<'_, Editor>,
586) {
587 let visible_hints = Arc::new(editor.visible_inlay_hints(cx));
588 for (excerpt_id, (excerpt_buffer, new_task_buffer_version, excerpt_visible_range)) in
589 excerpts_to_query
590 {
591 if excerpt_visible_range.is_empty() {
592 continue;
593 }
594 let buffer = excerpt_buffer.read(cx);
595 let buffer_id = buffer.remote_id();
596 let buffer_snapshot = buffer.snapshot();
597 if buffer_snapshot
598 .version()
599 .changed_since(&new_task_buffer_version)
600 {
601 continue;
602 }
603
604 let cached_excerpt_hints = editor.inlay_hint_cache.hints.get(&excerpt_id).cloned();
605 if let Some(cached_excerpt_hints) = &cached_excerpt_hints {
606 let cached_excerpt_hints = cached_excerpt_hints.read();
607 let cached_buffer_version = &cached_excerpt_hints.buffer_version;
608 if cached_excerpt_hints.version > update_cache_version
609 || cached_buffer_version.changed_since(&new_task_buffer_version)
610 {
611 continue;
612 }
613 };
614
615 let (multi_buffer_snapshot, Some(query_ranges)) =
616 editor.buffer.update(cx, |multi_buffer, cx| {
617 (
618 multi_buffer.snapshot(cx),
619 determine_query_ranges(
620 multi_buffer,
621 excerpt_id,
622 &excerpt_buffer,
623 excerpt_visible_range,
624 cx,
625 ),
626 )
627 })
628 else {
629 return;
630 };
631 let query = ExcerptQuery {
632 buffer_id,
633 excerpt_id,
634 cache_version: update_cache_version,
635 invalidate,
636 reason,
637 };
638
639 let new_update_task = |query_ranges| {
640 new_update_task(
641 query,
642 query_ranges,
643 multi_buffer_snapshot,
644 buffer_snapshot.clone(),
645 Arc::clone(&visible_hints),
646 cached_excerpt_hints,
647 Arc::clone(&editor.inlay_hint_cache.lsp_request_limiter),
648 cx,
649 )
650 };
651
652 match editor.inlay_hint_cache.update_tasks.entry(excerpt_id) {
653 hash_map::Entry::Occupied(mut o) => {
654 o.get_mut().update_cached_tasks(
655 &buffer_snapshot,
656 query_ranges,
657 invalidate,
658 new_update_task,
659 );
660 }
661 hash_map::Entry::Vacant(v) => {
662 v.insert(TasksForRanges::new(
663 query_ranges.clone(),
664 new_update_task(query_ranges),
665 ));
666 }
667 }
668 }
669}
670
671#[derive(Debug, Clone)]
672struct QueryRanges {
673 before_visible: Vec<Range<language::Anchor>>,
674 visible: Vec<Range<language::Anchor>>,
675 after_visible: Vec<Range<language::Anchor>>,
676}
677
678impl QueryRanges {
679 fn is_empty(&self) -> bool {
680 self.before_visible.is_empty() && self.visible.is_empty() && self.after_visible.is_empty()
681 }
682}
683
684fn determine_query_ranges(
685 multi_buffer: &mut MultiBuffer,
686 excerpt_id: ExcerptId,
687 excerpt_buffer: &Model<Buffer>,
688 excerpt_visible_range: Range<usize>,
689 cx: &mut ModelContext<'_, MultiBuffer>,
690) -> Option<QueryRanges> {
691 let full_excerpt_range = multi_buffer
692 .excerpts_for_buffer(excerpt_buffer, cx)
693 .into_iter()
694 .find(|(id, _)| id == &excerpt_id)
695 .map(|(_, range)| range.context)?;
696 let buffer = excerpt_buffer.read(cx);
697 let snapshot = buffer.snapshot();
698 let excerpt_visible_len = excerpt_visible_range.end - excerpt_visible_range.start;
699
700 let visible_range = if excerpt_visible_range.start == excerpt_visible_range.end {
701 return None;
702 } else {
703 vec![
704 buffer.anchor_before(snapshot.clip_offset(excerpt_visible_range.start, Bias::Left))
705 ..buffer.anchor_after(snapshot.clip_offset(excerpt_visible_range.end, Bias::Right)),
706 ]
707 };
708
709 let full_excerpt_range_end_offset = full_excerpt_range.end.to_offset(&snapshot);
710 let after_visible_range_start = excerpt_visible_range
711 .end
712 .saturating_add(1)
713 .min(full_excerpt_range_end_offset)
714 .min(buffer.len());
715 let after_visible_range = if after_visible_range_start == full_excerpt_range_end_offset {
716 Vec::new()
717 } else {
718 let after_range_end_offset = after_visible_range_start
719 .saturating_add(excerpt_visible_len)
720 .min(full_excerpt_range_end_offset)
721 .min(buffer.len());
722 vec![
723 buffer.anchor_before(snapshot.clip_offset(after_visible_range_start, Bias::Left))
724 ..buffer.anchor_after(snapshot.clip_offset(after_range_end_offset, Bias::Right)),
725 ]
726 };
727
728 let full_excerpt_range_start_offset = full_excerpt_range.start.to_offset(&snapshot);
729 let before_visible_range_end = excerpt_visible_range
730 .start
731 .saturating_sub(1)
732 .max(full_excerpt_range_start_offset);
733 let before_visible_range = if before_visible_range_end == full_excerpt_range_start_offset {
734 Vec::new()
735 } else {
736 let before_range_start_offset = before_visible_range_end
737 .saturating_sub(excerpt_visible_len)
738 .max(full_excerpt_range_start_offset);
739 vec![
740 buffer.anchor_before(snapshot.clip_offset(before_range_start_offset, Bias::Left))
741 ..buffer.anchor_after(snapshot.clip_offset(before_visible_range_end, Bias::Right)),
742 ]
743 };
744
745 Some(QueryRanges {
746 before_visible: before_visible_range,
747 visible: visible_range,
748 after_visible: after_visible_range,
749 })
750}
751
752const MAX_CONCURRENT_LSP_REQUESTS: usize = 5;
753const INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS: u64 = 400;
754
755fn new_update_task(
756 query: ExcerptQuery,
757 query_ranges: QueryRanges,
758 multi_buffer_snapshot: MultiBufferSnapshot,
759 buffer_snapshot: BufferSnapshot,
760 visible_hints: Arc<Vec<Inlay>>,
761 cached_excerpt_hints: Option<Arc<RwLock<CachedExcerptHints>>>,
762 lsp_request_limiter: Arc<Semaphore>,
763 cx: &mut ViewContext<'_, Editor>,
764) -> Task<()> {
765 cx.spawn(|editor, mut cx| async move {
766 let closure_cx = cx.clone();
767 let fetch_and_update_hints = |invalidate, range| {
768 fetch_and_update_hints(
769 editor.clone(),
770 multi_buffer_snapshot.clone(),
771 buffer_snapshot.clone(),
772 Arc::clone(&visible_hints),
773 cached_excerpt_hints.as_ref().map(Arc::clone),
774 query,
775 invalidate,
776 range,
777 Arc::clone(&lsp_request_limiter),
778 closure_cx.clone(),
779 )
780 };
781 let visible_range_update_results = future::join_all(query_ranges.visible.into_iter().map(
782 |visible_range| async move {
783 (
784 visible_range.clone(),
785 fetch_and_update_hints(query.invalidate.should_invalidate(), visible_range)
786 .await,
787 )
788 },
789 ))
790 .await;
791
792 let hint_delay = cx.background_executor().timer(Duration::from_millis(
793 INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS,
794 ));
795
796 let mut query_range_failed = |range: &Range<language::Anchor>, e: anyhow::Error| {
797 log::error!("inlay hint update task for range {range:?} failed: {e:#}");
798 editor
799 .update(&mut cx, |editor, _| {
800 if let Some(task_ranges) = editor
801 .inlay_hint_cache
802 .update_tasks
803 .get_mut(&query.excerpt_id)
804 {
805 task_ranges.invalidate_range(&buffer_snapshot, &range);
806 }
807 })
808 .ok()
809 };
810
811 for (range, result) in visible_range_update_results {
812 if let Err(e) = result {
813 query_range_failed(&range, e);
814 }
815 }
816
817 hint_delay.await;
818 let invisible_range_update_results = future::join_all(
819 query_ranges
820 .before_visible
821 .into_iter()
822 .chain(query_ranges.after_visible.into_iter())
823 .map(|invisible_range| async move {
824 (
825 invisible_range.clone(),
826 fetch_and_update_hints(false, invisible_range).await,
827 )
828 }),
829 )
830 .await;
831 for (range, result) in invisible_range_update_results {
832 if let Err(e) = result {
833 query_range_failed(&range, e);
834 }
835 }
836 })
837}
838
839async fn fetch_and_update_hints(
840 editor: gpui::WeakView<Editor>,
841 multi_buffer_snapshot: MultiBufferSnapshot,
842 buffer_snapshot: BufferSnapshot,
843 visible_hints: Arc<Vec<Inlay>>,
844 cached_excerpt_hints: Option<Arc<RwLock<CachedExcerptHints>>>,
845 query: ExcerptQuery,
846 invalidate: bool,
847 fetch_range: Range<language::Anchor>,
848 lsp_request_limiter: Arc<Semaphore>,
849 mut cx: gpui::AsyncWindowContext,
850) -> anyhow::Result<()> {
851 let (lsp_request_guard, got_throttled) = if query.invalidate.should_invalidate() {
852 (None, false)
853 } else {
854 match lsp_request_limiter.try_acquire() {
855 Some(guard) => (Some(guard), false),
856 None => (Some(lsp_request_limiter.acquire().await), true),
857 }
858 };
859 let fetch_range_to_log =
860 fetch_range.start.to_point(&buffer_snapshot)..fetch_range.end.to_point(&buffer_snapshot);
861 let inlay_hints_fetch_task = editor
862 .update(&mut cx, |editor, cx| {
863 if got_throttled {
864 let query_not_around_visible_range = match editor.excerpt_visible_offsets(None, cx).remove(&query.excerpt_id) {
865 Some((_, _, current_visible_range)) => {
866 let visible_offset_length = current_visible_range.len();
867 let double_visible_range = current_visible_range
868 .start
869 .saturating_sub(visible_offset_length)
870 ..current_visible_range
871 .end
872 .saturating_add(visible_offset_length)
873 .min(buffer_snapshot.len());
874 !double_visible_range
875 .contains(&fetch_range.start.to_offset(&buffer_snapshot))
876 && !double_visible_range
877 .contains(&fetch_range.end.to_offset(&buffer_snapshot))
878 },
879 None => true,
880 };
881 if query_not_around_visible_range {
882 log::trace!("Fetching inlay hints for range {fetch_range_to_log:?} got throttled and fell off the current visible range, skipping.");
883 if let Some(task_ranges) = editor
884 .inlay_hint_cache
885 .update_tasks
886 .get_mut(&query.excerpt_id)
887 {
888 task_ranges.invalidate_range(&buffer_snapshot, &fetch_range);
889 }
890 return None;
891 }
892 }
893 editor
894 .buffer()
895 .read(cx)
896 .buffer(query.buffer_id)
897 .and_then(|buffer| {
898 let project = editor.project.as_ref()?;
899 Some(project.update(cx, |project, cx| {
900 project.inlay_hints(buffer, fetch_range.clone(), cx)
901 }))
902 })
903 })
904 .ok()
905 .flatten();
906 let new_hints = match inlay_hints_fetch_task {
907 Some(fetch_task) => {
908 log::debug!(
909 "Fetching inlay hints for range {fetch_range_to_log:?}, reason: {query_reason}, invalidate: {invalidate}",
910 query_reason = query.reason,
911 );
912 log::trace!(
913 "Currently visible hints: {visible_hints:?}, cached hints present: {}",
914 cached_excerpt_hints.is_some(),
915 );
916 fetch_task.await.context("inlay hint fetch task")?
917 }
918 None => return Ok(()),
919 };
920 drop(lsp_request_guard);
921 log::debug!(
922 "Fetched {} hints for range {fetch_range_to_log:?}",
923 new_hints.len()
924 );
925 log::trace!("Fetched hints: {new_hints:?}");
926
927 let background_task_buffer_snapshot = buffer_snapshot.clone();
928 let backround_fetch_range = fetch_range.clone();
929 let new_update = cx
930 .background_executor()
931 .spawn(async move {
932 calculate_hint_updates(
933 query.excerpt_id,
934 invalidate,
935 backround_fetch_range,
936 new_hints,
937 &background_task_buffer_snapshot,
938 cached_excerpt_hints,
939 &visible_hints,
940 )
941 })
942 .await;
943 if let Some(new_update) = new_update {
944 log::debug!(
945 "Applying update for range {fetch_range_to_log:?}: remove from editor: {}, remove from cache: {}, add to cache: {}",
946 new_update.remove_from_visible.len(),
947 new_update.remove_from_cache.len(),
948 new_update.add_to_cache.len()
949 );
950 log::trace!("New update: {new_update:?}");
951 editor
952 .update(&mut cx, |editor, cx| {
953 apply_hint_update(
954 editor,
955 new_update,
956 query,
957 invalidate,
958 buffer_snapshot,
959 multi_buffer_snapshot,
960 cx,
961 );
962 })
963 .ok();
964 }
965 Ok(())
966}
967
968fn calculate_hint_updates(
969 excerpt_id: ExcerptId,
970 invalidate: bool,
971 fetch_range: Range<language::Anchor>,
972 new_excerpt_hints: Vec<InlayHint>,
973 buffer_snapshot: &BufferSnapshot,
974 cached_excerpt_hints: Option<Arc<RwLock<CachedExcerptHints>>>,
975 visible_hints: &[Inlay],
976) -> Option<ExcerptHintsUpdate> {
977 let mut add_to_cache = Vec::<InlayHint>::new();
978 let mut excerpt_hints_to_persist = HashMap::default();
979 for new_hint in new_excerpt_hints {
980 if !contains_position(&fetch_range, new_hint.position, buffer_snapshot) {
981 continue;
982 }
983 let missing_from_cache = match &cached_excerpt_hints {
984 Some(cached_excerpt_hints) => {
985 let cached_excerpt_hints = cached_excerpt_hints.read();
986 match cached_excerpt_hints
987 .ordered_hints
988 .binary_search_by(|probe| {
989 cached_excerpt_hints.hints_by_id[probe]
990 .position
991 .cmp(&new_hint.position, buffer_snapshot)
992 }) {
993 Ok(ix) => {
994 let mut missing_from_cache = true;
995 for id in &cached_excerpt_hints.ordered_hints[ix..] {
996 let cached_hint = &cached_excerpt_hints.hints_by_id[id];
997 if new_hint
998 .position
999 .cmp(&cached_hint.position, buffer_snapshot)
1000 .is_gt()
1001 {
1002 break;
1003 }
1004 if cached_hint == &new_hint {
1005 excerpt_hints_to_persist.insert(*id, cached_hint.kind);
1006 missing_from_cache = false;
1007 }
1008 }
1009 missing_from_cache
1010 }
1011 Err(_) => true,
1012 }
1013 }
1014 None => true,
1015 };
1016 if missing_from_cache {
1017 add_to_cache.push(new_hint);
1018 }
1019 }
1020
1021 let mut remove_from_visible = Vec::new();
1022 let mut remove_from_cache = HashSet::default();
1023 if invalidate {
1024 remove_from_visible.extend(
1025 visible_hints
1026 .iter()
1027 .filter(|hint| hint.position.excerpt_id == excerpt_id)
1028 .map(|inlay_hint| inlay_hint.id)
1029 .filter(|hint_id| !excerpt_hints_to_persist.contains_key(hint_id)),
1030 );
1031
1032 if let Some(cached_excerpt_hints) = &cached_excerpt_hints {
1033 let cached_excerpt_hints = cached_excerpt_hints.read();
1034 remove_from_cache.extend(
1035 cached_excerpt_hints
1036 .ordered_hints
1037 .iter()
1038 .filter(|cached_inlay_id| {
1039 !excerpt_hints_to_persist.contains_key(cached_inlay_id)
1040 })
1041 .copied(),
1042 );
1043 }
1044 }
1045
1046 if remove_from_visible.is_empty() && remove_from_cache.is_empty() && add_to_cache.is_empty() {
1047 None
1048 } else {
1049 Some(ExcerptHintsUpdate {
1050 excerpt_id,
1051 remove_from_visible,
1052 remove_from_cache,
1053 add_to_cache,
1054 })
1055 }
1056}
1057
1058fn contains_position(
1059 range: &Range<language::Anchor>,
1060 position: language::Anchor,
1061 buffer_snapshot: &BufferSnapshot,
1062) -> bool {
1063 range.start.cmp(&position, buffer_snapshot).is_le()
1064 && range.end.cmp(&position, buffer_snapshot).is_ge()
1065}
1066
1067fn apply_hint_update(
1068 editor: &mut Editor,
1069 new_update: ExcerptHintsUpdate,
1070 query: ExcerptQuery,
1071 invalidate: bool,
1072 buffer_snapshot: BufferSnapshot,
1073 multi_buffer_snapshot: MultiBufferSnapshot,
1074 cx: &mut ViewContext<'_, Editor>,
1075) {
1076 let cached_excerpt_hints = editor
1077 .inlay_hint_cache
1078 .hints
1079 .entry(new_update.excerpt_id)
1080 .or_insert_with(|| {
1081 Arc::new(RwLock::new(CachedExcerptHints {
1082 version: query.cache_version,
1083 buffer_version: buffer_snapshot.version().clone(),
1084 buffer_id: query.buffer_id,
1085 ordered_hints: Vec::new(),
1086 hints_by_id: HashMap::default(),
1087 }))
1088 });
1089 let mut cached_excerpt_hints = cached_excerpt_hints.write();
1090 match query.cache_version.cmp(&cached_excerpt_hints.version) {
1091 cmp::Ordering::Less => return,
1092 cmp::Ordering::Greater | cmp::Ordering::Equal => {
1093 cached_excerpt_hints.version = query.cache_version;
1094 }
1095 }
1096
1097 let mut cached_inlays_changed = !new_update.remove_from_cache.is_empty();
1098 cached_excerpt_hints
1099 .ordered_hints
1100 .retain(|hint_id| !new_update.remove_from_cache.contains(hint_id));
1101 cached_excerpt_hints
1102 .hints_by_id
1103 .retain(|hint_id, _| !new_update.remove_from_cache.contains(hint_id));
1104 let mut splice = InlaySplice {
1105 to_remove: new_update.remove_from_visible,
1106 to_insert: Vec::new(),
1107 };
1108 for new_hint in new_update.add_to_cache {
1109 let insert_position = match cached_excerpt_hints
1110 .ordered_hints
1111 .binary_search_by(|probe| {
1112 cached_excerpt_hints.hints_by_id[probe]
1113 .position
1114 .cmp(&new_hint.position, &buffer_snapshot)
1115 }) {
1116 Ok(i) => {
1117 let mut insert_position = Some(i);
1118 for id in &cached_excerpt_hints.ordered_hints[i..] {
1119 let cached_hint = &cached_excerpt_hints.hints_by_id[id];
1120 if new_hint
1121 .position
1122 .cmp(&cached_hint.position, &buffer_snapshot)
1123 .is_gt()
1124 {
1125 break;
1126 }
1127 if cached_hint.text() == new_hint.text() {
1128 insert_position = None;
1129 break;
1130 }
1131 }
1132 insert_position
1133 }
1134 Err(i) => Some(i),
1135 };
1136
1137 if let Some(insert_position) = insert_position {
1138 let new_inlay_id = post_inc(&mut editor.next_inlay_id);
1139 if editor
1140 .inlay_hint_cache
1141 .allowed_hint_kinds
1142 .contains(&new_hint.kind)
1143 {
1144 let new_hint_position =
1145 multi_buffer_snapshot.anchor_in_excerpt(query.excerpt_id, new_hint.position);
1146 splice
1147 .to_insert
1148 .push(Inlay::hint(new_inlay_id, new_hint_position, &new_hint));
1149 }
1150 let new_id = InlayId::Hint(new_inlay_id);
1151 cached_excerpt_hints.hints_by_id.insert(new_id, new_hint);
1152 cached_excerpt_hints
1153 .ordered_hints
1154 .insert(insert_position, new_id);
1155 cached_inlays_changed = true;
1156 }
1157 }
1158 cached_excerpt_hints.buffer_version = buffer_snapshot.version().clone();
1159 drop(cached_excerpt_hints);
1160
1161 if invalidate {
1162 let mut outdated_excerpt_caches = HashSet::default();
1163 for (excerpt_id, excerpt_hints) in &editor.inlay_hint_cache().hints {
1164 let excerpt_hints = excerpt_hints.read();
1165 if excerpt_hints.buffer_id == query.buffer_id
1166 && excerpt_id != &query.excerpt_id
1167 && buffer_snapshot
1168 .version()
1169 .changed_since(&excerpt_hints.buffer_version)
1170 {
1171 outdated_excerpt_caches.insert(*excerpt_id);
1172 splice
1173 .to_remove
1174 .extend(excerpt_hints.ordered_hints.iter().copied());
1175 }
1176 }
1177 cached_inlays_changed |= !outdated_excerpt_caches.is_empty();
1178 editor
1179 .inlay_hint_cache
1180 .hints
1181 .retain(|excerpt_id, _| !outdated_excerpt_caches.contains(excerpt_id));
1182 }
1183
1184 let InlaySplice {
1185 to_remove,
1186 to_insert,
1187 } = splice;
1188 let displayed_inlays_changed = !to_remove.is_empty() || !to_insert.is_empty();
1189 if cached_inlays_changed || displayed_inlays_changed {
1190 editor.inlay_hint_cache.version += 1;
1191 }
1192 if displayed_inlays_changed {
1193 editor.splice_inlay_hints(to_remove, to_insert, cx)
1194 }
1195}
1196
1197#[cfg(test)]
1198pub mod tests {
1199 use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
1200
1201 use crate::{
1202 scroll::{autoscroll::Autoscroll, scroll_amount::ScrollAmount},
1203 ExcerptRange,
1204 };
1205 use futures::StreamExt;
1206 use gpui::{Context, TestAppContext, View, WindowHandle};
1207 use itertools::Itertools;
1208 use language::{
1209 language_settings::AllLanguageSettingsContent, FakeLspAdapter, Language, LanguageConfig,
1210 };
1211 use lsp::FakeLanguageServer;
1212 use parking_lot::Mutex;
1213 use project::{FakeFs, Project};
1214 use serde_json::json;
1215 use settings::SettingsStore;
1216 use text::{Point, ToPoint};
1217 use workspace::Workspace;
1218
1219 use crate::editor_tests::update_test_language_settings;
1220
1221 use super::*;
1222
1223 // todo!()
1224 #[ignore = "fails due to unimplemented `impl PlatformAtlas for TestAtlas` method"]
1225 #[gpui::test]
1226 async fn test_basic_cache_update_with_duplicate_hints(cx: &mut gpui::TestAppContext) {
1227 let allowed_hint_kinds = HashSet::from_iter([None, Some(InlayHintKind::Type)]);
1228 init_test(cx, |settings| {
1229 settings.defaults.inlay_hints = Some(InlayHintSettings {
1230 enabled: true,
1231 show_type_hints: allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1232 show_parameter_hints: allowed_hint_kinds.contains(&Some(InlayHintKind::Parameter)),
1233 show_other_hints: allowed_hint_kinds.contains(&None),
1234 })
1235 });
1236
1237 let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
1238 let lsp_request_count = Arc::new(AtomicU32::new(0));
1239 fake_server
1240 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1241 let task_lsp_request_count = Arc::clone(&lsp_request_count);
1242 async move {
1243 assert_eq!(
1244 params.text_document.uri,
1245 lsp::Url::from_file_path(file_with_hints).unwrap(),
1246 );
1247 let current_call_id =
1248 Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1249 let mut new_hints = Vec::with_capacity(2 * current_call_id as usize);
1250 for _ in 0..2 {
1251 let mut i = current_call_id;
1252 loop {
1253 new_hints.push(lsp::InlayHint {
1254 position: lsp::Position::new(0, i),
1255 label: lsp::InlayHintLabel::String(i.to_string()),
1256 kind: None,
1257 text_edits: None,
1258 tooltip: None,
1259 padding_left: None,
1260 padding_right: None,
1261 data: None,
1262 });
1263 if i == 0 {
1264 break;
1265 }
1266 i -= 1;
1267 }
1268 }
1269
1270 Ok(Some(new_hints))
1271 }
1272 })
1273 .next()
1274 .await;
1275 cx.executor().run_until_parked();
1276
1277 let mut edits_made = 1;
1278 editor.update(cx, |editor, cx| {
1279 let expected_hints = vec!["0".to_string()];
1280 assert_eq!(
1281 expected_hints,
1282 cached_hint_labels(editor),
1283 "Should get its first hints when opening the editor"
1284 );
1285 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1286 let inlay_cache = editor.inlay_hint_cache();
1287 assert_eq!(
1288 inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
1289 "Cache should use editor settings to get the allowed hint kinds"
1290 );
1291 assert_eq!(
1292 inlay_cache.version, edits_made,
1293 "The editor update the cache version after every cache/view change"
1294 );
1295 });
1296
1297 editor.update(cx, |editor, cx| {
1298 editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
1299 editor.handle_input("some change", cx);
1300 edits_made += 1;
1301 });
1302 cx.executor().run_until_parked();
1303 editor.update(cx, |editor, cx| {
1304 let expected_hints = vec!["0".to_string(), "1".to_string()];
1305 assert_eq!(
1306 expected_hints,
1307 cached_hint_labels(editor),
1308 "Should get new hints after an edit"
1309 );
1310 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1311 let inlay_cache = editor.inlay_hint_cache();
1312 assert_eq!(
1313 inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
1314 "Cache should use editor settings to get the allowed hint kinds"
1315 );
1316 assert_eq!(
1317 inlay_cache.version, edits_made,
1318 "The editor update the cache version after every cache/view change"
1319 );
1320 });
1321
1322 fake_server
1323 .request::<lsp::request::InlayHintRefreshRequest>(())
1324 .await
1325 .expect("inlay refresh request failed");
1326 edits_made += 1;
1327 cx.executor().run_until_parked();
1328 editor.update(cx, |editor, cx| {
1329 let expected_hints = vec!["0".to_string(), "1".to_string(), "2".to_string()];
1330 assert_eq!(
1331 expected_hints,
1332 cached_hint_labels(editor),
1333 "Should get new hints after hint refresh/ request"
1334 );
1335 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1336 let inlay_cache = editor.inlay_hint_cache();
1337 assert_eq!(
1338 inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
1339 "Cache should use editor settings to get the allowed hint kinds"
1340 );
1341 assert_eq!(
1342 inlay_cache.version, edits_made,
1343 "The editor update the cache version after every cache/view change"
1344 );
1345 });
1346 }
1347
1348 // todo!()
1349 #[ignore = "fails due to unimplemented `impl PlatformAtlas for TestAtlas` method"]
1350 #[gpui::test]
1351 async fn test_cache_update_on_lsp_completion_tasks(cx: &mut gpui::TestAppContext) {
1352 init_test(cx, |settings| {
1353 settings.defaults.inlay_hints = Some(InlayHintSettings {
1354 enabled: true,
1355 show_type_hints: true,
1356 show_parameter_hints: true,
1357 show_other_hints: true,
1358 })
1359 });
1360
1361 let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
1362 let lsp_request_count = Arc::new(AtomicU32::new(0));
1363 fake_server
1364 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1365 let task_lsp_request_count = Arc::clone(&lsp_request_count);
1366 async move {
1367 assert_eq!(
1368 params.text_document.uri,
1369 lsp::Url::from_file_path(file_with_hints).unwrap(),
1370 );
1371 let current_call_id =
1372 Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1373 Ok(Some(vec![lsp::InlayHint {
1374 position: lsp::Position::new(0, current_call_id),
1375 label: lsp::InlayHintLabel::String(current_call_id.to_string()),
1376 kind: None,
1377 text_edits: None,
1378 tooltip: None,
1379 padding_left: None,
1380 padding_right: None,
1381 data: None,
1382 }]))
1383 }
1384 })
1385 .next()
1386 .await;
1387 cx.executor().run_until_parked();
1388
1389 let mut edits_made = 1;
1390 editor.update(cx, |editor, cx| {
1391 let expected_hints = vec!["0".to_string()];
1392 assert_eq!(
1393 expected_hints,
1394 cached_hint_labels(editor),
1395 "Should get its first hints when opening the editor"
1396 );
1397 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1398 assert_eq!(
1399 editor.inlay_hint_cache().version,
1400 edits_made,
1401 "The editor update the cache version after every cache/view change"
1402 );
1403 });
1404
1405 let progress_token = "test_progress_token";
1406 fake_server
1407 .request::<lsp::request::WorkDoneProgressCreate>(lsp::WorkDoneProgressCreateParams {
1408 token: lsp::ProgressToken::String(progress_token.to_string()),
1409 })
1410 .await
1411 .expect("work done progress create request failed");
1412 cx.executor().run_until_parked();
1413 fake_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
1414 token: lsp::ProgressToken::String(progress_token.to_string()),
1415 value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::Begin(
1416 lsp::WorkDoneProgressBegin::default(),
1417 )),
1418 });
1419 cx.executor().run_until_parked();
1420
1421 editor.update(cx, |editor, cx| {
1422 let expected_hints = vec!["0".to_string()];
1423 assert_eq!(
1424 expected_hints,
1425 cached_hint_labels(editor),
1426 "Should not update hints while the work task is running"
1427 );
1428 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1429 assert_eq!(
1430 editor.inlay_hint_cache().version,
1431 edits_made,
1432 "Should not update the cache while the work task is running"
1433 );
1434 });
1435
1436 fake_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
1437 token: lsp::ProgressToken::String(progress_token.to_string()),
1438 value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::End(
1439 lsp::WorkDoneProgressEnd::default(),
1440 )),
1441 });
1442 cx.executor().run_until_parked();
1443
1444 edits_made += 1;
1445 editor.update(cx, |editor, cx| {
1446 let expected_hints = vec!["1".to_string()];
1447 assert_eq!(
1448 expected_hints,
1449 cached_hint_labels(editor),
1450 "New hints should be queried after the work task is done"
1451 );
1452 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1453 assert_eq!(
1454 editor.inlay_hint_cache().version,
1455 edits_made,
1456 "Cache version should udpate once after the work task is done"
1457 );
1458 });
1459 }
1460
1461 // todo!()
1462 #[ignore = "fails due to unimplemented `impl PlatformAtlas for TestAtlas` method"]
1463 #[gpui::test]
1464 async fn test_no_hint_updates_for_unrelated_language_files(cx: &mut gpui::TestAppContext) {
1465 init_test(cx, |settings| {
1466 settings.defaults.inlay_hints = Some(InlayHintSettings {
1467 enabled: true,
1468 show_type_hints: true,
1469 show_parameter_hints: true,
1470 show_other_hints: true,
1471 })
1472 });
1473
1474 let fs = FakeFs::new(cx.background_executor.clone());
1475 fs.insert_tree(
1476 "/a",
1477 json!({
1478 "main.rs": "fn main() { a } // and some long comment to ensure inlays are not trimmed out",
1479 "other.md": "Test md file with some text",
1480 }),
1481 )
1482 .await;
1483 let project = Project::test(fs, ["/a".as_ref()], cx).await;
1484
1485 let mut rs_fake_servers = None;
1486 let mut md_fake_servers = None;
1487 for (name, path_suffix) in [("Rust", "rs"), ("Markdown", "md")] {
1488 let mut language = Language::new(
1489 LanguageConfig {
1490 name: name.into(),
1491 path_suffixes: vec![path_suffix.to_string()],
1492 ..Default::default()
1493 },
1494 Some(tree_sitter_rust::language()),
1495 );
1496 let fake_servers = language
1497 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
1498 name,
1499 capabilities: lsp::ServerCapabilities {
1500 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
1501 ..Default::default()
1502 },
1503 ..Default::default()
1504 }))
1505 .await;
1506 match name {
1507 "Rust" => rs_fake_servers = Some(fake_servers),
1508 "Markdown" => md_fake_servers = Some(fake_servers),
1509 _ => unreachable!(),
1510 }
1511 project.update(cx, |project, _| {
1512 project.languages().add(Arc::new(language));
1513 });
1514 }
1515
1516 let rs_buffer = project
1517 .update(cx, |project, cx| {
1518 project.open_local_buffer("/a/main.rs", cx)
1519 })
1520 .await
1521 .unwrap();
1522 cx.executor().run_until_parked();
1523 cx.executor().start_waiting();
1524 let rs_fake_server = rs_fake_servers.unwrap().next().await.unwrap();
1525 let rs_editor =
1526 cx.add_window(|cx| Editor::for_buffer(rs_buffer, Some(project.clone()), cx));
1527 let rs_lsp_request_count = Arc::new(AtomicU32::new(0));
1528 rs_fake_server
1529 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1530 let task_lsp_request_count = Arc::clone(&rs_lsp_request_count);
1531 async move {
1532 assert_eq!(
1533 params.text_document.uri,
1534 lsp::Url::from_file_path("/a/main.rs").unwrap(),
1535 );
1536 let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1537 Ok(Some(vec![lsp::InlayHint {
1538 position: lsp::Position::new(0, i),
1539 label: lsp::InlayHintLabel::String(i.to_string()),
1540 kind: None,
1541 text_edits: None,
1542 tooltip: None,
1543 padding_left: None,
1544 padding_right: None,
1545 data: None,
1546 }]))
1547 }
1548 })
1549 .next()
1550 .await;
1551 cx.executor().run_until_parked();
1552 rs_editor.update(cx, |editor, cx| {
1553 let expected_hints = vec!["0".to_string()];
1554 assert_eq!(
1555 expected_hints,
1556 cached_hint_labels(editor),
1557 "Should get its first hints when opening the editor"
1558 );
1559 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1560 assert_eq!(
1561 editor.inlay_hint_cache().version,
1562 1,
1563 "Rust editor update the cache version after every cache/view change"
1564 );
1565 });
1566
1567 cx.executor().run_until_parked();
1568 let md_buffer = project
1569 .update(cx, |project, cx| {
1570 project.open_local_buffer("/a/other.md", cx)
1571 })
1572 .await
1573 .unwrap();
1574 cx.executor().run_until_parked();
1575 cx.executor().start_waiting();
1576 let md_fake_server = md_fake_servers.unwrap().next().await.unwrap();
1577 let md_editor = cx.add_window(|cx| Editor::for_buffer(md_buffer, Some(project), cx));
1578 let md_lsp_request_count = Arc::new(AtomicU32::new(0));
1579 md_fake_server
1580 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1581 let task_lsp_request_count = Arc::clone(&md_lsp_request_count);
1582 async move {
1583 assert_eq!(
1584 params.text_document.uri,
1585 lsp::Url::from_file_path("/a/other.md").unwrap(),
1586 );
1587 let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1588 Ok(Some(vec![lsp::InlayHint {
1589 position: lsp::Position::new(0, i),
1590 label: lsp::InlayHintLabel::String(i.to_string()),
1591 kind: None,
1592 text_edits: None,
1593 tooltip: None,
1594 padding_left: None,
1595 padding_right: None,
1596 data: None,
1597 }]))
1598 }
1599 })
1600 .next()
1601 .await;
1602 cx.executor().run_until_parked();
1603 md_editor.update(cx, |editor, cx| {
1604 let expected_hints = vec!["0".to_string()];
1605 assert_eq!(
1606 expected_hints,
1607 cached_hint_labels(editor),
1608 "Markdown editor should have a separate verison, repeating Rust editor rules"
1609 );
1610 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1611 assert_eq!(editor.inlay_hint_cache().version, 1);
1612 });
1613
1614 rs_editor.update(cx, |editor, cx| {
1615 editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
1616 editor.handle_input("some rs change", cx);
1617 });
1618 cx.executor().run_until_parked();
1619 rs_editor.update(cx, |editor, cx| {
1620 let expected_hints = vec!["1".to_string()];
1621 assert_eq!(
1622 expected_hints,
1623 cached_hint_labels(editor),
1624 "Rust inlay cache should change after the edit"
1625 );
1626 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1627 assert_eq!(
1628 editor.inlay_hint_cache().version,
1629 2,
1630 "Every time hint cache changes, cache version should be incremented"
1631 );
1632 });
1633 md_editor.update(cx, |editor, cx| {
1634 let expected_hints = vec!["0".to_string()];
1635 assert_eq!(
1636 expected_hints,
1637 cached_hint_labels(editor),
1638 "Markdown editor should not be affected by Rust editor changes"
1639 );
1640 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1641 assert_eq!(editor.inlay_hint_cache().version, 1);
1642 });
1643
1644 md_editor.update(cx, |editor, cx| {
1645 editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
1646 editor.handle_input("some md change", cx);
1647 });
1648 cx.executor().run_until_parked();
1649 md_editor.update(cx, |editor, cx| {
1650 let expected_hints = vec!["1".to_string()];
1651 assert_eq!(
1652 expected_hints,
1653 cached_hint_labels(editor),
1654 "Rust editor should not be affected by Markdown editor changes"
1655 );
1656 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1657 assert_eq!(editor.inlay_hint_cache().version, 2);
1658 });
1659 rs_editor.update(cx, |editor, cx| {
1660 let expected_hints = vec!["1".to_string()];
1661 assert_eq!(
1662 expected_hints,
1663 cached_hint_labels(editor),
1664 "Markdown editor should also change independently"
1665 );
1666 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
1667 assert_eq!(editor.inlay_hint_cache().version, 2);
1668 });
1669 }
1670
1671 // todo!()
1672 #[ignore = "fails due to unimplemented `impl PlatformAtlas for TestAtlas` method"]
1673 #[gpui::test]
1674 async fn test_hint_setting_changes(cx: &mut gpui::TestAppContext) {
1675 let allowed_hint_kinds = HashSet::from_iter([None, Some(InlayHintKind::Type)]);
1676 init_test(cx, |settings| {
1677 settings.defaults.inlay_hints = Some(InlayHintSettings {
1678 enabled: true,
1679 show_type_hints: allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1680 show_parameter_hints: allowed_hint_kinds.contains(&Some(InlayHintKind::Parameter)),
1681 show_other_hints: allowed_hint_kinds.contains(&None),
1682 })
1683 });
1684
1685 let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
1686 let lsp_request_count = Arc::new(AtomicU32::new(0));
1687 let another_lsp_request_count = Arc::clone(&lsp_request_count);
1688 fake_server
1689 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1690 let task_lsp_request_count = Arc::clone(&another_lsp_request_count);
1691 async move {
1692 Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst);
1693 assert_eq!(
1694 params.text_document.uri,
1695 lsp::Url::from_file_path(file_with_hints).unwrap(),
1696 );
1697 Ok(Some(vec![
1698 lsp::InlayHint {
1699 position: lsp::Position::new(0, 1),
1700 label: lsp::InlayHintLabel::String("type hint".to_string()),
1701 kind: Some(lsp::InlayHintKind::TYPE),
1702 text_edits: None,
1703 tooltip: None,
1704 padding_left: None,
1705 padding_right: None,
1706 data: None,
1707 },
1708 lsp::InlayHint {
1709 position: lsp::Position::new(0, 2),
1710 label: lsp::InlayHintLabel::String("parameter hint".to_string()),
1711 kind: Some(lsp::InlayHintKind::PARAMETER),
1712 text_edits: None,
1713 tooltip: None,
1714 padding_left: None,
1715 padding_right: None,
1716 data: None,
1717 },
1718 lsp::InlayHint {
1719 position: lsp::Position::new(0, 3),
1720 label: lsp::InlayHintLabel::String("other hint".to_string()),
1721 kind: None,
1722 text_edits: None,
1723 tooltip: None,
1724 padding_left: None,
1725 padding_right: None,
1726 data: None,
1727 },
1728 ]))
1729 }
1730 })
1731 .next()
1732 .await;
1733 cx.executor().run_until_parked();
1734
1735 let mut edits_made = 1;
1736 editor.update(cx, |editor, cx| {
1737 assert_eq!(
1738 lsp_request_count.load(Ordering::Relaxed),
1739 1,
1740 "Should query new hints once"
1741 );
1742 assert_eq!(
1743 vec![
1744 "other hint".to_string(),
1745 "parameter hint".to_string(),
1746 "type hint".to_string(),
1747 ],
1748 cached_hint_labels(editor),
1749 "Should get its first hints when opening the editor"
1750 );
1751 assert_eq!(
1752 vec!["other hint".to_string(), "type hint".to_string()],
1753 visible_hint_labels(editor, cx)
1754 );
1755 let inlay_cache = editor.inlay_hint_cache();
1756 assert_eq!(
1757 inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
1758 "Cache should use editor settings to get the allowed hint kinds"
1759 );
1760 assert_eq!(
1761 inlay_cache.version, edits_made,
1762 "The editor update the cache version after every cache/view change"
1763 );
1764 });
1765
1766 fake_server
1767 .request::<lsp::request::InlayHintRefreshRequest>(())
1768 .await
1769 .expect("inlay refresh request failed");
1770 cx.executor().run_until_parked();
1771 editor.update(cx, |editor, cx| {
1772 assert_eq!(
1773 lsp_request_count.load(Ordering::Relaxed),
1774 2,
1775 "Should load new hints twice"
1776 );
1777 assert_eq!(
1778 vec![
1779 "other hint".to_string(),
1780 "parameter hint".to_string(),
1781 "type hint".to_string(),
1782 ],
1783 cached_hint_labels(editor),
1784 "Cached hints should not change due to allowed hint kinds settings update"
1785 );
1786 assert_eq!(
1787 vec!["other hint".to_string(), "type hint".to_string()],
1788 visible_hint_labels(editor, cx)
1789 );
1790 assert_eq!(
1791 editor.inlay_hint_cache().version,
1792 edits_made,
1793 "Should not update cache version due to new loaded hints being the same"
1794 );
1795 });
1796
1797 for (new_allowed_hint_kinds, expected_visible_hints) in [
1798 (HashSet::from_iter([None]), vec!["other hint".to_string()]),
1799 (
1800 HashSet::from_iter([Some(InlayHintKind::Type)]),
1801 vec!["type hint".to_string()],
1802 ),
1803 (
1804 HashSet::from_iter([Some(InlayHintKind::Parameter)]),
1805 vec!["parameter hint".to_string()],
1806 ),
1807 (
1808 HashSet::from_iter([None, Some(InlayHintKind::Type)]),
1809 vec!["other hint".to_string(), "type hint".to_string()],
1810 ),
1811 (
1812 HashSet::from_iter([None, Some(InlayHintKind::Parameter)]),
1813 vec!["other hint".to_string(), "parameter hint".to_string()],
1814 ),
1815 (
1816 HashSet::from_iter([Some(InlayHintKind::Type), Some(InlayHintKind::Parameter)]),
1817 vec!["parameter hint".to_string(), "type hint".to_string()],
1818 ),
1819 (
1820 HashSet::from_iter([
1821 None,
1822 Some(InlayHintKind::Type),
1823 Some(InlayHintKind::Parameter),
1824 ]),
1825 vec![
1826 "other hint".to_string(),
1827 "parameter hint".to_string(),
1828 "type hint".to_string(),
1829 ],
1830 ),
1831 ] {
1832 edits_made += 1;
1833 update_test_language_settings(cx, |settings| {
1834 settings.defaults.inlay_hints = Some(InlayHintSettings {
1835 enabled: true,
1836 show_type_hints: new_allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1837 show_parameter_hints: new_allowed_hint_kinds
1838 .contains(&Some(InlayHintKind::Parameter)),
1839 show_other_hints: new_allowed_hint_kinds.contains(&None),
1840 })
1841 });
1842 cx.executor().run_until_parked();
1843 editor.update(cx, |editor, cx| {
1844 assert_eq!(
1845 lsp_request_count.load(Ordering::Relaxed),
1846 2,
1847 "Should not load new hints on allowed hint kinds change for hint kinds {new_allowed_hint_kinds:?}"
1848 );
1849 assert_eq!(
1850 vec![
1851 "other hint".to_string(),
1852 "parameter hint".to_string(),
1853 "type hint".to_string(),
1854 ],
1855 cached_hint_labels(editor),
1856 "Should get its cached hints unchanged after the settings change for hint kinds {new_allowed_hint_kinds:?}"
1857 );
1858 assert_eq!(
1859 expected_visible_hints,
1860 visible_hint_labels(editor, cx),
1861 "Should get its visible hints filtered after the settings change for hint kinds {new_allowed_hint_kinds:?}"
1862 );
1863 let inlay_cache = editor.inlay_hint_cache();
1864 assert_eq!(
1865 inlay_cache.allowed_hint_kinds, new_allowed_hint_kinds,
1866 "Cache should use editor settings to get the allowed hint kinds for hint kinds {new_allowed_hint_kinds:?}"
1867 );
1868 assert_eq!(
1869 inlay_cache.version, edits_made,
1870 "The editor should update the cache version after every cache/view change for hint kinds {new_allowed_hint_kinds:?} due to visible hints change"
1871 );
1872 });
1873 }
1874
1875 edits_made += 1;
1876 let another_allowed_hint_kinds = HashSet::from_iter([Some(InlayHintKind::Type)]);
1877 update_test_language_settings(cx, |settings| {
1878 settings.defaults.inlay_hints = Some(InlayHintSettings {
1879 enabled: false,
1880 show_type_hints: another_allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1881 show_parameter_hints: another_allowed_hint_kinds
1882 .contains(&Some(InlayHintKind::Parameter)),
1883 show_other_hints: another_allowed_hint_kinds.contains(&None),
1884 })
1885 });
1886 cx.executor().run_until_parked();
1887 editor.update(cx, |editor, cx| {
1888 assert_eq!(
1889 lsp_request_count.load(Ordering::Relaxed),
1890 2,
1891 "Should not load new hints when hints got disabled"
1892 );
1893 assert!(
1894 cached_hint_labels(editor).is_empty(),
1895 "Should clear the cache when hints got disabled"
1896 );
1897 assert!(
1898 visible_hint_labels(editor, cx).is_empty(),
1899 "Should clear visible hints when hints got disabled"
1900 );
1901 let inlay_cache = editor.inlay_hint_cache();
1902 assert_eq!(
1903 inlay_cache.allowed_hint_kinds, another_allowed_hint_kinds,
1904 "Should update its allowed hint kinds even when hints got disabled"
1905 );
1906 assert_eq!(
1907 inlay_cache.version, edits_made,
1908 "The editor should update the cache version after hints got disabled"
1909 );
1910 });
1911
1912 fake_server
1913 .request::<lsp::request::InlayHintRefreshRequest>(())
1914 .await
1915 .expect("inlay refresh request failed");
1916 cx.executor().run_until_parked();
1917 editor.update(cx, |editor, cx| {
1918 assert_eq!(
1919 lsp_request_count.load(Ordering::Relaxed),
1920 2,
1921 "Should not load new hints when they got disabled"
1922 );
1923 assert!(cached_hint_labels(editor).is_empty());
1924 assert!(visible_hint_labels(editor, cx).is_empty());
1925 assert_eq!(
1926 editor.inlay_hint_cache().version, edits_made,
1927 "The editor should not update the cache version after /refresh query without updates"
1928 );
1929 });
1930
1931 let final_allowed_hint_kinds = HashSet::from_iter([Some(InlayHintKind::Parameter)]);
1932 edits_made += 1;
1933 update_test_language_settings(cx, |settings| {
1934 settings.defaults.inlay_hints = Some(InlayHintSettings {
1935 enabled: true,
1936 show_type_hints: final_allowed_hint_kinds.contains(&Some(InlayHintKind::Type)),
1937 show_parameter_hints: final_allowed_hint_kinds
1938 .contains(&Some(InlayHintKind::Parameter)),
1939 show_other_hints: final_allowed_hint_kinds.contains(&None),
1940 })
1941 });
1942 cx.executor().run_until_parked();
1943 editor.update(cx, |editor, cx| {
1944 assert_eq!(
1945 lsp_request_count.load(Ordering::Relaxed),
1946 3,
1947 "Should query for new hints when they got reenabled"
1948 );
1949 assert_eq!(
1950 vec![
1951 "other hint".to_string(),
1952 "parameter hint".to_string(),
1953 "type hint".to_string(),
1954 ],
1955 cached_hint_labels(editor),
1956 "Should get its cached hints fully repopulated after the hints got reenabled"
1957 );
1958 assert_eq!(
1959 vec!["parameter hint".to_string()],
1960 visible_hint_labels(editor, cx),
1961 "Should get its visible hints repopulated and filtered after the h"
1962 );
1963 let inlay_cache = editor.inlay_hint_cache();
1964 assert_eq!(
1965 inlay_cache.allowed_hint_kinds, final_allowed_hint_kinds,
1966 "Cache should update editor settings when hints got reenabled"
1967 );
1968 assert_eq!(
1969 inlay_cache.version, edits_made,
1970 "Cache should update its version after hints got reenabled"
1971 );
1972 });
1973
1974 fake_server
1975 .request::<lsp::request::InlayHintRefreshRequest>(())
1976 .await
1977 .expect("inlay refresh request failed");
1978 cx.executor().run_until_parked();
1979 editor.update(cx, |editor, cx| {
1980 assert_eq!(
1981 lsp_request_count.load(Ordering::Relaxed),
1982 4,
1983 "Should query for new hints again"
1984 );
1985 assert_eq!(
1986 vec![
1987 "other hint".to_string(),
1988 "parameter hint".to_string(),
1989 "type hint".to_string(),
1990 ],
1991 cached_hint_labels(editor),
1992 );
1993 assert_eq!(
1994 vec!["parameter hint".to_string()],
1995 visible_hint_labels(editor, cx),
1996 );
1997 assert_eq!(editor.inlay_hint_cache().version, edits_made);
1998 });
1999 }
2000
2001 // todo!()
2002 #[ignore = "fails due to unimplemented `impl PlatformAtlas for TestAtlas` method"]
2003 #[gpui::test]
2004 async fn test_hint_request_cancellation(cx: &mut gpui::TestAppContext) {
2005 init_test(cx, |settings| {
2006 settings.defaults.inlay_hints = Some(InlayHintSettings {
2007 enabled: true,
2008 show_type_hints: true,
2009 show_parameter_hints: true,
2010 show_other_hints: true,
2011 })
2012 });
2013
2014 let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
2015 let fake_server = Arc::new(fake_server);
2016 let lsp_request_count = Arc::new(AtomicU32::new(0));
2017 let another_lsp_request_count = Arc::clone(&lsp_request_count);
2018 fake_server
2019 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
2020 let task_lsp_request_count = Arc::clone(&another_lsp_request_count);
2021 async move {
2022 let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst) + 1;
2023 assert_eq!(
2024 params.text_document.uri,
2025 lsp::Url::from_file_path(file_with_hints).unwrap(),
2026 );
2027 Ok(Some(vec![lsp::InlayHint {
2028 position: lsp::Position::new(0, i),
2029 label: lsp::InlayHintLabel::String(i.to_string()),
2030 kind: None,
2031 text_edits: None,
2032 tooltip: None,
2033 padding_left: None,
2034 padding_right: None,
2035 data: None,
2036 }]))
2037 }
2038 })
2039 .next()
2040 .await;
2041
2042 let mut expected_changes = Vec::new();
2043 for change_after_opening in [
2044 "initial change #1",
2045 "initial change #2",
2046 "initial change #3",
2047 ] {
2048 editor.update(cx, |editor, cx| {
2049 editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
2050 editor.handle_input(change_after_opening, cx);
2051 });
2052 expected_changes.push(change_after_opening);
2053 }
2054
2055 cx.executor().run_until_parked();
2056
2057 editor.update(cx, |editor, cx| {
2058 let current_text = editor.text(cx);
2059 for change in &expected_changes {
2060 assert!(
2061 current_text.contains(change),
2062 "Should apply all changes made"
2063 );
2064 }
2065 assert_eq!(
2066 lsp_request_count.load(Ordering::Relaxed),
2067 2,
2068 "Should query new hints twice: for editor init and for the last edit that interrupted all others"
2069 );
2070 let expected_hints = vec!["2".to_string()];
2071 assert_eq!(
2072 expected_hints,
2073 cached_hint_labels(editor),
2074 "Should get hints from the last edit landed only"
2075 );
2076 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2077 assert_eq!(
2078 editor.inlay_hint_cache().version, 1,
2079 "Only one update should be registered in the cache after all cancellations"
2080 );
2081 });
2082
2083 let mut edits = Vec::new();
2084 for async_later_change in [
2085 "another change #1",
2086 "another change #2",
2087 "another change #3",
2088 ] {
2089 expected_changes.push(async_later_change);
2090 let task_editor = editor.clone();
2091 edits.push(cx.spawn(|mut cx| async move {
2092 task_editor.update(&mut cx, |editor, cx| {
2093 editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
2094 editor.handle_input(async_later_change, cx);
2095 });
2096 }));
2097 }
2098 let _ = future::join_all(edits).await;
2099 cx.executor().run_until_parked();
2100
2101 editor.update(cx, |editor, cx| {
2102 let current_text = editor.text(cx);
2103 for change in &expected_changes {
2104 assert!(
2105 current_text.contains(change),
2106 "Should apply all changes made"
2107 );
2108 }
2109 assert_eq!(
2110 lsp_request_count.load(Ordering::SeqCst),
2111 3,
2112 "Should query new hints one more time, for the last edit only"
2113 );
2114 let expected_hints = vec!["3".to_string()];
2115 assert_eq!(
2116 expected_hints,
2117 cached_hint_labels(editor),
2118 "Should get hints from the last edit landed only"
2119 );
2120 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2121 assert_eq!(
2122 editor.inlay_hint_cache().version,
2123 2,
2124 "Should update the cache version once more, for the new change"
2125 );
2126 });
2127 }
2128
2129 // todo!()
2130 #[ignore = "fails due to unimplemented `impl PlatformAtlas for TestAtlas` method"]
2131 #[gpui::test(iterations = 10)]
2132 async fn test_large_buffer_inlay_requests_split(cx: &mut gpui::TestAppContext) {
2133 init_test(cx, |settings| {
2134 settings.defaults.inlay_hints = Some(InlayHintSettings {
2135 enabled: true,
2136 show_type_hints: true,
2137 show_parameter_hints: true,
2138 show_other_hints: true,
2139 })
2140 });
2141
2142 let mut language = Language::new(
2143 LanguageConfig {
2144 name: "Rust".into(),
2145 path_suffixes: vec!["rs".to_string()],
2146 ..Default::default()
2147 },
2148 Some(tree_sitter_rust::language()),
2149 );
2150 let mut fake_servers = language
2151 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
2152 capabilities: lsp::ServerCapabilities {
2153 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
2154 ..Default::default()
2155 },
2156 ..Default::default()
2157 }))
2158 .await;
2159 let fs = FakeFs::new(cx.background_executor.clone());
2160 fs.insert_tree(
2161 "/a",
2162 json!({
2163 "main.rs": format!("fn main() {{\n{}\n}}", "let i = 5;\n".repeat(500)),
2164 "other.rs": "// Test file",
2165 }),
2166 )
2167 .await;
2168 let project = Project::test(fs, ["/a".as_ref()], cx).await;
2169 project.update(cx, |project, _| project.languages().add(Arc::new(language)));
2170 let buffer = project
2171 .update(cx, |project, cx| {
2172 project.open_local_buffer("/a/main.rs", cx)
2173 })
2174 .await
2175 .unwrap();
2176 cx.executor().run_until_parked();
2177 cx.executor().start_waiting();
2178 let fake_server = fake_servers.next().await.unwrap();
2179 let editor = cx.add_window(|cx| Editor::for_buffer(buffer, Some(project), cx));
2180 let lsp_request_ranges = Arc::new(Mutex::new(Vec::new()));
2181 let lsp_request_count = Arc::new(AtomicUsize::new(0));
2182 let closure_lsp_request_ranges = Arc::clone(&lsp_request_ranges);
2183 let closure_lsp_request_count = Arc::clone(&lsp_request_count);
2184 fake_server
2185 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
2186 let task_lsp_request_ranges = Arc::clone(&closure_lsp_request_ranges);
2187 let task_lsp_request_count = Arc::clone(&closure_lsp_request_count);
2188 async move {
2189 assert_eq!(
2190 params.text_document.uri,
2191 lsp::Url::from_file_path("/a/main.rs").unwrap(),
2192 );
2193
2194 task_lsp_request_ranges.lock().push(params.range);
2195 let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::Release) + 1;
2196 Ok(Some(vec![lsp::InlayHint {
2197 position: params.range.end,
2198 label: lsp::InlayHintLabel::String(i.to_string()),
2199 kind: None,
2200 text_edits: None,
2201 tooltip: None,
2202 padding_left: None,
2203 padding_right: None,
2204 data: None,
2205 }]))
2206 }
2207 })
2208 .next()
2209 .await;
2210
2211 fn editor_visible_range(
2212 editor: &WindowHandle<Editor>,
2213 cx: &mut gpui::TestAppContext,
2214 ) -> Range<Point> {
2215 let ranges = editor
2216 .update(cx, |editor, cx| editor.excerpt_visible_offsets(None, cx))
2217 .unwrap();
2218 assert_eq!(
2219 ranges.len(),
2220 1,
2221 "Single buffer should produce a single excerpt with visible range"
2222 );
2223 let (_, (excerpt_buffer, _, excerpt_visible_range)) =
2224 ranges.into_iter().next().unwrap();
2225 excerpt_buffer.update(cx, |buffer, _| {
2226 let snapshot = buffer.snapshot();
2227 let start = buffer
2228 .anchor_before(excerpt_visible_range.start)
2229 .to_point(&snapshot);
2230 let end = buffer
2231 .anchor_after(excerpt_visible_range.end)
2232 .to_point(&snapshot);
2233 start..end
2234 })
2235 }
2236
2237 // in large buffers, requests are made for more than visible range of a buffer.
2238 // invisible parts are queried later, to avoid excessive requests on quick typing.
2239 // wait the timeout needed to get all requests.
2240 cx.executor().advance_clock(Duration::from_millis(
2241 INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2242 ));
2243 cx.executor().run_until_parked();
2244 let initial_visible_range = editor_visible_range(&editor, cx);
2245 let lsp_initial_visible_range = lsp::Range::new(
2246 lsp::Position::new(
2247 initial_visible_range.start.row,
2248 initial_visible_range.start.column,
2249 ),
2250 lsp::Position::new(
2251 initial_visible_range.end.row,
2252 initial_visible_range.end.column,
2253 ),
2254 );
2255 let expected_initial_query_range_end =
2256 lsp::Position::new(initial_visible_range.end.row * 2, 2);
2257 let mut expected_invisible_query_start = lsp_initial_visible_range.end;
2258 expected_invisible_query_start.character += 1;
2259 editor.update(cx, |editor, cx| {
2260 let ranges = lsp_request_ranges.lock().drain(..).collect::<Vec<_>>();
2261 assert_eq!(ranges.len(), 2,
2262 "When scroll is at the edge of a big document, its visible part and the same range further should be queried in order, but got: {ranges:?}");
2263 let visible_query_range = &ranges[0];
2264 assert_eq!(visible_query_range.start, lsp_initial_visible_range.start);
2265 assert_eq!(visible_query_range.end, lsp_initial_visible_range.end);
2266 let invisible_query_range = &ranges[1];
2267
2268 assert_eq!(invisible_query_range.start, expected_invisible_query_start, "Should initially query visible edge of the document");
2269 assert_eq!(invisible_query_range.end, expected_initial_query_range_end, "Should initially query visible edge of the document");
2270
2271 let requests_count = lsp_request_count.load(Ordering::Acquire);
2272 assert_eq!(requests_count, 2, "Visible + invisible request");
2273 let expected_hints = vec!["1".to_string(), "2".to_string()];
2274 assert_eq!(
2275 expected_hints,
2276 cached_hint_labels(editor),
2277 "Should have hints from both LSP requests made for a big file"
2278 );
2279 assert_eq!(expected_hints, visible_hint_labels(editor, cx), "Should display only hints from the visible range");
2280 assert_eq!(
2281 editor.inlay_hint_cache().version, requests_count,
2282 "LSP queries should've bumped the cache version"
2283 );
2284 });
2285
2286 editor.update(cx, |editor, cx| {
2287 editor.scroll_screen(&ScrollAmount::Page(1.0), cx);
2288 editor.scroll_screen(&ScrollAmount::Page(1.0), cx);
2289 });
2290 cx.executor().advance_clock(Duration::from_millis(
2291 INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2292 ));
2293 cx.executor().run_until_parked();
2294 let visible_range_after_scrolls = editor_visible_range(&editor, cx);
2295 let visible_line_count = editor
2296 .update(cx, |editor, _| editor.visible_line_count().unwrap())
2297 .unwrap();
2298 let selection_in_cached_range = editor
2299 .update(cx, |editor, cx| {
2300 let ranges = lsp_request_ranges
2301 .lock()
2302 .drain(..)
2303 .sorted_by_key(|r| r.start)
2304 .collect::<Vec<_>>();
2305 assert_eq!(
2306 ranges.len(),
2307 2,
2308 "Should query 2 ranges after both scrolls, but got: {ranges:?}"
2309 );
2310 let first_scroll = &ranges[0];
2311 let second_scroll = &ranges[1];
2312 assert_eq!(
2313 first_scroll.end, second_scroll.start,
2314 "Should query 2 adjacent ranges after the scrolls, but got: {ranges:?}"
2315 );
2316 assert_eq!(
2317 first_scroll.start, expected_initial_query_range_end,
2318 "First scroll should start the query right after the end of the original scroll",
2319 );
2320 assert_eq!(
2321 second_scroll.end,
2322 lsp::Position::new(
2323 visible_range_after_scrolls.end.row
2324 + visible_line_count.ceil() as u32,
2325 1,
2326 ),
2327 "Second scroll should query one more screen down after the end of the visible range"
2328 );
2329
2330 let lsp_requests = lsp_request_count.load(Ordering::Acquire);
2331 assert_eq!(lsp_requests, 4, "Should query for hints after every scroll");
2332 let expected_hints = vec![
2333 "1".to_string(),
2334 "2".to_string(),
2335 "3".to_string(),
2336 "4".to_string(),
2337 ];
2338 assert_eq!(
2339 expected_hints,
2340 cached_hint_labels(editor),
2341 "Should have hints from the new LSP response after the edit"
2342 );
2343 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2344 assert_eq!(
2345 editor.inlay_hint_cache().version,
2346 lsp_requests,
2347 "Should update the cache for every LSP response with hints added"
2348 );
2349
2350 let mut selection_in_cached_range = visible_range_after_scrolls.end;
2351 selection_in_cached_range.row -= visible_line_count.ceil() as u32;
2352 selection_in_cached_range
2353 })
2354 .unwrap();
2355
2356 editor.update(cx, |editor, cx| {
2357 editor.change_selections(Some(Autoscroll::center()), cx, |s| {
2358 s.select_ranges([selection_in_cached_range..selection_in_cached_range])
2359 });
2360 });
2361 cx.executor().advance_clock(Duration::from_millis(
2362 INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2363 ));
2364 cx.executor().run_until_parked();
2365 editor.update(cx, |_, _| {
2366 let ranges = lsp_request_ranges
2367 .lock()
2368 .drain(..)
2369 .sorted_by_key(|r| r.start)
2370 .collect::<Vec<_>>();
2371 assert!(ranges.is_empty(), "No new ranges or LSP queries should be made after returning to the selection with cached hints");
2372 assert_eq!(lsp_request_count.load(Ordering::Acquire), 4);
2373 });
2374
2375 editor.update(cx, |editor, cx| {
2376 editor.handle_input("++++more text++++", cx);
2377 });
2378 cx.executor().advance_clock(Duration::from_millis(
2379 INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2380 ));
2381 cx.executor().run_until_parked();
2382 editor.update(cx, |editor, cx| {
2383 let mut ranges = lsp_request_ranges.lock().drain(..).collect::<Vec<_>>();
2384 ranges.sort_by_key(|r| r.start);
2385
2386 assert_eq!(ranges.len(), 3,
2387 "On edit, should scroll to selection and query a range around it: visible + same range above and below. Instead, got query ranges {ranges:?}");
2388 let above_query_range = &ranges[0];
2389 let visible_query_range = &ranges[1];
2390 let below_query_range = &ranges[2];
2391 assert!(above_query_range.end.character < visible_query_range.start.character || above_query_range.end.line + 1 == visible_query_range.start.line,
2392 "Above range {above_query_range:?} should be before visible range {visible_query_range:?}");
2393 assert!(visible_query_range.end.character < below_query_range.start.character || visible_query_range.end.line + 1 == below_query_range.start.line,
2394 "Visible range {visible_query_range:?} should be before below range {below_query_range:?}");
2395 assert!(above_query_range.start.line < selection_in_cached_range.row,
2396 "Hints should be queried with the selected range after the query range start");
2397 assert!(below_query_range.end.line > selection_in_cached_range.row,
2398 "Hints should be queried with the selected range before the query range end");
2399 assert!(above_query_range.start.line <= selection_in_cached_range.row - (visible_line_count * 3.0 / 2.0) as u32,
2400 "Hints query range should contain one more screen before");
2401 assert!(below_query_range.end.line >= selection_in_cached_range.row + (visible_line_count * 3.0 / 2.0) as u32,
2402 "Hints query range should contain one more screen after");
2403
2404 let lsp_requests = lsp_request_count.load(Ordering::Acquire);
2405 assert_eq!(lsp_requests, 7, "There should be a visible range and two ranges above and below it queried");
2406 let expected_hints = vec!["5".to_string(), "6".to_string(), "7".to_string()];
2407 assert_eq!(expected_hints, cached_hint_labels(editor),
2408 "Should have hints from the new LSP response after the edit");
2409 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2410 assert_eq!(editor.inlay_hint_cache().version, lsp_requests, "Should update the cache for every LSP response with hints added");
2411 });
2412 }
2413
2414 // todo!()
2415 #[ignore = "fails due to text.rs `measurement has not been performed` error"]
2416 #[gpui::test(iterations = 10)]
2417 async fn test_multiple_excerpts_large_multibuffer(cx: &mut gpui::TestAppContext) {
2418 init_test(cx, |settings| {
2419 settings.defaults.inlay_hints = Some(InlayHintSettings {
2420 enabled: true,
2421 show_type_hints: true,
2422 show_parameter_hints: true,
2423 show_other_hints: true,
2424 })
2425 });
2426
2427 let mut language = Language::new(
2428 LanguageConfig {
2429 name: "Rust".into(),
2430 path_suffixes: vec!["rs".to_string()],
2431 ..Default::default()
2432 },
2433 Some(tree_sitter_rust::language()),
2434 );
2435 let mut fake_servers = language
2436 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
2437 capabilities: lsp::ServerCapabilities {
2438 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
2439 ..Default::default()
2440 },
2441 ..Default::default()
2442 }))
2443 .await;
2444 let language = Arc::new(language);
2445 let fs = FakeFs::new(cx.background_executor.clone());
2446 fs.insert_tree(
2447 "/a",
2448 json!({
2449 "main.rs": format!("fn main() {{\n{}\n}}", (0..501).map(|i| format!("let i = {i};\n")).collect::<Vec<_>>().join("")),
2450 "other.rs": format!("fn main() {{\n{}\n}}", (0..501).map(|j| format!("let j = {j};\n")).collect::<Vec<_>>().join("")),
2451 }),
2452 )
2453 .await;
2454 let project = Project::test(fs, ["/a".as_ref()], cx).await;
2455 project.update(cx, |project, _| {
2456 project.languages().add(Arc::clone(&language))
2457 });
2458 let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2459 let worktree_id = workspace
2460 .update(cx, |workspace, cx| {
2461 workspace.project().read_with(cx, |project, cx| {
2462 project.worktrees().next().unwrap().read(cx).id()
2463 })
2464 })
2465 .unwrap();
2466
2467 let buffer_1 = project
2468 .update(cx, |project, cx| {
2469 project.open_buffer((worktree_id, "main.rs"), cx)
2470 })
2471 .await
2472 .unwrap();
2473 let buffer_2 = project
2474 .update(cx, |project, cx| {
2475 project.open_buffer((worktree_id, "other.rs"), cx)
2476 })
2477 .await
2478 .unwrap();
2479 let multibuffer = cx.build_model(|cx| {
2480 let mut multibuffer = MultiBuffer::new(0);
2481 multibuffer.push_excerpts(
2482 buffer_1.clone(),
2483 [
2484 ExcerptRange {
2485 context: Point::new(0, 0)..Point::new(2, 0),
2486 primary: None,
2487 },
2488 ExcerptRange {
2489 context: Point::new(4, 0)..Point::new(11, 0),
2490 primary: None,
2491 },
2492 ExcerptRange {
2493 context: Point::new(22, 0)..Point::new(33, 0),
2494 primary: None,
2495 },
2496 ExcerptRange {
2497 context: Point::new(44, 0)..Point::new(55, 0),
2498 primary: None,
2499 },
2500 ExcerptRange {
2501 context: Point::new(56, 0)..Point::new(66, 0),
2502 primary: None,
2503 },
2504 ExcerptRange {
2505 context: Point::new(67, 0)..Point::new(77, 0),
2506 primary: None,
2507 },
2508 ],
2509 cx,
2510 );
2511 multibuffer.push_excerpts(
2512 buffer_2.clone(),
2513 [
2514 ExcerptRange {
2515 context: Point::new(0, 1)..Point::new(2, 1),
2516 primary: None,
2517 },
2518 ExcerptRange {
2519 context: Point::new(4, 1)..Point::new(11, 1),
2520 primary: None,
2521 },
2522 ExcerptRange {
2523 context: Point::new(22, 1)..Point::new(33, 1),
2524 primary: None,
2525 },
2526 ExcerptRange {
2527 context: Point::new(44, 1)..Point::new(55, 1),
2528 primary: None,
2529 },
2530 ExcerptRange {
2531 context: Point::new(56, 1)..Point::new(66, 1),
2532 primary: None,
2533 },
2534 ExcerptRange {
2535 context: Point::new(67, 1)..Point::new(77, 1),
2536 primary: None,
2537 },
2538 ],
2539 cx,
2540 );
2541 multibuffer
2542 });
2543
2544 cx.executor().run_until_parked();
2545 let editor =
2546 cx.add_window(|cx| Editor::for_multibuffer(multibuffer, Some(project.clone()), cx));
2547 let editor_edited = Arc::new(AtomicBool::new(false));
2548 let fake_server = fake_servers.next().await.unwrap();
2549 let closure_editor_edited = Arc::clone(&editor_edited);
2550 fake_server
2551 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
2552 let task_editor_edited = Arc::clone(&closure_editor_edited);
2553 async move {
2554 let hint_text = if params.text_document.uri
2555 == lsp::Url::from_file_path("/a/main.rs").unwrap()
2556 {
2557 "main hint"
2558 } else if params.text_document.uri
2559 == lsp::Url::from_file_path("/a/other.rs").unwrap()
2560 {
2561 "other hint"
2562 } else {
2563 panic!("unexpected uri: {:?}", params.text_document.uri);
2564 };
2565
2566 // one hint per excerpt
2567 let positions = [
2568 lsp::Position::new(0, 2),
2569 lsp::Position::new(4, 2),
2570 lsp::Position::new(22, 2),
2571 lsp::Position::new(44, 2),
2572 lsp::Position::new(56, 2),
2573 lsp::Position::new(67, 2),
2574 ];
2575 let out_of_range_hint = lsp::InlayHint {
2576 position: lsp::Position::new(
2577 params.range.start.line + 99,
2578 params.range.start.character + 99,
2579 ),
2580 label: lsp::InlayHintLabel::String(
2581 "out of excerpt range, should be ignored".to_string(),
2582 ),
2583 kind: None,
2584 text_edits: None,
2585 tooltip: None,
2586 padding_left: None,
2587 padding_right: None,
2588 data: None,
2589 };
2590
2591 let edited = task_editor_edited.load(Ordering::Acquire);
2592 Ok(Some(
2593 std::iter::once(out_of_range_hint)
2594 .chain(positions.into_iter().enumerate().map(|(i, position)| {
2595 lsp::InlayHint {
2596 position,
2597 label: lsp::InlayHintLabel::String(format!(
2598 "{hint_text}{} #{i}",
2599 if edited { "(edited)" } else { "" },
2600 )),
2601 kind: None,
2602 text_edits: None,
2603 tooltip: None,
2604 padding_left: None,
2605 padding_right: None,
2606 data: None,
2607 }
2608 }))
2609 .collect(),
2610 ))
2611 }
2612 })
2613 .next()
2614 .await;
2615 cx.executor().run_until_parked();
2616
2617 editor.update(cx, |editor, cx| {
2618 let expected_hints = vec![
2619 "main hint #0".to_string(),
2620 "main hint #1".to_string(),
2621 "main hint #2".to_string(),
2622 "main hint #3".to_string(),
2623 ];
2624 assert_eq!(
2625 expected_hints,
2626 cached_hint_labels(editor),
2627 "When scroll is at the edge of a multibuffer, its visible excerpts only should be queried for inlay hints"
2628 );
2629 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2630 assert_eq!(editor.inlay_hint_cache().version, expected_hints.len(), "Every visible excerpt hints should bump the verison");
2631 });
2632
2633 editor.update(cx, |editor, cx| {
2634 editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2635 s.select_ranges([Point::new(4, 0)..Point::new(4, 0)])
2636 });
2637 editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2638 s.select_ranges([Point::new(22, 0)..Point::new(22, 0)])
2639 });
2640 editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2641 s.select_ranges([Point::new(50, 0)..Point::new(50, 0)])
2642 });
2643 });
2644 cx.executor().run_until_parked();
2645 editor.update(cx, |editor, cx| {
2646 let expected_hints = vec![
2647 "main hint #0".to_string(),
2648 "main hint #1".to_string(),
2649 "main hint #2".to_string(),
2650 "main hint #3".to_string(),
2651 "main hint #4".to_string(),
2652 "main hint #5".to_string(),
2653 "other hint #0".to_string(),
2654 "other hint #1".to_string(),
2655 "other hint #2".to_string(),
2656 ];
2657 assert_eq!(expected_hints, cached_hint_labels(editor),
2658 "With more scrolls of the multibuffer, more hints should be added into the cache and nothing invalidated without edits");
2659 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2660 assert_eq!(editor.inlay_hint_cache().version, expected_hints.len(),
2661 "Due to every excerpt having one hint, we update cache per new excerpt scrolled");
2662 });
2663
2664 editor.update(cx, |editor, cx| {
2665 editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2666 s.select_ranges([Point::new(100, 0)..Point::new(100, 0)])
2667 });
2668 });
2669 cx.executor().advance_clock(Duration::from_millis(
2670 INVISIBLE_RANGES_HINTS_REQUEST_DELAY_MILLIS + 100,
2671 ));
2672 cx.executor().run_until_parked();
2673 let last_scroll_update_version = editor.update(cx, |editor, cx| {
2674 let expected_hints = vec![
2675 "main hint #0".to_string(),
2676 "main hint #1".to_string(),
2677 "main hint #2".to_string(),
2678 "main hint #3".to_string(),
2679 "main hint #4".to_string(),
2680 "main hint #5".to_string(),
2681 "other hint #0".to_string(),
2682 "other hint #1".to_string(),
2683 "other hint #2".to_string(),
2684 "other hint #3".to_string(),
2685 "other hint #4".to_string(),
2686 "other hint #5".to_string(),
2687 ];
2688 assert_eq!(expected_hints, cached_hint_labels(editor),
2689 "After multibuffer was scrolled to the end, all hints for all excerpts should be fetched");
2690 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2691 assert_eq!(editor.inlay_hint_cache().version, expected_hints.len());
2692 expected_hints.len()
2693 }).unwrap();
2694
2695 editor.update(cx, |editor, cx| {
2696 editor.change_selections(Some(Autoscroll::Next), cx, |s| {
2697 s.select_ranges([Point::new(4, 0)..Point::new(4, 0)])
2698 });
2699 });
2700 cx.executor().run_until_parked();
2701 editor.update(cx, |editor, cx| {
2702 let expected_hints = vec![
2703 "main hint #0".to_string(),
2704 "main hint #1".to_string(),
2705 "main hint #2".to_string(),
2706 "main hint #3".to_string(),
2707 "main hint #4".to_string(),
2708 "main hint #5".to_string(),
2709 "other hint #0".to_string(),
2710 "other hint #1".to_string(),
2711 "other hint #2".to_string(),
2712 "other hint #3".to_string(),
2713 "other hint #4".to_string(),
2714 "other hint #5".to_string(),
2715 ];
2716 assert_eq!(expected_hints, cached_hint_labels(editor),
2717 "After multibuffer was scrolled to the end, further scrolls up should not bring more hints");
2718 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2719 assert_eq!(editor.inlay_hint_cache().version, last_scroll_update_version, "No updates should happen during scrolling already scolled buffer");
2720 });
2721
2722 editor_edited.store(true, Ordering::Release);
2723 editor.update(cx, |editor, cx| {
2724 editor.change_selections(None, cx, |s| {
2725 s.select_ranges([Point::new(56, 0)..Point::new(56, 0)])
2726 });
2727 editor.handle_input("++++more text++++", cx);
2728 });
2729 cx.executor().run_until_parked();
2730 editor.update(cx, |editor, cx| {
2731 let expected_hints = vec![
2732 "main hint(edited) #0".to_string(),
2733 "main hint(edited) #1".to_string(),
2734 "main hint(edited) #2".to_string(),
2735 "main hint(edited) #3".to_string(),
2736 "main hint(edited) #4".to_string(),
2737 "main hint(edited) #5".to_string(),
2738 "other hint(edited) #0".to_string(),
2739 "other hint(edited) #1".to_string(),
2740 ];
2741 assert_eq!(
2742 expected_hints,
2743 cached_hint_labels(editor),
2744 "After multibuffer edit, editor gets scolled back to the last selection; \
2745all hints should be invalidated and requeried for all of its visible excerpts"
2746 );
2747 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
2748
2749 let current_cache_version = editor.inlay_hint_cache().version;
2750 let minimum_expected_version = last_scroll_update_version + expected_hints.len();
2751 assert!(
2752 current_cache_version == minimum_expected_version || current_cache_version == minimum_expected_version + 1,
2753 "Due to every excerpt having one hint, cache should update per new excerpt received + 1 potential sporadic update"
2754 );
2755 });
2756 }
2757
2758 // todo!()
2759 #[ignore = "fails due to text.rs `measurement has not been performed` error"]
2760 #[gpui::test]
2761 async fn test_excerpts_removed(cx: &mut gpui::TestAppContext) {
2762 init_test(cx, |settings| {
2763 settings.defaults.inlay_hints = Some(InlayHintSettings {
2764 enabled: true,
2765 show_type_hints: false,
2766 show_parameter_hints: false,
2767 show_other_hints: false,
2768 })
2769 });
2770
2771 let mut language = Language::new(
2772 LanguageConfig {
2773 name: "Rust".into(),
2774 path_suffixes: vec!["rs".to_string()],
2775 ..Default::default()
2776 },
2777 Some(tree_sitter_rust::language()),
2778 );
2779 let mut fake_servers = language
2780 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
2781 capabilities: lsp::ServerCapabilities {
2782 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
2783 ..Default::default()
2784 },
2785 ..Default::default()
2786 }))
2787 .await;
2788 let language = Arc::new(language);
2789 let fs = FakeFs::new(cx.background_executor.clone());
2790 fs.insert_tree(
2791 "/a",
2792 json!({
2793 "main.rs": format!("fn main() {{\n{}\n}}", (0..501).map(|i| format!("let i = {i};\n")).collect::<Vec<_>>().join("")),
2794 "other.rs": format!("fn main() {{\n{}\n}}", (0..501).map(|j| format!("let j = {j};\n")).collect::<Vec<_>>().join("")),
2795 }),
2796 )
2797 .await;
2798 let project = Project::test(fs, ["/a".as_ref()], cx).await;
2799 project.update(cx, |project, _| {
2800 project.languages().add(Arc::clone(&language))
2801 });
2802 let workspace = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2803 let worktree_id = workspace
2804 .update(cx, |workspace, cx| {
2805 workspace.project().read_with(cx, |project, cx| {
2806 project.worktrees().next().unwrap().read(cx).id()
2807 })
2808 })
2809 .unwrap();
2810
2811 let buffer_1 = project
2812 .update(cx, |project, cx| {
2813 project.open_buffer((worktree_id, "main.rs"), cx)
2814 })
2815 .await
2816 .unwrap();
2817 let buffer_2 = project
2818 .update(cx, |project, cx| {
2819 project.open_buffer((worktree_id, "other.rs"), cx)
2820 })
2821 .await
2822 .unwrap();
2823 let multibuffer = cx.build_model(|_| MultiBuffer::new(0));
2824 let (buffer_1_excerpts, buffer_2_excerpts) = multibuffer.update(cx, |multibuffer, cx| {
2825 let buffer_1_excerpts = multibuffer.push_excerpts(
2826 buffer_1.clone(),
2827 [ExcerptRange {
2828 context: Point::new(0, 0)..Point::new(2, 0),
2829 primary: None,
2830 }],
2831 cx,
2832 );
2833 let buffer_2_excerpts = multibuffer.push_excerpts(
2834 buffer_2.clone(),
2835 [ExcerptRange {
2836 context: Point::new(0, 1)..Point::new(2, 1),
2837 primary: None,
2838 }],
2839 cx,
2840 );
2841 (buffer_1_excerpts, buffer_2_excerpts)
2842 });
2843
2844 assert!(!buffer_1_excerpts.is_empty());
2845 assert!(!buffer_2_excerpts.is_empty());
2846
2847 cx.executor().run_until_parked();
2848 let editor =
2849 cx.add_window(|cx| Editor::for_multibuffer(multibuffer, Some(project.clone()), cx));
2850 let editor_edited = Arc::new(AtomicBool::new(false));
2851 let fake_server = fake_servers.next().await.unwrap();
2852 let closure_editor_edited = Arc::clone(&editor_edited);
2853 fake_server
2854 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
2855 let task_editor_edited = Arc::clone(&closure_editor_edited);
2856 async move {
2857 let hint_text = if params.text_document.uri
2858 == lsp::Url::from_file_path("/a/main.rs").unwrap()
2859 {
2860 "main hint"
2861 } else if params.text_document.uri
2862 == lsp::Url::from_file_path("/a/other.rs").unwrap()
2863 {
2864 "other hint"
2865 } else {
2866 panic!("unexpected uri: {:?}", params.text_document.uri);
2867 };
2868
2869 let positions = [
2870 lsp::Position::new(0, 2),
2871 lsp::Position::new(4, 2),
2872 lsp::Position::new(22, 2),
2873 lsp::Position::new(44, 2),
2874 lsp::Position::new(56, 2),
2875 lsp::Position::new(67, 2),
2876 ];
2877 let out_of_range_hint = lsp::InlayHint {
2878 position: lsp::Position::new(
2879 params.range.start.line + 99,
2880 params.range.start.character + 99,
2881 ),
2882 label: lsp::InlayHintLabel::String(
2883 "out of excerpt range, should be ignored".to_string(),
2884 ),
2885 kind: None,
2886 text_edits: None,
2887 tooltip: None,
2888 padding_left: None,
2889 padding_right: None,
2890 data: None,
2891 };
2892
2893 let edited = task_editor_edited.load(Ordering::Acquire);
2894 Ok(Some(
2895 std::iter::once(out_of_range_hint)
2896 .chain(positions.into_iter().enumerate().map(|(i, position)| {
2897 lsp::InlayHint {
2898 position,
2899 label: lsp::InlayHintLabel::String(format!(
2900 "{hint_text}{} #{i}",
2901 if edited { "(edited)" } else { "" },
2902 )),
2903 kind: None,
2904 text_edits: None,
2905 tooltip: None,
2906 padding_left: None,
2907 padding_right: None,
2908 data: None,
2909 }
2910 }))
2911 .collect(),
2912 ))
2913 }
2914 })
2915 .next()
2916 .await;
2917 cx.executor().run_until_parked();
2918
2919 editor.update(cx, |editor, cx| {
2920 assert_eq!(
2921 vec!["main hint #0".to_string(), "other hint #0".to_string()],
2922 cached_hint_labels(editor),
2923 "Cache should update for both excerpts despite hints display was disabled"
2924 );
2925 assert!(
2926 visible_hint_labels(editor, cx).is_empty(),
2927 "All hints are disabled and should not be shown despite being present in the cache"
2928 );
2929 assert_eq!(
2930 editor.inlay_hint_cache().version,
2931 2,
2932 "Cache should update once per excerpt query"
2933 );
2934 });
2935
2936 editor.update(cx, |editor, cx| {
2937 editor.buffer().update(cx, |multibuffer, cx| {
2938 multibuffer.remove_excerpts(buffer_2_excerpts, cx)
2939 })
2940 });
2941 cx.executor().run_until_parked();
2942 editor.update(cx, |editor, cx| {
2943 assert_eq!(
2944 vec!["main hint #0".to_string()],
2945 cached_hint_labels(editor),
2946 "For the removed excerpt, should clean corresponding cached hints"
2947 );
2948 assert!(
2949 visible_hint_labels(editor, cx).is_empty(),
2950 "All hints are disabled and should not be shown despite being present in the cache"
2951 );
2952 assert_eq!(
2953 editor.inlay_hint_cache().version,
2954 3,
2955 "Excerpt removal should trigger a cache update"
2956 );
2957 });
2958
2959 update_test_language_settings(cx, |settings| {
2960 settings.defaults.inlay_hints = Some(InlayHintSettings {
2961 enabled: true,
2962 show_type_hints: true,
2963 show_parameter_hints: true,
2964 show_other_hints: true,
2965 })
2966 });
2967 cx.executor().run_until_parked();
2968 editor.update(cx, |editor, cx| {
2969 let expected_hints = vec!["main hint #0".to_string()];
2970 assert_eq!(
2971 expected_hints,
2972 cached_hint_labels(editor),
2973 "Hint display settings change should not change the cache"
2974 );
2975 assert_eq!(
2976 expected_hints,
2977 visible_hint_labels(editor, cx),
2978 "Settings change should make cached hints visible"
2979 );
2980 assert_eq!(
2981 editor.inlay_hint_cache().version,
2982 4,
2983 "Settings change should trigger a cache update"
2984 );
2985 });
2986 }
2987
2988 // todo!()
2989 #[ignore = "fails due to unimplemented `impl PlatformAtlas for TestAtlas` method"]
2990 #[gpui::test]
2991 async fn test_inside_char_boundary_range_hints(cx: &mut gpui::TestAppContext) {
2992 init_test(cx, |settings| {
2993 settings.defaults.inlay_hints = Some(InlayHintSettings {
2994 enabled: true,
2995 show_type_hints: true,
2996 show_parameter_hints: true,
2997 show_other_hints: true,
2998 })
2999 });
3000
3001 let mut language = Language::new(
3002 LanguageConfig {
3003 name: "Rust".into(),
3004 path_suffixes: vec!["rs".to_string()],
3005 ..Default::default()
3006 },
3007 Some(tree_sitter_rust::language()),
3008 );
3009 let mut fake_servers = language
3010 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
3011 capabilities: lsp::ServerCapabilities {
3012 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
3013 ..Default::default()
3014 },
3015 ..Default::default()
3016 }))
3017 .await;
3018 let fs = FakeFs::new(cx.background_executor.clone());
3019 fs.insert_tree(
3020 "/a",
3021 json!({
3022 "main.rs": format!(r#"fn main() {{\n{}\n}}"#, format!("let i = {};\n", "√".repeat(10)).repeat(500)),
3023 "other.rs": "// Test file",
3024 }),
3025 )
3026 .await;
3027 let project = Project::test(fs, ["/a".as_ref()], cx).await;
3028 project.update(cx, |project, _| project.languages().add(Arc::new(language)));
3029 let buffer = project
3030 .update(cx, |project, cx| {
3031 project.open_local_buffer("/a/main.rs", cx)
3032 })
3033 .await
3034 .unwrap();
3035 cx.executor().run_until_parked();
3036 cx.executor().start_waiting();
3037 let fake_server = fake_servers.next().await.unwrap();
3038 let editor = cx.add_window(|cx| Editor::for_buffer(buffer, Some(project), cx));
3039 let lsp_request_count = Arc::new(AtomicU32::new(0));
3040 let closure_lsp_request_count = Arc::clone(&lsp_request_count);
3041 fake_server
3042 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
3043 let task_lsp_request_count = Arc::clone(&closure_lsp_request_count);
3044 async move {
3045 assert_eq!(
3046 params.text_document.uri,
3047 lsp::Url::from_file_path("/a/main.rs").unwrap(),
3048 );
3049 let query_start = params.range.start;
3050 let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::Release) + 1;
3051 Ok(Some(vec![lsp::InlayHint {
3052 position: query_start,
3053 label: lsp::InlayHintLabel::String(i.to_string()),
3054 kind: None,
3055 text_edits: None,
3056 tooltip: None,
3057 padding_left: None,
3058 padding_right: None,
3059 data: None,
3060 }]))
3061 }
3062 })
3063 .next()
3064 .await;
3065
3066 cx.executor().run_until_parked();
3067 editor.update(cx, |editor, cx| {
3068 editor.change_selections(None, cx, |s| {
3069 s.select_ranges([Point::new(10, 0)..Point::new(10, 0)])
3070 })
3071 });
3072 cx.executor().run_until_parked();
3073 editor.update(cx, |editor, cx| {
3074 let expected_hints = vec!["1".to_string()];
3075 assert_eq!(expected_hints, cached_hint_labels(editor));
3076 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
3077 assert_eq!(editor.inlay_hint_cache().version, 1);
3078 });
3079 }
3080
3081 // todo!()
3082 #[ignore = "fails due to unimplemented `impl PlatformAtlas for TestAtlas` method"]
3083 #[gpui::test]
3084 async fn test_toggle_inlay_hints(cx: &mut gpui::TestAppContext) {
3085 init_test(cx, |settings| {
3086 settings.defaults.inlay_hints = Some(InlayHintSettings {
3087 enabled: false,
3088 show_type_hints: true,
3089 show_parameter_hints: true,
3090 show_other_hints: true,
3091 })
3092 });
3093
3094 let (file_with_hints, editor, fake_server) = prepare_test_objects(cx).await;
3095
3096 editor.update(cx, |editor, cx| {
3097 editor.toggle_inlay_hints(&crate::ToggleInlayHints, cx)
3098 });
3099 cx.executor().start_waiting();
3100 let lsp_request_count = Arc::new(AtomicU32::new(0));
3101 let closure_lsp_request_count = Arc::clone(&lsp_request_count);
3102 fake_server
3103 .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
3104 let task_lsp_request_count = Arc::clone(&closure_lsp_request_count);
3105 async move {
3106 assert_eq!(
3107 params.text_document.uri,
3108 lsp::Url::from_file_path(file_with_hints).unwrap(),
3109 );
3110
3111 let i = Arc::clone(&task_lsp_request_count).fetch_add(1, Ordering::SeqCst) + 1;
3112 Ok(Some(vec![lsp::InlayHint {
3113 position: lsp::Position::new(0, i),
3114 label: lsp::InlayHintLabel::String(i.to_string()),
3115 kind: None,
3116 text_edits: None,
3117 tooltip: None,
3118 padding_left: None,
3119 padding_right: None,
3120 data: None,
3121 }]))
3122 }
3123 })
3124 .next()
3125 .await;
3126 cx.executor().run_until_parked();
3127 editor.update(cx, |editor, cx| {
3128 let expected_hints = vec!["1".to_string()];
3129 assert_eq!(
3130 expected_hints,
3131 cached_hint_labels(editor),
3132 "Should display inlays after toggle despite them disabled in settings"
3133 );
3134 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
3135 assert_eq!(
3136 editor.inlay_hint_cache().version,
3137 1,
3138 "First toggle should be cache's first update"
3139 );
3140 });
3141
3142 editor.update(cx, |editor, cx| {
3143 editor.toggle_inlay_hints(&crate::ToggleInlayHints, cx)
3144 });
3145 cx.executor().run_until_parked();
3146 editor.update(cx, |editor, cx| {
3147 assert!(
3148 cached_hint_labels(editor).is_empty(),
3149 "Should clear hints after 2nd toggle"
3150 );
3151 assert!(visible_hint_labels(editor, cx).is_empty());
3152 assert_eq!(editor.inlay_hint_cache().version, 2);
3153 });
3154
3155 update_test_language_settings(cx, |settings| {
3156 settings.defaults.inlay_hints = Some(InlayHintSettings {
3157 enabled: true,
3158 show_type_hints: true,
3159 show_parameter_hints: true,
3160 show_other_hints: true,
3161 })
3162 });
3163 cx.executor().run_until_parked();
3164 editor.update(cx, |editor, cx| {
3165 let expected_hints = vec!["2".to_string()];
3166 assert_eq!(
3167 expected_hints,
3168 cached_hint_labels(editor),
3169 "Should query LSP hints for the 2nd time after enabling hints in settings"
3170 );
3171 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
3172 assert_eq!(editor.inlay_hint_cache().version, 3);
3173 });
3174
3175 editor.update(cx, |editor, cx| {
3176 editor.toggle_inlay_hints(&crate::ToggleInlayHints, cx)
3177 });
3178 cx.executor().run_until_parked();
3179 editor.update(cx, |editor, cx| {
3180 assert!(
3181 cached_hint_labels(editor).is_empty(),
3182 "Should clear hints after enabling in settings and a 3rd toggle"
3183 );
3184 assert!(visible_hint_labels(editor, cx).is_empty());
3185 assert_eq!(editor.inlay_hint_cache().version, 4);
3186 });
3187
3188 editor.update(cx, |editor, cx| {
3189 editor.toggle_inlay_hints(&crate::ToggleInlayHints, cx)
3190 });
3191 cx.executor().run_until_parked();
3192 editor.update(cx, |editor, cx| {
3193 let expected_hints = vec!["3".to_string()];
3194 assert_eq!(
3195 expected_hints,
3196 cached_hint_labels(editor),
3197 "Should query LSP hints for the 3rd time after enabling hints in settings and toggling them back on"
3198 );
3199 assert_eq!(expected_hints, visible_hint_labels(editor, cx));
3200 assert_eq!(editor.inlay_hint_cache().version, 5);
3201 });
3202 }
3203
3204 pub(crate) fn init_test(cx: &mut TestAppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
3205 cx.update(|cx| {
3206 let settings_store = SettingsStore::test(cx);
3207 cx.set_global(settings_store);
3208 theme::init(cx);
3209 client::init_settings(cx);
3210 language::init(cx);
3211 Project::init_settings(cx);
3212 workspace::init_settings(cx);
3213 crate::init(cx);
3214 });
3215
3216 update_test_language_settings(cx, f);
3217 }
3218
3219 async fn prepare_test_objects(
3220 cx: &mut TestAppContext,
3221 ) -> (&'static str, WindowHandle<Editor>, FakeLanguageServer) {
3222 let mut language = Language::new(
3223 LanguageConfig {
3224 name: "Rust".into(),
3225 path_suffixes: vec!["rs".to_string()],
3226 ..Default::default()
3227 },
3228 Some(tree_sitter_rust::language()),
3229 );
3230 let mut fake_servers = language
3231 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
3232 capabilities: lsp::ServerCapabilities {
3233 inlay_hint_provider: Some(lsp::OneOf::Left(true)),
3234 ..Default::default()
3235 },
3236 ..Default::default()
3237 }))
3238 .await;
3239
3240 let fs = FakeFs::new(cx.background_executor.clone());
3241 fs.insert_tree(
3242 "/a",
3243 json!({
3244 "main.rs": "fn main() { a } // and some long comment to ensure inlays are not trimmed out",
3245 "other.rs": "// Test file",
3246 }),
3247 )
3248 .await;
3249
3250 let project = Project::test(fs, ["/a".as_ref()], cx).await;
3251 project.update(cx, |project, _| project.languages().add(Arc::new(language)));
3252 let buffer = project
3253 .update(cx, |project, cx| {
3254 project.open_local_buffer("/a/main.rs", cx)
3255 })
3256 .await
3257 .unwrap();
3258 cx.executor().run_until_parked();
3259 cx.executor().start_waiting();
3260 let fake_server = fake_servers.next().await.unwrap();
3261 let editor = cx.add_window(|cx| Editor::for_buffer(buffer, Some(project), cx));
3262
3263 editor.update(cx, |editor, cx| {
3264 assert!(cached_hint_labels(editor).is_empty());
3265 assert!(visible_hint_labels(editor, cx).is_empty());
3266 assert_eq!(editor.inlay_hint_cache().version, 0);
3267 });
3268
3269 ("/a/main.rs", editor, fake_server)
3270 }
3271
3272 pub fn cached_hint_labels(editor: &Editor) -> Vec<String> {
3273 let mut labels = Vec::new();
3274 for (_, excerpt_hints) in &editor.inlay_hint_cache().hints {
3275 let excerpt_hints = excerpt_hints.read();
3276 for id in &excerpt_hints.ordered_hints {
3277 labels.push(excerpt_hints.hints_by_id[id].text());
3278 }
3279 }
3280
3281 labels.sort();
3282 labels
3283 }
3284
3285 pub fn visible_hint_labels(editor: &Editor, cx: &ViewContext<'_, Editor>) -> Vec<String> {
3286 let mut hints = editor
3287 .visible_inlay_hints(cx)
3288 .into_iter()
3289 .map(|hint| hint.text.to_string())
3290 .collect::<Vec<_>>();
3291 hints.sort();
3292 hints
3293 }
3294}