1use crate::{
2 display_map::{DisplayMap, DisplaySnapshot, ToDisplayPoint},
3 multi_buffer::ToPointUtf16,
4 AnchorRangeExt, Autoscroll, DisplayPoint, Editor, EditorMode, MultiBuffer, ToPoint,
5};
6use anyhow::Result;
7use futures::{Future, StreamExt};
8use gpui::{
9 json, keymap::Keystroke, AppContext, ModelContext, ModelHandle, ViewContext, ViewHandle,
10};
11use indoc::indoc;
12use language::{point_to_lsp, Buffer, BufferSnapshot, FakeLspAdapter, Language, LanguageConfig};
13use lsp::{notification, request};
14use project::Project;
15use settings::Settings;
16use std::{
17 any::TypeId,
18 ops::{Deref, DerefMut, Range},
19 sync::Arc,
20};
21use util::{
22 assert_set_eq, set_eq,
23 test::{generate_marked_text, marked_text_offsets, marked_text_ranges},
24};
25use workspace::{pane, AppState, Workspace, WorkspaceHandle};
26
27#[cfg(test)]
28#[ctor::ctor]
29fn init_logger() {
30 if std::env::var("RUST_LOG").is_ok() {
31 env_logger::init();
32 }
33}
34
35// Returns a snapshot from text containing '|' character markers with the markers removed, and DisplayPoints for each one.
36pub fn marked_display_snapshot(
37 text: &str,
38 cx: &mut gpui::MutableAppContext,
39) -> (DisplaySnapshot, Vec<DisplayPoint>) {
40 let (unmarked_text, markers) = marked_text_offsets(text);
41
42 let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
43 let font_id = cx
44 .font_cache()
45 .select_font(family_id, &Default::default())
46 .unwrap();
47 let font_size = 14.0;
48
49 let buffer = MultiBuffer::build_simple(&unmarked_text, cx);
50 let display_map =
51 cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
52 let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
53 let markers = markers
54 .into_iter()
55 .map(|offset| offset.to_display_point(&snapshot))
56 .collect();
57
58 (snapshot, markers)
59}
60
61pub fn select_ranges(editor: &mut Editor, marked_text: &str, cx: &mut ViewContext<Editor>) {
62 let (umarked_text, text_ranges) = marked_text_ranges(marked_text, true);
63 assert_eq!(editor.text(cx), umarked_text);
64 editor.change_selections(None, cx, |s| s.select_ranges(text_ranges));
65}
66
67pub fn assert_text_with_selections(
68 editor: &mut Editor,
69 marked_text: &str,
70 cx: &mut ViewContext<Editor>,
71) {
72 let (unmarked_text, text_ranges) = marked_text_ranges(marked_text, true);
73 assert_eq!(editor.text(cx), unmarked_text);
74 assert_eq!(editor.selections.ranges(cx), text_ranges);
75}
76
77pub(crate) fn build_editor(
78 buffer: ModelHandle<MultiBuffer>,
79 cx: &mut ViewContext<Editor>,
80) -> Editor {
81 Editor::new(EditorMode::Full, buffer, None, None, cx)
82}
83
84pub struct EditorTestContext<'a> {
85 pub cx: &'a mut gpui::TestAppContext,
86 pub window_id: usize,
87 pub editor: ViewHandle<Editor>,
88}
89
90impl<'a> EditorTestContext<'a> {
91 pub async fn new(cx: &'a mut gpui::TestAppContext) -> EditorTestContext<'a> {
92 let (window_id, editor) = cx.update(|cx| {
93 cx.set_global(Settings::test(cx));
94 crate::init(cx);
95
96 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
97 build_editor(MultiBuffer::build_simple("", cx), cx)
98 });
99
100 editor.update(cx, |_, cx| cx.focus_self());
101
102 (window_id, editor)
103 });
104
105 Self {
106 cx,
107 window_id,
108 editor,
109 }
110 }
111
112 pub fn condition(
113 &self,
114 predicate: impl FnMut(&Editor, &AppContext) -> bool,
115 ) -> impl Future<Output = ()> {
116 self.editor.condition(self.cx, predicate)
117 }
118
119 pub fn editor<F, T>(&self, read: F) -> T
120 where
121 F: FnOnce(&Editor, &AppContext) -> T,
122 {
123 self.editor.read_with(self.cx, read)
124 }
125
126 pub fn update_editor<F, T>(&mut self, update: F) -> T
127 where
128 F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
129 {
130 self.editor.update(self.cx, update)
131 }
132
133 pub fn multibuffer<F, T>(&self, read: F) -> T
134 where
135 F: FnOnce(&MultiBuffer, &AppContext) -> T,
136 {
137 self.editor(|editor, cx| read(editor.buffer().read(cx), cx))
138 }
139
140 pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
141 where
142 F: FnOnce(&mut MultiBuffer, &mut ModelContext<MultiBuffer>) -> T,
143 {
144 self.update_editor(|editor, cx| editor.buffer().update(cx, update))
145 }
146
147 pub fn buffer_text(&self) -> String {
148 self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
149 }
150
151 pub fn buffer<F, T>(&self, read: F) -> T
152 where
153 F: FnOnce(&Buffer, &AppContext) -> T,
154 {
155 self.multibuffer(|multibuffer, cx| {
156 let buffer = multibuffer.as_singleton().unwrap().read(cx);
157 read(buffer, cx)
158 })
159 }
160
161 pub fn update_buffer<F, T>(&mut self, update: F) -> T
162 where
163 F: FnOnce(&mut Buffer, &mut ModelContext<Buffer>) -> T,
164 {
165 self.update_multibuffer(|multibuffer, cx| {
166 let buffer = multibuffer.as_singleton().unwrap();
167 buffer.update(cx, update)
168 })
169 }
170
171 pub fn buffer_snapshot(&self) -> BufferSnapshot {
172 self.buffer(|buffer, _| buffer.snapshot())
173 }
174
175 pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
176 let keystroke = Keystroke::parse(keystroke_text).unwrap();
177 self.cx.dispatch_keystroke(self.window_id, keystroke, false);
178 }
179
180 pub fn simulate_keystrokes<const COUNT: usize>(&mut self, keystroke_texts: [&str; COUNT]) {
181 for keystroke_text in keystroke_texts.into_iter() {
182 self.simulate_keystroke(keystroke_text);
183 }
184 }
185
186 pub fn ranges(&self, marked_text: &str) -> Vec<Range<usize>> {
187 let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
188 assert_eq!(self.buffer_text(), unmarked_text);
189 ranges
190 }
191
192 pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
193 let ranges = self.ranges(marked_text);
194 let snapshot = self
195 .editor
196 .update(self.cx, |editor, cx| editor.snapshot(cx));
197 ranges[0].start.to_display_point(&snapshot)
198 }
199
200 // Returns anchors for the current buffer using `«` and `»`
201 pub fn text_anchor_range(&self, marked_text: &str) -> Range<language::Anchor> {
202 let ranges = self.ranges(marked_text);
203 let snapshot = self.buffer_snapshot();
204 snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
205 }
206
207 /// Change the editor's text and selections using a string containing
208 /// embedded range markers that represent the ranges and directions of
209 /// each selection.
210 ///
211 /// See the `util::test::marked_text_ranges` function for more information.
212 pub fn set_state(&mut self, marked_text: &str) {
213 let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
214 self.editor.update(self.cx, |editor, cx| {
215 editor.set_text(unmarked_text, cx);
216 editor.change_selections(Some(Autoscroll::Fit), cx, |s| {
217 s.select_ranges(selection_ranges)
218 })
219 })
220 }
221
222 /// Make an assertion about the editor's text and the ranges and directions
223 /// of its selections using a string containing embedded range markers.
224 ///
225 /// See the `util::test::marked_text_ranges` function for more information.
226 pub fn assert_editor_state(&mut self, marked_text: &str) {
227 let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
228 let buffer_text = self.buffer_text();
229 assert_eq!(
230 buffer_text, unmarked_text,
231 "Unmarked text doesn't match buffer text"
232 );
233 self.assert_selections(expected_selections, marked_text.to_string())
234 }
235
236 pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
237 let expected_ranges = self.ranges(marked_text);
238 let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, cx| {
239 let snapshot = editor.snapshot(cx);
240 editor
241 .background_highlights
242 .get(&TypeId::of::<Tag>())
243 .map(|h| h.1.clone())
244 .unwrap_or_default()
245 .into_iter()
246 .map(|range| range.to_offset(&snapshot.buffer_snapshot))
247 .collect()
248 });
249 assert_set_eq!(actual_ranges, expected_ranges);
250 }
251
252 pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
253 let expected_ranges = self.ranges(marked_text);
254 let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
255 let actual_ranges: Vec<Range<usize>> = snapshot
256 .highlight_ranges::<Tag>()
257 .map(|ranges| ranges.as_ref().clone().1)
258 .unwrap_or_default()
259 .into_iter()
260 .map(|range| range.to_offset(&snapshot.buffer_snapshot))
261 .collect();
262 assert_set_eq!(actual_ranges, expected_ranges);
263 }
264
265 pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
266 let expected_marked_text =
267 generate_marked_text(&self.buffer_text(), &expected_selections, true);
268 self.assert_selections(expected_selections, expected_marked_text)
269 }
270
271 fn assert_selections(
272 &mut self,
273 expected_selections: Vec<Range<usize>>,
274 expected_marked_text: String,
275 ) {
276 let actual_selections = self
277 .editor
278 .read_with(self.cx, |editor, cx| editor.selections.all::<usize>(cx))
279 .into_iter()
280 .map(|s| {
281 if s.reversed {
282 s.end..s.start
283 } else {
284 s.start..s.end
285 }
286 })
287 .collect::<Vec<_>>();
288 let actual_marked_text =
289 generate_marked_text(&self.buffer_text(), &actual_selections, true);
290 if expected_selections != actual_selections {
291 panic!(
292 indoc! {"
293 Editor has unexpected selections.
294
295 Expected selections:
296 {}
297
298 Actual selections:
299 {}
300 "},
301 expected_marked_text, actual_marked_text,
302 );
303 }
304 }
305}
306
307impl<'a> Deref for EditorTestContext<'a> {
308 type Target = gpui::TestAppContext;
309
310 fn deref(&self) -> &Self::Target {
311 self.cx
312 }
313}
314
315impl<'a> DerefMut for EditorTestContext<'a> {
316 fn deref_mut(&mut self) -> &mut Self::Target {
317 &mut self.cx
318 }
319}
320
321pub struct EditorLspTestContext<'a> {
322 pub cx: EditorTestContext<'a>,
323 pub lsp: lsp::FakeLanguageServer,
324 pub workspace: ViewHandle<Workspace>,
325 pub buffer_lsp_url: lsp::Url,
326}
327
328impl<'a> EditorLspTestContext<'a> {
329 pub async fn new(
330 mut language: Language,
331 capabilities: lsp::ServerCapabilities,
332 cx: &'a mut gpui::TestAppContext,
333 ) -> EditorLspTestContext<'a> {
334 use json::json;
335
336 cx.update(|cx| {
337 crate::init(cx);
338 pane::init(cx);
339 });
340
341 let params = cx.update(AppState::test);
342
343 let file_name = format!(
344 "file.{}",
345 language
346 .path_suffixes()
347 .first()
348 .unwrap_or(&"txt".to_string())
349 );
350
351 let mut fake_servers = language
352 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
353 capabilities,
354 ..Default::default()
355 }))
356 .await;
357
358 let project = Project::test(params.fs.clone(), [], cx).await;
359 project.update(cx, |project, _| project.languages().add(Arc::new(language)));
360
361 params
362 .fs
363 .as_fake()
364 .insert_tree("/root", json!({ "dir": { file_name: "" }}))
365 .await;
366
367 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
368 project
369 .update(cx, |project, cx| {
370 project.find_or_create_local_worktree("/root", true, cx)
371 })
372 .await
373 .unwrap();
374 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
375 .await;
376
377 let file = cx.read(|cx| workspace.file_project_paths(cx)[0].clone());
378 let item = workspace
379 .update(cx, |workspace, cx| workspace.open_path(file, true, cx))
380 .await
381 .expect("Could not open test file");
382
383 let editor = cx.update(|cx| {
384 item.act_as::<Editor>(cx)
385 .expect("Opened test file wasn't an editor")
386 });
387 editor.update(cx, |_, cx| cx.focus_self());
388
389 let lsp = fake_servers.next().await.unwrap();
390
391 Self {
392 cx: EditorTestContext {
393 cx,
394 window_id,
395 editor,
396 },
397 lsp,
398 workspace,
399 buffer_lsp_url: lsp::Url::from_file_path("/root/dir/file.rs").unwrap(),
400 }
401 }
402
403 pub async fn new_rust(
404 capabilities: lsp::ServerCapabilities,
405 cx: &'a mut gpui::TestAppContext,
406 ) -> EditorLspTestContext<'a> {
407 let language = Language::new(
408 LanguageConfig {
409 name: "Rust".into(),
410 path_suffixes: vec!["rs".to_string()],
411 ..Default::default()
412 },
413 Some(tree_sitter_rust::language()),
414 );
415
416 Self::new(language, capabilities, cx).await
417 }
418
419 // Constructs lsp range using a marked string with '[', ']' range delimiters
420 pub fn lsp_range(&mut self, marked_text: &str) -> lsp::Range {
421 let ranges = self.ranges(marked_text);
422 self.to_lsp_range(ranges[0].clone())
423 }
424
425 pub fn to_lsp_range(&mut self, range: Range<usize>) -> lsp::Range {
426 let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
427 let start_point = range.start.to_point(&snapshot.buffer_snapshot);
428 let end_point = range.end.to_point(&snapshot.buffer_snapshot);
429
430 self.editor(|editor, cx| {
431 let buffer = editor.buffer().read(cx);
432 let start = point_to_lsp(
433 buffer
434 .point_to_buffer_offset(start_point, cx)
435 .unwrap()
436 .1
437 .to_point_utf16(&buffer.read(cx)),
438 );
439 let end = point_to_lsp(
440 buffer
441 .point_to_buffer_offset(end_point, cx)
442 .unwrap()
443 .1
444 .to_point_utf16(&buffer.read(cx)),
445 );
446
447 lsp::Range { start, end }
448 })
449 }
450
451 pub fn to_lsp(&mut self, offset: usize) -> lsp::Position {
452 let snapshot = self.update_editor(|editor, cx| editor.snapshot(cx));
453 let point = offset.to_point(&snapshot.buffer_snapshot);
454
455 self.editor(|editor, cx| {
456 let buffer = editor.buffer().read(cx);
457 point_to_lsp(
458 buffer
459 .point_to_buffer_offset(point, cx)
460 .unwrap()
461 .1
462 .to_point_utf16(&buffer.read(cx)),
463 )
464 })
465 }
466
467 pub fn update_workspace<F, T>(&mut self, update: F) -> T
468 where
469 F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
470 {
471 self.workspace.update(self.cx.cx, update)
472 }
473
474 pub fn handle_request<T, F, Fut>(
475 &self,
476 mut handler: F,
477 ) -> futures::channel::mpsc::UnboundedReceiver<()>
478 where
479 T: 'static + request::Request,
480 T::Params: 'static + Send,
481 F: 'static + Send + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut,
482 Fut: 'static + Send + Future<Output = Result<T::Result>>,
483 {
484 let url = self.buffer_lsp_url.clone();
485 self.lsp.handle_request::<T, _, _>(move |params, cx| {
486 let url = url.clone();
487 handler(url, params, cx)
488 })
489 }
490
491 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
492 self.lsp.notify::<T>(params);
493 }
494}
495
496impl<'a> Deref for EditorLspTestContext<'a> {
497 type Target = EditorTestContext<'a>;
498
499 fn deref(&self) -> &Self::Target {
500 &self.cx
501 }
502}
503
504impl<'a> DerefMut for EditorLspTestContext<'a> {
505 fn deref_mut(&mut self) -> &mut Self::Target {
506 &mut self.cx
507 }
508}