1pub mod fs;
2mod ignore;
3mod lsp_command;
4pub mod search;
5pub mod worktree;
6
7use anyhow::{anyhow, Context, Result};
8use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
9use clock::ReplicaId;
10use collections::{hash_map, BTreeMap, HashMap, HashSet};
11use futures::{future::Shared, Future, FutureExt, StreamExt, TryFutureExt};
12use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
13use gpui::{
14 AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
15 MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
16};
17use language::{
18 point_to_lsp,
19 proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version},
20 range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CodeAction, CodeLabel, Completion,
21 Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent, File as _, Language,
22 LanguageRegistry, LanguageServerName, LocalFile, LspAdapter, OffsetRangeExt, Operation, Patch,
23 PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction,
24};
25use lsp::{DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer};
26use lsp_command::*;
27use parking_lot::Mutex;
28use postage::watch;
29use rand::prelude::*;
30use search::SearchQuery;
31use sha2::{Digest, Sha256};
32use similar::{ChangeTag, TextDiff};
33use std::{
34 cell::RefCell,
35 cmp::{self, Ordering},
36 convert::TryInto,
37 hash::Hash,
38 mem,
39 ops::Range,
40 path::{Component, Path, PathBuf},
41 rc::Rc,
42 sync::{
43 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
44 Arc,
45 },
46 time::Instant,
47};
48use util::{post_inc, ResultExt, TryFutureExt as _};
49
50pub use fs::*;
51pub use worktree::*;
52
53pub trait Item: Entity {
54 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
55}
56
57pub struct Project {
58 worktrees: Vec<WorktreeHandle>,
59 active_entry: Option<ProjectEntryId>,
60 languages: Arc<LanguageRegistry>,
61 language_servers:
62 HashMap<(WorktreeId, LanguageServerName), (Arc<dyn LspAdapter>, Arc<LanguageServer>)>,
63 started_language_servers:
64 HashMap<(WorktreeId, LanguageServerName), Task<Option<Arc<LanguageServer>>>>,
65 language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
66 language_server_settings: Arc<Mutex<serde_json::Value>>,
67 next_language_server_id: usize,
68 client: Arc<client::Client>,
69 next_entry_id: Arc<AtomicUsize>,
70 user_store: ModelHandle<UserStore>,
71 fs: Arc<dyn Fs>,
72 client_state: ProjectClientState,
73 collaborators: HashMap<PeerId, Collaborator>,
74 subscriptions: Vec<client::Subscription>,
75 language_servers_with_diagnostics_running: isize,
76 opened_buffer: (Rc<RefCell<watch::Sender<()>>>, watch::Receiver<()>),
77 shared_buffers: HashMap<PeerId, HashSet<u64>>,
78 loading_buffers: HashMap<
79 ProjectPath,
80 postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
81 >,
82 loading_local_worktrees:
83 HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
84 opened_buffers: HashMap<u64, OpenBuffer>,
85 buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
86 nonce: u128,
87}
88
89enum OpenBuffer {
90 Strong(ModelHandle<Buffer>),
91 Weak(WeakModelHandle<Buffer>),
92 Loading(Vec<Operation>),
93}
94
95enum WorktreeHandle {
96 Strong(ModelHandle<Worktree>),
97 Weak(WeakModelHandle<Worktree>),
98}
99
100enum ProjectClientState {
101 Local {
102 is_shared: bool,
103 remote_id_tx: watch::Sender<Option<u64>>,
104 remote_id_rx: watch::Receiver<Option<u64>>,
105 _maintain_remote_id_task: Task<Option<()>>,
106 },
107 Remote {
108 sharing_has_stopped: bool,
109 remote_id: u64,
110 replica_id: ReplicaId,
111 _detect_unshare_task: Task<Option<()>>,
112 },
113}
114
115#[derive(Clone, Debug)]
116pub struct Collaborator {
117 pub user: Arc<User>,
118 pub peer_id: PeerId,
119 pub replica_id: ReplicaId,
120}
121
122#[derive(Clone, Debug, PartialEq)]
123pub enum Event {
124 ActiveEntryChanged(Option<ProjectEntryId>),
125 WorktreeRemoved(WorktreeId),
126 DiskBasedDiagnosticsStarted,
127 DiskBasedDiagnosticsUpdated,
128 DiskBasedDiagnosticsFinished,
129 DiagnosticsUpdated(ProjectPath),
130 RemoteIdChanged(Option<u64>),
131 CollaboratorLeft(PeerId),
132}
133
134enum LanguageServerEvent {
135 WorkStart {
136 token: String,
137 },
138 WorkProgress {
139 token: String,
140 progress: LanguageServerProgress,
141 },
142 WorkEnd {
143 token: String,
144 },
145 DiagnosticsUpdate(lsp::PublishDiagnosticsParams),
146}
147
148pub struct LanguageServerStatus {
149 pub name: String,
150 pub pending_work: BTreeMap<String, LanguageServerProgress>,
151 pending_diagnostic_updates: isize,
152}
153
154#[derive(Clone, Debug)]
155pub struct LanguageServerProgress {
156 pub message: Option<String>,
157 pub percentage: Option<usize>,
158 pub last_update_at: Instant,
159}
160
161#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
162pub struct ProjectPath {
163 pub worktree_id: WorktreeId,
164 pub path: Arc<Path>,
165}
166
167#[derive(Clone, Debug, Default, PartialEq)]
168pub struct DiagnosticSummary {
169 pub error_count: usize,
170 pub warning_count: usize,
171 pub info_count: usize,
172 pub hint_count: usize,
173}
174
175#[derive(Debug)]
176pub struct Location {
177 pub buffer: ModelHandle<Buffer>,
178 pub range: Range<language::Anchor>,
179}
180
181#[derive(Debug)]
182pub struct DocumentHighlight {
183 pub range: Range<language::Anchor>,
184 pub kind: DocumentHighlightKind,
185}
186
187#[derive(Clone, Debug)]
188pub struct Symbol {
189 pub source_worktree_id: WorktreeId,
190 pub worktree_id: WorktreeId,
191 pub language_server_name: LanguageServerName,
192 pub path: PathBuf,
193 pub label: CodeLabel,
194 pub name: String,
195 pub kind: lsp::SymbolKind,
196 pub range: Range<PointUtf16>,
197 pub signature: [u8; 32],
198}
199
200#[derive(Default)]
201pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
202
203impl DiagnosticSummary {
204 fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
205 let mut this = Self {
206 error_count: 0,
207 warning_count: 0,
208 info_count: 0,
209 hint_count: 0,
210 };
211
212 for entry in diagnostics {
213 if entry.diagnostic.is_primary {
214 match entry.diagnostic.severity {
215 DiagnosticSeverity::ERROR => this.error_count += 1,
216 DiagnosticSeverity::WARNING => this.warning_count += 1,
217 DiagnosticSeverity::INFORMATION => this.info_count += 1,
218 DiagnosticSeverity::HINT => this.hint_count += 1,
219 _ => {}
220 }
221 }
222 }
223
224 this
225 }
226
227 pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
228 proto::DiagnosticSummary {
229 path: path.to_string_lossy().to_string(),
230 error_count: self.error_count as u32,
231 warning_count: self.warning_count as u32,
232 info_count: self.info_count as u32,
233 hint_count: self.hint_count as u32,
234 }
235 }
236}
237
238#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
239pub struct ProjectEntryId(usize);
240
241impl ProjectEntryId {
242 pub fn new(counter: &AtomicUsize) -> Self {
243 Self(counter.fetch_add(1, SeqCst))
244 }
245
246 pub fn from_proto(id: u64) -> Self {
247 Self(id as usize)
248 }
249
250 pub fn to_proto(&self) -> u64 {
251 self.0 as u64
252 }
253
254 pub fn to_usize(&self) -> usize {
255 self.0
256 }
257}
258
259impl Project {
260 pub fn init(client: &Arc<Client>) {
261 client.add_model_message_handler(Self::handle_add_collaborator);
262 client.add_model_message_handler(Self::handle_buffer_reloaded);
263 client.add_model_message_handler(Self::handle_buffer_saved);
264 client.add_model_message_handler(Self::handle_start_language_server);
265 client.add_model_message_handler(Self::handle_update_language_server);
266 client.add_model_message_handler(Self::handle_remove_collaborator);
267 client.add_model_message_handler(Self::handle_register_worktree);
268 client.add_model_message_handler(Self::handle_unregister_worktree);
269 client.add_model_message_handler(Self::handle_unshare_project);
270 client.add_model_message_handler(Self::handle_update_buffer_file);
271 client.add_model_message_handler(Self::handle_update_buffer);
272 client.add_model_message_handler(Self::handle_update_diagnostic_summary);
273 client.add_model_message_handler(Self::handle_update_worktree);
274 client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
275 client.add_model_request_handler(Self::handle_apply_code_action);
276 client.add_model_request_handler(Self::handle_format_buffers);
277 client.add_model_request_handler(Self::handle_get_code_actions);
278 client.add_model_request_handler(Self::handle_get_completions);
279 client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
280 client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
281 client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
282 client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
283 client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
284 client.add_model_request_handler(Self::handle_search_project);
285 client.add_model_request_handler(Self::handle_get_project_symbols);
286 client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
287 client.add_model_request_handler(Self::handle_open_buffer_by_id);
288 client.add_model_request_handler(Self::handle_open_buffer_by_path);
289 client.add_model_request_handler(Self::handle_save_buffer);
290 }
291
292 pub fn local(
293 client: Arc<Client>,
294 user_store: ModelHandle<UserStore>,
295 languages: Arc<LanguageRegistry>,
296 fs: Arc<dyn Fs>,
297 cx: &mut MutableAppContext,
298 ) -> ModelHandle<Self> {
299 cx.add_model(|cx: &mut ModelContext<Self>| {
300 let (remote_id_tx, remote_id_rx) = watch::channel();
301 let _maintain_remote_id_task = cx.spawn_weak({
302 let rpc = client.clone();
303 move |this, mut cx| {
304 async move {
305 let mut status = rpc.status();
306 while let Some(status) = status.next().await {
307 if let Some(this) = this.upgrade(&cx) {
308 if status.is_connected() {
309 this.update(&mut cx, |this, cx| this.register(cx)).await?;
310 } else {
311 this.update(&mut cx, |this, cx| this.unregister(cx));
312 }
313 }
314 }
315 Ok(())
316 }
317 .log_err()
318 }
319 });
320
321 let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
322 Self {
323 worktrees: Default::default(),
324 collaborators: Default::default(),
325 opened_buffers: Default::default(),
326 shared_buffers: Default::default(),
327 loading_buffers: Default::default(),
328 loading_local_worktrees: Default::default(),
329 buffer_snapshots: Default::default(),
330 client_state: ProjectClientState::Local {
331 is_shared: false,
332 remote_id_tx,
333 remote_id_rx,
334 _maintain_remote_id_task,
335 },
336 opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
337 subscriptions: Vec::new(),
338 active_entry: None,
339 languages,
340 client,
341 user_store,
342 fs,
343 next_entry_id: Default::default(),
344 language_servers_with_diagnostics_running: 0,
345 language_servers: Default::default(),
346 started_language_servers: Default::default(),
347 language_server_statuses: Default::default(),
348 language_server_settings: Default::default(),
349 next_language_server_id: 0,
350 nonce: StdRng::from_entropy().gen(),
351 }
352 })
353 }
354
355 pub async fn remote(
356 remote_id: u64,
357 client: Arc<Client>,
358 user_store: ModelHandle<UserStore>,
359 languages: Arc<LanguageRegistry>,
360 fs: Arc<dyn Fs>,
361 cx: &mut AsyncAppContext,
362 ) -> Result<ModelHandle<Self>> {
363 client.authenticate_and_connect(true, &cx).await?;
364
365 let response = client
366 .request(proto::JoinProject {
367 project_id: remote_id,
368 })
369 .await?;
370
371 let replica_id = response.replica_id as ReplicaId;
372
373 let mut worktrees = Vec::new();
374 for worktree in response.worktrees {
375 let (worktree, load_task) = cx
376 .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
377 worktrees.push(worktree);
378 load_task.detach();
379 }
380
381 let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
382 let this = cx.add_model(|cx: &mut ModelContext<Self>| {
383 let mut this = Self {
384 worktrees: Vec::new(),
385 loading_buffers: Default::default(),
386 opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
387 shared_buffers: Default::default(),
388 loading_local_worktrees: Default::default(),
389 active_entry: None,
390 collaborators: Default::default(),
391 languages,
392 user_store: user_store.clone(),
393 fs,
394 next_entry_id: Default::default(),
395 subscriptions: vec![client.add_model_for_remote_entity(remote_id, cx)],
396 client: client.clone(),
397 client_state: ProjectClientState::Remote {
398 sharing_has_stopped: false,
399 remote_id,
400 replica_id,
401 _detect_unshare_task: cx.spawn_weak(move |this, mut cx| {
402 async move {
403 let mut status = client.status();
404 let is_connected =
405 status.next().await.map_or(false, |s| s.is_connected());
406 // Even if we're initially connected, any future change of the status means we momentarily disconnected.
407 if !is_connected || status.next().await.is_some() {
408 if let Some(this) = this.upgrade(&cx) {
409 this.update(&mut cx, |this, cx| this.project_unshared(cx))
410 }
411 }
412 Ok(())
413 }
414 .log_err()
415 }),
416 },
417 language_servers_with_diagnostics_running: 0,
418 language_servers: Default::default(),
419 started_language_servers: Default::default(),
420 language_server_settings: Default::default(),
421 language_server_statuses: response
422 .language_servers
423 .into_iter()
424 .map(|server| {
425 (
426 server.id as usize,
427 LanguageServerStatus {
428 name: server.name,
429 pending_work: Default::default(),
430 pending_diagnostic_updates: 0,
431 },
432 )
433 })
434 .collect(),
435 next_language_server_id: 0,
436 opened_buffers: Default::default(),
437 buffer_snapshots: Default::default(),
438 nonce: StdRng::from_entropy().gen(),
439 };
440 for worktree in worktrees {
441 this.add_worktree(&worktree, cx);
442 }
443 this
444 });
445
446 let user_ids = response
447 .collaborators
448 .iter()
449 .map(|peer| peer.user_id)
450 .collect();
451 user_store
452 .update(cx, |user_store, cx| user_store.load_users(user_ids, cx))
453 .await?;
454 let mut collaborators = HashMap::default();
455 for message in response.collaborators {
456 let collaborator = Collaborator::from_proto(message, &user_store, cx).await?;
457 collaborators.insert(collaborator.peer_id, collaborator);
458 }
459
460 this.update(cx, |this, _| {
461 this.collaborators = collaborators;
462 });
463
464 Ok(this)
465 }
466
467 #[cfg(any(test, feature = "test-support"))]
468 pub fn test(fs: Arc<dyn Fs>, cx: &mut gpui::TestAppContext) -> ModelHandle<Project> {
469 let languages = Arc::new(LanguageRegistry::test());
470 let http_client = client::test::FakeHttpClient::with_404_response();
471 let client = client::Client::new(http_client.clone());
472 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
473 cx.update(|cx| Project::local(client, user_store, languages, fs, cx))
474 }
475
476 pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
477 self.opened_buffers
478 .get(&remote_id)
479 .and_then(|buffer| buffer.upgrade(cx))
480 }
481
482 #[cfg(any(test, feature = "test-support"))]
483 pub fn languages(&self) -> &Arc<LanguageRegistry> {
484 &self.languages
485 }
486
487 #[cfg(any(test, feature = "test-support"))]
488 pub fn check_invariants(&self, cx: &AppContext) {
489 if self.is_local() {
490 let mut worktree_root_paths = HashMap::default();
491 for worktree in self.worktrees(cx) {
492 let worktree = worktree.read(cx);
493 let abs_path = worktree.as_local().unwrap().abs_path().clone();
494 let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
495 assert_eq!(
496 prev_worktree_id,
497 None,
498 "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
499 abs_path,
500 worktree.id(),
501 prev_worktree_id
502 )
503 }
504 } else {
505 let replica_id = self.replica_id();
506 for buffer in self.opened_buffers.values() {
507 if let Some(buffer) = buffer.upgrade(cx) {
508 let buffer = buffer.read(cx);
509 assert_eq!(
510 buffer.deferred_ops_len(),
511 0,
512 "replica {}, buffer {} has deferred operations",
513 replica_id,
514 buffer.remote_id()
515 );
516 }
517 }
518 }
519 }
520
521 #[cfg(any(test, feature = "test-support"))]
522 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
523 let path = path.into();
524 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
525 self.opened_buffers.iter().any(|(_, buffer)| {
526 if let Some(buffer) = buffer.upgrade(cx) {
527 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
528 if file.worktree == worktree && file.path() == &path.path {
529 return true;
530 }
531 }
532 }
533 false
534 })
535 } else {
536 false
537 }
538 }
539
540 pub fn fs(&self) -> &Arc<dyn Fs> {
541 &self.fs
542 }
543
544 fn unregister(&mut self, cx: &mut ModelContext<Self>) {
545 self.unshare(cx);
546 for worktree in &self.worktrees {
547 if let Some(worktree) = worktree.upgrade(cx) {
548 worktree.update(cx, |worktree, _| {
549 worktree.as_local_mut().unwrap().unregister();
550 });
551 }
552 }
553
554 if let ProjectClientState::Local { remote_id_tx, .. } = &mut self.client_state {
555 *remote_id_tx.borrow_mut() = None;
556 }
557
558 self.subscriptions.clear();
559 }
560
561 fn register(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
562 self.unregister(cx);
563
564 let response = self.client.request(proto::RegisterProject {});
565 cx.spawn(|this, mut cx| async move {
566 let remote_id = response.await?.project_id;
567
568 let mut registrations = Vec::new();
569 this.update(&mut cx, |this, cx| {
570 if let ProjectClientState::Local { remote_id_tx, .. } = &mut this.client_state {
571 *remote_id_tx.borrow_mut() = Some(remote_id);
572 }
573
574 cx.emit(Event::RemoteIdChanged(Some(remote_id)));
575
576 this.subscriptions
577 .push(this.client.add_model_for_remote_entity(remote_id, cx));
578
579 for worktree in &this.worktrees {
580 if let Some(worktree) = worktree.upgrade(cx) {
581 registrations.push(worktree.update(cx, |worktree, cx| {
582 let worktree = worktree.as_local_mut().unwrap();
583 worktree.register(remote_id, cx)
584 }));
585 }
586 }
587 });
588
589 futures::future::try_join_all(registrations).await?;
590 Ok(())
591 })
592 }
593
594 pub fn remote_id(&self) -> Option<u64> {
595 match &self.client_state {
596 ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
597 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
598 }
599 }
600
601 pub fn next_remote_id(&self) -> impl Future<Output = u64> {
602 let mut id = None;
603 let mut watch = None;
604 match &self.client_state {
605 ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
606 ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
607 }
608
609 async move {
610 if let Some(id) = id {
611 return id;
612 }
613 let mut watch = watch.unwrap();
614 loop {
615 let id = *watch.borrow();
616 if let Some(id) = id {
617 return id;
618 }
619 watch.next().await;
620 }
621 }
622 }
623
624 pub fn replica_id(&self) -> ReplicaId {
625 match &self.client_state {
626 ProjectClientState::Local { .. } => 0,
627 ProjectClientState::Remote { replica_id, .. } => *replica_id,
628 }
629 }
630
631 pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
632 &self.collaborators
633 }
634
635 pub fn worktrees<'a>(
636 &'a self,
637 cx: &'a AppContext,
638 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
639 self.worktrees
640 .iter()
641 .filter_map(move |worktree| worktree.upgrade(cx))
642 }
643
644 pub fn visible_worktrees<'a>(
645 &'a self,
646 cx: &'a AppContext,
647 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
648 self.worktrees.iter().filter_map(|worktree| {
649 worktree.upgrade(cx).and_then(|worktree| {
650 if worktree.read(cx).is_visible() {
651 Some(worktree)
652 } else {
653 None
654 }
655 })
656 })
657 }
658
659 pub fn worktree_for_id(
660 &self,
661 id: WorktreeId,
662 cx: &AppContext,
663 ) -> Option<ModelHandle<Worktree>> {
664 self.worktrees(cx)
665 .find(|worktree| worktree.read(cx).id() == id)
666 }
667
668 pub fn worktree_for_entry(
669 &self,
670 entry_id: ProjectEntryId,
671 cx: &AppContext,
672 ) -> Option<ModelHandle<Worktree>> {
673 self.worktrees(cx)
674 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
675 }
676
677 pub fn worktree_id_for_entry(
678 &self,
679 entry_id: ProjectEntryId,
680 cx: &AppContext,
681 ) -> Option<WorktreeId> {
682 self.worktree_for_entry(entry_id, cx)
683 .map(|worktree| worktree.read(cx).id())
684 }
685
686 pub fn share(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
687 let rpc = self.client.clone();
688 cx.spawn(|this, mut cx| async move {
689 let project_id = this.update(&mut cx, |this, cx| {
690 if let ProjectClientState::Local {
691 is_shared,
692 remote_id_rx,
693 ..
694 } = &mut this.client_state
695 {
696 *is_shared = true;
697
698 for open_buffer in this.opened_buffers.values_mut() {
699 match open_buffer {
700 OpenBuffer::Strong(_) => {}
701 OpenBuffer::Weak(buffer) => {
702 if let Some(buffer) = buffer.upgrade(cx) {
703 *open_buffer = OpenBuffer::Strong(buffer);
704 }
705 }
706 OpenBuffer::Loading(_) => unreachable!(),
707 }
708 }
709
710 for worktree_handle in this.worktrees.iter_mut() {
711 match worktree_handle {
712 WorktreeHandle::Strong(_) => {}
713 WorktreeHandle::Weak(worktree) => {
714 if let Some(worktree) = worktree.upgrade(cx) {
715 *worktree_handle = WorktreeHandle::Strong(worktree);
716 }
717 }
718 }
719 }
720
721 remote_id_rx
722 .borrow()
723 .ok_or_else(|| anyhow!("no project id"))
724 } else {
725 Err(anyhow!("can't share a remote project"))
726 }
727 })?;
728
729 rpc.request(proto::ShareProject { project_id }).await?;
730
731 let mut tasks = Vec::new();
732 this.update(&mut cx, |this, cx| {
733 for worktree in this.worktrees(cx).collect::<Vec<_>>() {
734 worktree.update(cx, |worktree, cx| {
735 let worktree = worktree.as_local_mut().unwrap();
736 tasks.push(worktree.share(project_id, cx));
737 });
738 }
739 });
740 for task in tasks {
741 task.await?;
742 }
743 this.update(&mut cx, |_, cx| cx.notify());
744 Ok(())
745 })
746 }
747
748 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) {
749 let rpc = self.client.clone();
750
751 if let ProjectClientState::Local {
752 is_shared,
753 remote_id_rx,
754 ..
755 } = &mut self.client_state
756 {
757 if !*is_shared {
758 return;
759 }
760
761 *is_shared = false;
762 self.collaborators.clear();
763 self.shared_buffers.clear();
764 for worktree_handle in self.worktrees.iter_mut() {
765 if let WorktreeHandle::Strong(worktree) = worktree_handle {
766 let is_visible = worktree.update(cx, |worktree, _| {
767 worktree.as_local_mut().unwrap().unshare();
768 worktree.is_visible()
769 });
770 if !is_visible {
771 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
772 }
773 }
774 }
775
776 for open_buffer in self.opened_buffers.values_mut() {
777 match open_buffer {
778 OpenBuffer::Strong(buffer) => {
779 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
780 }
781 _ => {}
782 }
783 }
784
785 if let Some(project_id) = *remote_id_rx.borrow() {
786 rpc.send(proto::UnshareProject { project_id }).log_err();
787 }
788
789 cx.notify();
790 } else {
791 log::error!("attempted to unshare a remote project");
792 }
793 }
794
795 fn project_unshared(&mut self, cx: &mut ModelContext<Self>) {
796 if let ProjectClientState::Remote {
797 sharing_has_stopped,
798 ..
799 } = &mut self.client_state
800 {
801 *sharing_has_stopped = true;
802 self.collaborators.clear();
803 cx.notify();
804 }
805 }
806
807 pub fn is_read_only(&self) -> bool {
808 match &self.client_state {
809 ProjectClientState::Local { .. } => false,
810 ProjectClientState::Remote {
811 sharing_has_stopped,
812 ..
813 } => *sharing_has_stopped,
814 }
815 }
816
817 pub fn is_local(&self) -> bool {
818 match &self.client_state {
819 ProjectClientState::Local { .. } => true,
820 ProjectClientState::Remote { .. } => false,
821 }
822 }
823
824 pub fn is_remote(&self) -> bool {
825 !self.is_local()
826 }
827
828 pub fn create_buffer(&mut self, cx: &mut ModelContext<Self>) -> Result<ModelHandle<Buffer>> {
829 if self.is_remote() {
830 return Err(anyhow!("creating buffers as a guest is not supported yet"));
831 }
832
833 let buffer = cx.add_model(|cx| {
834 Buffer::new(self.replica_id(), "", cx).with_language(language::PLAIN_TEXT.clone(), cx)
835 });
836 self.register_buffer(&buffer, cx)?;
837 Ok(buffer)
838 }
839
840 pub fn open_path(
841 &mut self,
842 path: impl Into<ProjectPath>,
843 cx: &mut ModelContext<Self>,
844 ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
845 let task = self.open_buffer(path, cx);
846 cx.spawn_weak(|_, cx| async move {
847 let buffer = task.await?;
848 let project_entry_id = buffer
849 .read_with(&cx, |buffer, cx| {
850 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
851 })
852 .ok_or_else(|| anyhow!("no project entry"))?;
853 Ok((project_entry_id, buffer.into()))
854 })
855 }
856
857 pub fn open_buffer(
858 &mut self,
859 path: impl Into<ProjectPath>,
860 cx: &mut ModelContext<Self>,
861 ) -> Task<Result<ModelHandle<Buffer>>> {
862 let project_path = path.into();
863 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
864 worktree
865 } else {
866 return Task::ready(Err(anyhow!("no such worktree")));
867 };
868
869 // If there is already a buffer for the given path, then return it.
870 let existing_buffer = self.get_open_buffer(&project_path, cx);
871 if let Some(existing_buffer) = existing_buffer {
872 return Task::ready(Ok(existing_buffer));
873 }
874
875 let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
876 // If the given path is already being loaded, then wait for that existing
877 // task to complete and return the same buffer.
878 hash_map::Entry::Occupied(e) => e.get().clone(),
879
880 // Otherwise, record the fact that this path is now being loaded.
881 hash_map::Entry::Vacant(entry) => {
882 let (mut tx, rx) = postage::watch::channel();
883 entry.insert(rx.clone());
884
885 let load_buffer = if worktree.read(cx).is_local() {
886 self.open_local_buffer(&project_path.path, &worktree, cx)
887 } else {
888 self.open_remote_buffer(&project_path.path, &worktree, cx)
889 };
890
891 cx.spawn(move |this, mut cx| async move {
892 let load_result = load_buffer.await;
893 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
894 // Record the fact that the buffer is no longer loading.
895 this.loading_buffers.remove(&project_path);
896 let buffer = load_result.map_err(Arc::new)?;
897 Ok(buffer)
898 }));
899 })
900 .detach();
901 rx
902 }
903 };
904
905 cx.foreground().spawn(async move {
906 loop {
907 if let Some(result) = loading_watch.borrow().as_ref() {
908 match result {
909 Ok(buffer) => return Ok(buffer.clone()),
910 Err(error) => return Err(anyhow!("{}", error)),
911 }
912 }
913 loading_watch.next().await;
914 }
915 })
916 }
917
918 fn open_local_buffer(
919 &mut self,
920 path: &Arc<Path>,
921 worktree: &ModelHandle<Worktree>,
922 cx: &mut ModelContext<Self>,
923 ) -> Task<Result<ModelHandle<Buffer>>> {
924 let load_buffer = worktree.update(cx, |worktree, cx| {
925 let worktree = worktree.as_local_mut().unwrap();
926 worktree.load_buffer(path, cx)
927 });
928 cx.spawn(|this, mut cx| async move {
929 let buffer = load_buffer.await?;
930 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
931 Ok(buffer)
932 })
933 }
934
935 fn open_remote_buffer(
936 &mut self,
937 path: &Arc<Path>,
938 worktree: &ModelHandle<Worktree>,
939 cx: &mut ModelContext<Self>,
940 ) -> Task<Result<ModelHandle<Buffer>>> {
941 let rpc = self.client.clone();
942 let project_id = self.remote_id().unwrap();
943 let remote_worktree_id = worktree.read(cx).id();
944 let path = path.clone();
945 let path_string = path.to_string_lossy().to_string();
946 cx.spawn(|this, mut cx| async move {
947 let response = rpc
948 .request(proto::OpenBufferByPath {
949 project_id,
950 worktree_id: remote_worktree_id.to_proto(),
951 path: path_string,
952 })
953 .await?;
954 let buffer = response.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
955 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
956 .await
957 })
958 }
959
960 fn open_local_buffer_via_lsp(
961 &mut self,
962 abs_path: lsp::Url,
963 lsp_adapter: Arc<dyn LspAdapter>,
964 lsp_server: Arc<LanguageServer>,
965 cx: &mut ModelContext<Self>,
966 ) -> Task<Result<ModelHandle<Buffer>>> {
967 cx.spawn(|this, mut cx| async move {
968 let abs_path = abs_path
969 .to_file_path()
970 .map_err(|_| anyhow!("can't convert URI to path"))?;
971 let (worktree, relative_path) = if let Some(result) =
972 this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
973 {
974 result
975 } else {
976 let worktree = this
977 .update(&mut cx, |this, cx| {
978 this.create_local_worktree(&abs_path, false, cx)
979 })
980 .await?;
981 this.update(&mut cx, |this, cx| {
982 this.language_servers.insert(
983 (worktree.read(cx).id(), lsp_adapter.name()),
984 (lsp_adapter, lsp_server),
985 );
986 });
987 (worktree, PathBuf::new())
988 };
989
990 let project_path = ProjectPath {
991 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
992 path: relative_path.into(),
993 };
994 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
995 .await
996 })
997 }
998
999 pub fn open_buffer_by_id(
1000 &mut self,
1001 id: u64,
1002 cx: &mut ModelContext<Self>,
1003 ) -> Task<Result<ModelHandle<Buffer>>> {
1004 if let Some(buffer) = self.buffer_for_id(id, cx) {
1005 Task::ready(Ok(buffer))
1006 } else if self.is_local() {
1007 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1008 } else if let Some(project_id) = self.remote_id() {
1009 let request = self
1010 .client
1011 .request(proto::OpenBufferById { project_id, id });
1012 cx.spawn(|this, mut cx| async move {
1013 let buffer = request
1014 .await?
1015 .buffer
1016 .ok_or_else(|| anyhow!("invalid buffer"))?;
1017 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1018 .await
1019 })
1020 } else {
1021 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1022 }
1023 }
1024
1025 pub fn save_buffer_as(
1026 &mut self,
1027 buffer: ModelHandle<Buffer>,
1028 abs_path: PathBuf,
1029 cx: &mut ModelContext<Project>,
1030 ) -> Task<Result<()>> {
1031 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1032 cx.spawn(|this, mut cx| async move {
1033 let (worktree, path) = worktree_task.await?;
1034 worktree
1035 .update(&mut cx, |worktree, cx| {
1036 worktree
1037 .as_local_mut()
1038 .unwrap()
1039 .save_buffer_as(buffer.clone(), path, cx)
1040 })
1041 .await?;
1042 this.update(&mut cx, |this, cx| {
1043 this.assign_language_to_buffer(&buffer, cx);
1044 this.register_buffer_with_language_server(&buffer, cx);
1045 });
1046 Ok(())
1047 })
1048 }
1049
1050 pub fn get_open_buffer(
1051 &mut self,
1052 path: &ProjectPath,
1053 cx: &mut ModelContext<Self>,
1054 ) -> Option<ModelHandle<Buffer>> {
1055 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1056 self.opened_buffers.values().find_map(|buffer| {
1057 let buffer = buffer.upgrade(cx)?;
1058 let file = File::from_dyn(buffer.read(cx).file())?;
1059 if file.worktree == worktree && file.path() == &path.path {
1060 Some(buffer)
1061 } else {
1062 None
1063 }
1064 })
1065 }
1066
1067 fn register_buffer(
1068 &mut self,
1069 buffer: &ModelHandle<Buffer>,
1070 cx: &mut ModelContext<Self>,
1071 ) -> Result<()> {
1072 let remote_id = buffer.read(cx).remote_id();
1073 let open_buffer = if self.is_remote() || self.is_shared() {
1074 OpenBuffer::Strong(buffer.clone())
1075 } else {
1076 OpenBuffer::Weak(buffer.downgrade())
1077 };
1078
1079 match self.opened_buffers.insert(remote_id, open_buffer) {
1080 None => {}
1081 Some(OpenBuffer::Loading(operations)) => {
1082 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1083 }
1084 Some(OpenBuffer::Weak(existing_handle)) => {
1085 if existing_handle.upgrade(cx).is_some() {
1086 Err(anyhow!(
1087 "already registered buffer with remote id {}",
1088 remote_id
1089 ))?
1090 }
1091 }
1092 Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1093 "already registered buffer with remote id {}",
1094 remote_id
1095 ))?,
1096 }
1097 cx.subscribe(buffer, |this, buffer, event, cx| {
1098 this.on_buffer_event(buffer, event, cx);
1099 })
1100 .detach();
1101
1102 self.assign_language_to_buffer(buffer, cx);
1103 self.register_buffer_with_language_server(buffer, cx);
1104
1105 Ok(())
1106 }
1107
1108 fn register_buffer_with_language_server(
1109 &mut self,
1110 buffer_handle: &ModelHandle<Buffer>,
1111 cx: &mut ModelContext<Self>,
1112 ) {
1113 let buffer = buffer_handle.read(cx);
1114 let buffer_id = buffer.remote_id();
1115 if let Some(file) = File::from_dyn(buffer.file()) {
1116 if file.is_local() {
1117 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1118 let initial_snapshot = buffer.text_snapshot();
1119 let language_server = self.language_server_for_buffer(buffer, cx).cloned();
1120
1121 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1122 if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1123 self.update_buffer_diagnostics(&buffer_handle, diagnostics, None, cx)
1124 .log_err();
1125 }
1126 }
1127
1128 if let Some((_, server)) = language_server {
1129 server
1130 .notify::<lsp::notification::DidOpenTextDocument>(
1131 lsp::DidOpenTextDocumentParams {
1132 text_document: lsp::TextDocumentItem::new(
1133 uri,
1134 Default::default(),
1135 0,
1136 initial_snapshot.text(),
1137 ),
1138 }
1139 .clone(),
1140 )
1141 .log_err();
1142 buffer_handle.update(cx, |buffer, cx| {
1143 buffer.set_completion_triggers(
1144 server
1145 .capabilities()
1146 .completion_provider
1147 .as_ref()
1148 .and_then(|provider| provider.trigger_characters.clone())
1149 .unwrap_or(Vec::new()),
1150 cx,
1151 )
1152 });
1153 self.buffer_snapshots
1154 .insert(buffer_id, vec![(0, initial_snapshot)]);
1155 }
1156
1157 cx.observe_release(buffer_handle, |this, buffer, cx| {
1158 if let Some(file) = File::from_dyn(buffer.file()) {
1159 if file.is_local() {
1160 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1161 if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1162 server
1163 .notify::<lsp::notification::DidCloseTextDocument>(
1164 lsp::DidCloseTextDocumentParams {
1165 text_document: lsp::TextDocumentIdentifier::new(
1166 uri.clone(),
1167 ),
1168 },
1169 )
1170 .log_err();
1171 }
1172 }
1173 }
1174 })
1175 .detach();
1176 }
1177 }
1178 }
1179
1180 fn on_buffer_event(
1181 &mut self,
1182 buffer: ModelHandle<Buffer>,
1183 event: &BufferEvent,
1184 cx: &mut ModelContext<Self>,
1185 ) -> Option<()> {
1186 match event {
1187 BufferEvent::Operation(operation) => {
1188 let project_id = self.remote_id()?;
1189 let request = self.client.request(proto::UpdateBuffer {
1190 project_id,
1191 buffer_id: buffer.read(cx).remote_id(),
1192 operations: vec![language::proto::serialize_operation(&operation)],
1193 });
1194 cx.background().spawn(request).detach_and_log_err(cx);
1195 }
1196 BufferEvent::Edited { .. } => {
1197 let (_, language_server) = self
1198 .language_server_for_buffer(buffer.read(cx), cx)?
1199 .clone();
1200 let buffer = buffer.read(cx);
1201 let file = File::from_dyn(buffer.file())?;
1202 let abs_path = file.as_local()?.abs_path(cx);
1203 let uri = lsp::Url::from_file_path(abs_path).unwrap();
1204 let buffer_snapshots = self.buffer_snapshots.entry(buffer.remote_id()).or_default();
1205 let (version, prev_snapshot) = buffer_snapshots.last()?;
1206 let next_snapshot = buffer.text_snapshot();
1207 let next_version = version + 1;
1208
1209 let content_changes = buffer
1210 .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1211 .map(|edit| {
1212 let edit_start = edit.new.start.0;
1213 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1214 let new_text = next_snapshot
1215 .text_for_range(edit.new.start.1..edit.new.end.1)
1216 .collect();
1217 lsp::TextDocumentContentChangeEvent {
1218 range: Some(lsp::Range::new(
1219 point_to_lsp(edit_start),
1220 point_to_lsp(edit_end),
1221 )),
1222 range_length: None,
1223 text: new_text,
1224 }
1225 })
1226 .collect();
1227
1228 buffer_snapshots.push((next_version, next_snapshot));
1229
1230 language_server
1231 .notify::<lsp::notification::DidChangeTextDocument>(
1232 lsp::DidChangeTextDocumentParams {
1233 text_document: lsp::VersionedTextDocumentIdentifier::new(
1234 uri,
1235 next_version,
1236 ),
1237 content_changes,
1238 },
1239 )
1240 .log_err();
1241 }
1242 BufferEvent::Saved => {
1243 let file = File::from_dyn(buffer.read(cx).file())?;
1244 let worktree_id = file.worktree_id(cx);
1245 let abs_path = file.as_local()?.abs_path(cx);
1246 let text_document = lsp::TextDocumentIdentifier {
1247 uri: lsp::Url::from_file_path(abs_path).unwrap(),
1248 };
1249
1250 for (_, server) in self.language_servers_for_worktree(worktree_id) {
1251 server
1252 .notify::<lsp::notification::DidSaveTextDocument>(
1253 lsp::DidSaveTextDocumentParams {
1254 text_document: text_document.clone(),
1255 text: None,
1256 },
1257 )
1258 .log_err();
1259 }
1260 }
1261 _ => {}
1262 }
1263
1264 None
1265 }
1266
1267 fn language_servers_for_worktree(
1268 &self,
1269 worktree_id: WorktreeId,
1270 ) -> impl Iterator<Item = &(Arc<dyn LspAdapter>, Arc<LanguageServer>)> {
1271 self.language_servers.iter().filter_map(
1272 move |((language_server_worktree_id, _), server)| {
1273 if *language_server_worktree_id == worktree_id {
1274 Some(server)
1275 } else {
1276 None
1277 }
1278 },
1279 )
1280 }
1281
1282 fn assign_language_to_buffer(
1283 &mut self,
1284 buffer: &ModelHandle<Buffer>,
1285 cx: &mut ModelContext<Self>,
1286 ) -> Option<()> {
1287 // If the buffer has a language, set it and start the language server if we haven't already.
1288 let full_path = buffer.read(cx).file()?.full_path(cx);
1289 let language = self.languages.select_language(&full_path)?;
1290 buffer.update(cx, |buffer, cx| {
1291 buffer.set_language(Some(language.clone()), cx);
1292 });
1293
1294 let file = File::from_dyn(buffer.read(cx).file())?;
1295 let worktree = file.worktree.read(cx).as_local()?;
1296 let worktree_id = worktree.id();
1297 let worktree_abs_path = worktree.abs_path().clone();
1298 self.start_language_server(worktree_id, worktree_abs_path, language, cx);
1299
1300 None
1301 }
1302
1303 fn start_language_server(
1304 &mut self,
1305 worktree_id: WorktreeId,
1306 worktree_path: Arc<Path>,
1307 language: Arc<Language>,
1308 cx: &mut ModelContext<Self>,
1309 ) {
1310 let adapter = if let Some(adapter) = language.lsp_adapter() {
1311 adapter
1312 } else {
1313 return;
1314 };
1315 let key = (worktree_id, adapter.name());
1316 self.started_language_servers
1317 .entry(key.clone())
1318 .or_insert_with(|| {
1319 let server_id = post_inc(&mut self.next_language_server_id);
1320 let language_server = self.languages.start_language_server(
1321 server_id,
1322 language.clone(),
1323 worktree_path,
1324 self.client.http_client(),
1325 cx,
1326 );
1327 cx.spawn_weak(|this, mut cx| async move {
1328 let language_server = language_server?.await.log_err()?;
1329 let this = this.upgrade(&cx)?;
1330 let (language_server_events_tx, language_server_events_rx) =
1331 smol::channel::unbounded();
1332
1333 language_server
1334 .on_notification::<lsp::notification::PublishDiagnostics, _>({
1335 let language_server_events_tx = language_server_events_tx.clone();
1336 move |params, _| {
1337 language_server_events_tx
1338 .try_send(LanguageServerEvent::DiagnosticsUpdate(params))
1339 .ok();
1340 }
1341 })
1342 .detach();
1343
1344 language_server
1345 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
1346 let settings = this
1347 .read_with(&cx, |this, _| this.language_server_settings.clone());
1348 move |params, _| {
1349 let settings = settings.lock().clone();
1350 async move {
1351 Ok(params
1352 .items
1353 .into_iter()
1354 .map(|item| {
1355 if let Some(section) = &item.section {
1356 settings
1357 .get(section)
1358 .cloned()
1359 .unwrap_or(serde_json::Value::Null)
1360 } else {
1361 settings.clone()
1362 }
1363 })
1364 .collect())
1365 }
1366 }
1367 })
1368 .detach();
1369
1370 language_server
1371 .on_notification::<lsp::notification::Progress, _>(move |params, _| {
1372 let token = match params.token {
1373 lsp::NumberOrString::String(token) => token,
1374 lsp::NumberOrString::Number(token) => {
1375 log::info!("skipping numeric progress token {}", token);
1376 return;
1377 }
1378 };
1379
1380 match params.value {
1381 lsp::ProgressParamsValue::WorkDone(progress) => match progress {
1382 lsp::WorkDoneProgress::Begin(_) => {
1383 language_server_events_tx
1384 .try_send(LanguageServerEvent::WorkStart { token })
1385 .ok();
1386 }
1387 lsp::WorkDoneProgress::Report(report) => {
1388 language_server_events_tx
1389 .try_send(LanguageServerEvent::WorkProgress {
1390 token,
1391 progress: LanguageServerProgress {
1392 message: report.message,
1393 percentage: report
1394 .percentage
1395 .map(|p| p as usize),
1396 last_update_at: Instant::now(),
1397 },
1398 })
1399 .ok();
1400 }
1401 lsp::WorkDoneProgress::End(_) => {
1402 language_server_events_tx
1403 .try_send(LanguageServerEvent::WorkEnd { token })
1404 .ok();
1405 }
1406 },
1407 }
1408 })
1409 .detach();
1410
1411 let language_server = language_server
1412 .initialize(adapter.initialization_options())
1413 .await
1414 .log_err()?;
1415
1416 // Process all the LSP events.
1417 cx.spawn(|mut cx| {
1418 let this = this.downgrade();
1419 async move {
1420 while let Ok(event) = language_server_events_rx.recv().await {
1421 let this = this.upgrade(&cx)?;
1422 this.update(&mut cx, |this, cx| {
1423 this.on_lsp_event(server_id, event, &language, cx)
1424 });
1425
1426 // Don't starve the main thread when lots of events arrive all at once.
1427 smol::future::yield_now().await;
1428 }
1429 Some(())
1430 }
1431 })
1432 .detach();
1433
1434 this.update(&mut cx, |this, cx| {
1435 this.language_servers
1436 .insert(key.clone(), (adapter, language_server.clone()));
1437 this.language_server_statuses.insert(
1438 server_id,
1439 LanguageServerStatus {
1440 name: language_server.name().to_string(),
1441 pending_work: Default::default(),
1442 pending_diagnostic_updates: 0,
1443 },
1444 );
1445 language_server
1446 .notify::<lsp::notification::DidChangeConfiguration>(
1447 lsp::DidChangeConfigurationParams {
1448 settings: this.language_server_settings.lock().clone(),
1449 },
1450 )
1451 .ok();
1452
1453 if let Some(project_id) = this.remote_id() {
1454 this.client
1455 .send(proto::StartLanguageServer {
1456 project_id,
1457 server: Some(proto::LanguageServer {
1458 id: server_id as u64,
1459 name: language_server.name().to_string(),
1460 }),
1461 })
1462 .log_err();
1463 }
1464
1465 // Tell the language server about every open buffer in the worktree that matches the language.
1466 for buffer in this.opened_buffers.values() {
1467 if let Some(buffer_handle) = buffer.upgrade(cx) {
1468 let buffer = buffer_handle.read(cx);
1469 let file = if let Some(file) = File::from_dyn(buffer.file()) {
1470 file
1471 } else {
1472 continue;
1473 };
1474 let language = if let Some(language) = buffer.language() {
1475 language
1476 } else {
1477 continue;
1478 };
1479 if file.worktree.read(cx).id() != key.0
1480 || language.lsp_adapter().map(|a| a.name())
1481 != Some(key.1.clone())
1482 {
1483 continue;
1484 }
1485
1486 let file = file.as_local()?;
1487 let versions = this
1488 .buffer_snapshots
1489 .entry(buffer.remote_id())
1490 .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
1491 let (version, initial_snapshot) = versions.last().unwrap();
1492 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1493 language_server
1494 .notify::<lsp::notification::DidOpenTextDocument>(
1495 lsp::DidOpenTextDocumentParams {
1496 text_document: lsp::TextDocumentItem::new(
1497 uri,
1498 Default::default(),
1499 *version,
1500 initial_snapshot.text(),
1501 ),
1502 },
1503 )
1504 .log_err()?;
1505 buffer_handle.update(cx, |buffer, cx| {
1506 buffer.set_completion_triggers(
1507 language_server
1508 .capabilities()
1509 .completion_provider
1510 .as_ref()
1511 .and_then(|provider| {
1512 provider.trigger_characters.clone()
1513 })
1514 .unwrap_or(Vec::new()),
1515 cx,
1516 )
1517 });
1518 }
1519 }
1520
1521 cx.notify();
1522 Some(())
1523 });
1524
1525 Some(language_server)
1526 })
1527 });
1528 }
1529
1530 pub fn restart_language_servers_for_buffers(
1531 &mut self,
1532 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
1533 cx: &mut ModelContext<Self>,
1534 ) -> Option<()> {
1535 let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
1536 .into_iter()
1537 .filter_map(|buffer| {
1538 let file = File::from_dyn(buffer.read(cx).file())?;
1539 let worktree = file.worktree.read(cx).as_local()?;
1540 let worktree_id = worktree.id();
1541 let worktree_abs_path = worktree.abs_path().clone();
1542 let full_path = file.full_path(cx);
1543 Some((worktree_id, worktree_abs_path, full_path))
1544 })
1545 .collect();
1546 for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
1547 let language = self.languages.select_language(&full_path)?;
1548 self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
1549 }
1550
1551 None
1552 }
1553
1554 fn restart_language_server(
1555 &mut self,
1556 worktree_id: WorktreeId,
1557 worktree_path: Arc<Path>,
1558 language: Arc<Language>,
1559 cx: &mut ModelContext<Self>,
1560 ) {
1561 let adapter = if let Some(adapter) = language.lsp_adapter() {
1562 adapter
1563 } else {
1564 return;
1565 };
1566 let key = (worktree_id, adapter.name());
1567 let server_to_shutdown = self.language_servers.remove(&key);
1568 self.started_language_servers.remove(&key);
1569 server_to_shutdown
1570 .as_ref()
1571 .map(|(_, server)| self.language_server_statuses.remove(&server.server_id()));
1572 cx.spawn_weak(|this, mut cx| async move {
1573 if let Some(this) = this.upgrade(&cx) {
1574 if let Some((_, server_to_shutdown)) = server_to_shutdown {
1575 if let Some(shutdown_task) = server_to_shutdown.shutdown() {
1576 shutdown_task.await;
1577 }
1578 }
1579
1580 this.update(&mut cx, |this, cx| {
1581 this.start_language_server(worktree_id, worktree_path, language, cx);
1582 });
1583 }
1584 })
1585 .detach();
1586 }
1587
1588 fn on_lsp_event(
1589 &mut self,
1590 language_server_id: usize,
1591 event: LanguageServerEvent,
1592 language: &Arc<Language>,
1593 cx: &mut ModelContext<Self>,
1594 ) {
1595 let disk_diagnostics_token = language.disk_based_diagnostics_progress_token();
1596 let language_server_status =
1597 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
1598 status
1599 } else {
1600 return;
1601 };
1602
1603 match event {
1604 LanguageServerEvent::WorkStart { token } => {
1605 if Some(token.as_str()) == disk_diagnostics_token {
1606 language_server_status.pending_diagnostic_updates += 1;
1607 if language_server_status.pending_diagnostic_updates == 1 {
1608 self.disk_based_diagnostics_started(cx);
1609 self.broadcast_language_server_update(
1610 language_server_id,
1611 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
1612 proto::LspDiskBasedDiagnosticsUpdating {},
1613 ),
1614 );
1615 }
1616 } else {
1617 self.on_lsp_work_start(language_server_id, token.clone(), cx);
1618 self.broadcast_language_server_update(
1619 language_server_id,
1620 proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
1621 token,
1622 }),
1623 );
1624 }
1625 }
1626 LanguageServerEvent::WorkProgress { token, progress } => {
1627 if Some(token.as_str()) != disk_diagnostics_token {
1628 self.on_lsp_work_progress(
1629 language_server_id,
1630 token.clone(),
1631 progress.clone(),
1632 cx,
1633 );
1634 self.broadcast_language_server_update(
1635 language_server_id,
1636 proto::update_language_server::Variant::WorkProgress(
1637 proto::LspWorkProgress {
1638 token,
1639 message: progress.message,
1640 percentage: progress.percentage.map(|p| p as u32),
1641 },
1642 ),
1643 );
1644 }
1645 }
1646 LanguageServerEvent::WorkEnd { token } => {
1647 if Some(token.as_str()) == disk_diagnostics_token {
1648 language_server_status.pending_diagnostic_updates -= 1;
1649 if language_server_status.pending_diagnostic_updates == 0 {
1650 self.disk_based_diagnostics_finished(cx);
1651 self.broadcast_language_server_update(
1652 language_server_id,
1653 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1654 proto::LspDiskBasedDiagnosticsUpdated {},
1655 ),
1656 );
1657 }
1658 } else {
1659 self.on_lsp_work_end(language_server_id, token.clone(), cx);
1660 self.broadcast_language_server_update(
1661 language_server_id,
1662 proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
1663 token,
1664 }),
1665 );
1666 }
1667 }
1668 LanguageServerEvent::DiagnosticsUpdate(mut params) => {
1669 language.process_diagnostics(&mut params);
1670
1671 if disk_diagnostics_token.is_none() {
1672 self.disk_based_diagnostics_started(cx);
1673 self.broadcast_language_server_update(
1674 language_server_id,
1675 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
1676 proto::LspDiskBasedDiagnosticsUpdating {},
1677 ),
1678 );
1679 }
1680 self.update_diagnostics(params, language.disk_based_diagnostic_sources(), cx)
1681 .log_err();
1682 if disk_diagnostics_token.is_none() {
1683 self.disk_based_diagnostics_finished(cx);
1684 self.broadcast_language_server_update(
1685 language_server_id,
1686 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1687 proto::LspDiskBasedDiagnosticsUpdated {},
1688 ),
1689 );
1690 }
1691 }
1692 }
1693 }
1694
1695 fn on_lsp_work_start(
1696 &mut self,
1697 language_server_id: usize,
1698 token: String,
1699 cx: &mut ModelContext<Self>,
1700 ) {
1701 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
1702 status.pending_work.insert(
1703 token,
1704 LanguageServerProgress {
1705 message: None,
1706 percentage: None,
1707 last_update_at: Instant::now(),
1708 },
1709 );
1710 cx.notify();
1711 }
1712 }
1713
1714 fn on_lsp_work_progress(
1715 &mut self,
1716 language_server_id: usize,
1717 token: String,
1718 progress: LanguageServerProgress,
1719 cx: &mut ModelContext<Self>,
1720 ) {
1721 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
1722 status.pending_work.insert(token, progress);
1723 cx.notify();
1724 }
1725 }
1726
1727 fn on_lsp_work_end(
1728 &mut self,
1729 language_server_id: usize,
1730 token: String,
1731 cx: &mut ModelContext<Self>,
1732 ) {
1733 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
1734 status.pending_work.remove(&token);
1735 cx.notify();
1736 }
1737 }
1738
1739 fn broadcast_language_server_update(
1740 &self,
1741 language_server_id: usize,
1742 event: proto::update_language_server::Variant,
1743 ) {
1744 if let Some(project_id) = self.remote_id() {
1745 self.client
1746 .send(proto::UpdateLanguageServer {
1747 project_id,
1748 language_server_id: language_server_id as u64,
1749 variant: Some(event),
1750 })
1751 .log_err();
1752 }
1753 }
1754
1755 pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
1756 for (_, server) in self.language_servers.values() {
1757 server
1758 .notify::<lsp::notification::DidChangeConfiguration>(
1759 lsp::DidChangeConfigurationParams {
1760 settings: settings.clone(),
1761 },
1762 )
1763 .ok();
1764 }
1765 *self.language_server_settings.lock() = settings;
1766 }
1767
1768 pub fn language_server_statuses(
1769 &self,
1770 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
1771 self.language_server_statuses.values()
1772 }
1773
1774 pub fn update_diagnostics(
1775 &mut self,
1776 params: lsp::PublishDiagnosticsParams,
1777 disk_based_sources: &[&str],
1778 cx: &mut ModelContext<Self>,
1779 ) -> Result<()> {
1780 let abs_path = params
1781 .uri
1782 .to_file_path()
1783 .map_err(|_| anyhow!("URI is not a file"))?;
1784 let mut next_group_id = 0;
1785 let mut diagnostics = Vec::default();
1786 let mut primary_diagnostic_group_ids = HashMap::default();
1787 let mut sources_by_group_id = HashMap::default();
1788 let mut supporting_diagnostics = HashMap::default();
1789 for diagnostic in ¶ms.diagnostics {
1790 let source = diagnostic.source.as_ref();
1791 let code = diagnostic.code.as_ref().map(|code| match code {
1792 lsp::NumberOrString::Number(code) => code.to_string(),
1793 lsp::NumberOrString::String(code) => code.clone(),
1794 });
1795 let range = range_from_lsp(diagnostic.range);
1796 let is_supporting = diagnostic
1797 .related_information
1798 .as_ref()
1799 .map_or(false, |infos| {
1800 infos.iter().any(|info| {
1801 primary_diagnostic_group_ids.contains_key(&(
1802 source,
1803 code.clone(),
1804 range_from_lsp(info.location.range),
1805 ))
1806 })
1807 });
1808
1809 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
1810 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
1811 });
1812
1813 if is_supporting {
1814 supporting_diagnostics.insert(
1815 (source, code.clone(), range),
1816 (diagnostic.severity, is_unnecessary),
1817 );
1818 } else {
1819 let group_id = post_inc(&mut next_group_id);
1820 let is_disk_based = source.map_or(false, |source| {
1821 disk_based_sources.contains(&source.as_str())
1822 });
1823
1824 sources_by_group_id.insert(group_id, source);
1825 primary_diagnostic_group_ids
1826 .insert((source, code.clone(), range.clone()), group_id);
1827
1828 diagnostics.push(DiagnosticEntry {
1829 range,
1830 diagnostic: Diagnostic {
1831 code: code.clone(),
1832 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
1833 message: diagnostic.message.clone(),
1834 group_id,
1835 is_primary: true,
1836 is_valid: true,
1837 is_disk_based,
1838 is_unnecessary,
1839 },
1840 });
1841 if let Some(infos) = &diagnostic.related_information {
1842 for info in infos {
1843 if info.location.uri == params.uri && !info.message.is_empty() {
1844 let range = range_from_lsp(info.location.range);
1845 diagnostics.push(DiagnosticEntry {
1846 range,
1847 diagnostic: Diagnostic {
1848 code: code.clone(),
1849 severity: DiagnosticSeverity::INFORMATION,
1850 message: info.message.clone(),
1851 group_id,
1852 is_primary: false,
1853 is_valid: true,
1854 is_disk_based,
1855 is_unnecessary: false,
1856 },
1857 });
1858 }
1859 }
1860 }
1861 }
1862 }
1863
1864 for entry in &mut diagnostics {
1865 let diagnostic = &mut entry.diagnostic;
1866 if !diagnostic.is_primary {
1867 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
1868 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
1869 source,
1870 diagnostic.code.clone(),
1871 entry.range.clone(),
1872 )) {
1873 if let Some(severity) = severity {
1874 diagnostic.severity = severity;
1875 }
1876 diagnostic.is_unnecessary = is_unnecessary;
1877 }
1878 }
1879 }
1880
1881 self.update_diagnostic_entries(abs_path, params.version, diagnostics, cx)?;
1882 Ok(())
1883 }
1884
1885 pub fn update_diagnostic_entries(
1886 &mut self,
1887 abs_path: PathBuf,
1888 version: Option<i32>,
1889 diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
1890 cx: &mut ModelContext<Project>,
1891 ) -> Result<(), anyhow::Error> {
1892 let (worktree, relative_path) = self
1893 .find_local_worktree(&abs_path, cx)
1894 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
1895 if !worktree.read(cx).is_visible() {
1896 return Ok(());
1897 }
1898
1899 let project_path = ProjectPath {
1900 worktree_id: worktree.read(cx).id(),
1901 path: relative_path.into(),
1902 };
1903
1904 for buffer in self.opened_buffers.values() {
1905 if let Some(buffer) = buffer.upgrade(cx) {
1906 if buffer
1907 .read(cx)
1908 .file()
1909 .map_or(false, |file| *file.path() == project_path.path)
1910 {
1911 self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
1912 break;
1913 }
1914 }
1915 }
1916 worktree.update(cx, |worktree, cx| {
1917 worktree
1918 .as_local_mut()
1919 .ok_or_else(|| anyhow!("not a local worktree"))?
1920 .update_diagnostics(project_path.path.clone(), diagnostics, cx)
1921 })?;
1922 cx.emit(Event::DiagnosticsUpdated(project_path));
1923 Ok(())
1924 }
1925
1926 fn update_buffer_diagnostics(
1927 &mut self,
1928 buffer: &ModelHandle<Buffer>,
1929 mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
1930 version: Option<i32>,
1931 cx: &mut ModelContext<Self>,
1932 ) -> Result<()> {
1933 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
1934 Ordering::Equal
1935 .then_with(|| b.is_primary.cmp(&a.is_primary))
1936 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
1937 .then_with(|| a.severity.cmp(&b.severity))
1938 .then_with(|| a.message.cmp(&b.message))
1939 }
1940
1941 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
1942
1943 diagnostics.sort_unstable_by(|a, b| {
1944 Ordering::Equal
1945 .then_with(|| a.range.start.cmp(&b.range.start))
1946 .then_with(|| b.range.end.cmp(&a.range.end))
1947 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
1948 });
1949
1950 let mut sanitized_diagnostics = Vec::new();
1951 let edits_since_save = Patch::new(
1952 snapshot
1953 .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
1954 .collect(),
1955 );
1956 for entry in diagnostics {
1957 let start;
1958 let end;
1959 if entry.diagnostic.is_disk_based {
1960 // Some diagnostics are based on files on disk instead of buffers'
1961 // current contents. Adjust these diagnostics' ranges to reflect
1962 // any unsaved edits.
1963 start = edits_since_save.old_to_new(entry.range.start);
1964 end = edits_since_save.old_to_new(entry.range.end);
1965 } else {
1966 start = entry.range.start;
1967 end = entry.range.end;
1968 }
1969
1970 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
1971 ..snapshot.clip_point_utf16(end, Bias::Right);
1972
1973 // Expand empty ranges by one character
1974 if range.start == range.end {
1975 range.end.column += 1;
1976 range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
1977 if range.start == range.end && range.end.column > 0 {
1978 range.start.column -= 1;
1979 range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
1980 }
1981 }
1982
1983 sanitized_diagnostics.push(DiagnosticEntry {
1984 range,
1985 diagnostic: entry.diagnostic,
1986 });
1987 }
1988 drop(edits_since_save);
1989
1990 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
1991 buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
1992 Ok(())
1993 }
1994
1995 pub fn format(
1996 &self,
1997 buffers: HashSet<ModelHandle<Buffer>>,
1998 push_to_history: bool,
1999 cx: &mut ModelContext<Project>,
2000 ) -> Task<Result<ProjectTransaction>> {
2001 let mut local_buffers = Vec::new();
2002 let mut remote_buffers = None;
2003 for buffer_handle in buffers {
2004 let buffer = buffer_handle.read(cx);
2005 if let Some(file) = File::from_dyn(buffer.file()) {
2006 if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
2007 if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
2008 local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
2009 }
2010 } else {
2011 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2012 }
2013 } else {
2014 return Task::ready(Ok(Default::default()));
2015 }
2016 }
2017
2018 let remote_buffers = self.remote_id().zip(remote_buffers);
2019 let client = self.client.clone();
2020
2021 cx.spawn(|this, mut cx| async move {
2022 let mut project_transaction = ProjectTransaction::default();
2023
2024 if let Some((project_id, remote_buffers)) = remote_buffers {
2025 let response = client
2026 .request(proto::FormatBuffers {
2027 project_id,
2028 buffer_ids: remote_buffers
2029 .iter()
2030 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2031 .collect(),
2032 })
2033 .await?
2034 .transaction
2035 .ok_or_else(|| anyhow!("missing transaction"))?;
2036 project_transaction = this
2037 .update(&mut cx, |this, cx| {
2038 this.deserialize_project_transaction(response, push_to_history, cx)
2039 })
2040 .await?;
2041 }
2042
2043 for (buffer, buffer_abs_path, language_server) in local_buffers {
2044 let text_document = lsp::TextDocumentIdentifier::new(
2045 lsp::Url::from_file_path(&buffer_abs_path).unwrap(),
2046 );
2047 let capabilities = &language_server.capabilities();
2048 let lsp_edits = if capabilities
2049 .document_formatting_provider
2050 .as_ref()
2051 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2052 {
2053 language_server
2054 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2055 text_document,
2056 options: lsp::FormattingOptions {
2057 tab_size: 4,
2058 insert_spaces: true,
2059 insert_final_newline: Some(true),
2060 ..Default::default()
2061 },
2062 work_done_progress_params: Default::default(),
2063 })
2064 .await?
2065 } else if capabilities
2066 .document_range_formatting_provider
2067 .as_ref()
2068 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2069 {
2070 let buffer_start = lsp::Position::new(0, 0);
2071 let buffer_end =
2072 buffer.read_with(&cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
2073 language_server
2074 .request::<lsp::request::RangeFormatting>(
2075 lsp::DocumentRangeFormattingParams {
2076 text_document,
2077 range: lsp::Range::new(buffer_start, buffer_end),
2078 options: lsp::FormattingOptions {
2079 tab_size: 4,
2080 insert_spaces: true,
2081 insert_final_newline: Some(true),
2082 ..Default::default()
2083 },
2084 work_done_progress_params: Default::default(),
2085 },
2086 )
2087 .await?
2088 } else {
2089 continue;
2090 };
2091
2092 if let Some(lsp_edits) = lsp_edits {
2093 let edits = this
2094 .update(&mut cx, |this, cx| {
2095 this.edits_from_lsp(&buffer, lsp_edits, None, cx)
2096 })
2097 .await?;
2098 buffer.update(&mut cx, |buffer, cx| {
2099 buffer.finalize_last_transaction();
2100 buffer.start_transaction();
2101 for (range, text) in edits {
2102 buffer.edit([range], text, cx);
2103 }
2104 if buffer.end_transaction(cx).is_some() {
2105 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2106 if !push_to_history {
2107 buffer.forget_transaction(transaction.id);
2108 }
2109 project_transaction.0.insert(cx.handle(), transaction);
2110 }
2111 });
2112 }
2113 }
2114
2115 Ok(project_transaction)
2116 })
2117 }
2118
2119 pub fn definition<T: ToPointUtf16>(
2120 &self,
2121 buffer: &ModelHandle<Buffer>,
2122 position: T,
2123 cx: &mut ModelContext<Self>,
2124 ) -> Task<Result<Vec<Location>>> {
2125 let position = position.to_point_utf16(buffer.read(cx));
2126 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
2127 }
2128
2129 pub fn references<T: ToPointUtf16>(
2130 &self,
2131 buffer: &ModelHandle<Buffer>,
2132 position: T,
2133 cx: &mut ModelContext<Self>,
2134 ) -> Task<Result<Vec<Location>>> {
2135 let position = position.to_point_utf16(buffer.read(cx));
2136 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
2137 }
2138
2139 pub fn document_highlights<T: ToPointUtf16>(
2140 &self,
2141 buffer: &ModelHandle<Buffer>,
2142 position: T,
2143 cx: &mut ModelContext<Self>,
2144 ) -> Task<Result<Vec<DocumentHighlight>>> {
2145 let position = position.to_point_utf16(buffer.read(cx));
2146
2147 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
2148 }
2149
2150 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
2151 if self.is_local() {
2152 let mut language_servers = HashMap::default();
2153 for ((worktree_id, _), (lsp_adapter, language_server)) in self.language_servers.iter() {
2154 if let Some(worktree) = self
2155 .worktree_for_id(*worktree_id, cx)
2156 .and_then(|worktree| worktree.read(cx).as_local())
2157 {
2158 language_servers
2159 .entry(Arc::as_ptr(language_server))
2160 .or_insert((
2161 lsp_adapter.clone(),
2162 language_server.clone(),
2163 *worktree_id,
2164 worktree.abs_path().clone(),
2165 ));
2166 }
2167 }
2168
2169 let mut requests = Vec::new();
2170 for (_, language_server, _, _) in language_servers.values() {
2171 requests.push(language_server.request::<lsp::request::WorkspaceSymbol>(
2172 lsp::WorkspaceSymbolParams {
2173 query: query.to_string(),
2174 ..Default::default()
2175 },
2176 ));
2177 }
2178
2179 cx.spawn_weak(|this, cx| async move {
2180 let responses = futures::future::try_join_all(requests).await?;
2181
2182 let mut symbols = Vec::new();
2183 if let Some(this) = this.upgrade(&cx) {
2184 this.read_with(&cx, |this, cx| {
2185 for ((adapter, _, source_worktree_id, worktree_abs_path), lsp_symbols) in
2186 language_servers.into_values().zip(responses)
2187 {
2188 symbols.extend(lsp_symbols.into_iter().flatten().filter_map(
2189 |lsp_symbol| {
2190 let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
2191 let mut worktree_id = source_worktree_id;
2192 let path;
2193 if let Some((worktree, rel_path)) =
2194 this.find_local_worktree(&abs_path, cx)
2195 {
2196 worktree_id = worktree.read(cx).id();
2197 path = rel_path;
2198 } else {
2199 path = relativize_path(&worktree_abs_path, &abs_path);
2200 }
2201
2202 let label = this
2203 .languages
2204 .select_language(&path)
2205 .and_then(|language| {
2206 language
2207 .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
2208 })
2209 .unwrap_or_else(|| {
2210 CodeLabel::plain(lsp_symbol.name.clone(), None)
2211 });
2212 let signature = this.symbol_signature(worktree_id, &path);
2213
2214 Some(Symbol {
2215 source_worktree_id,
2216 worktree_id,
2217 language_server_name: adapter.name(),
2218 name: lsp_symbol.name,
2219 kind: lsp_symbol.kind,
2220 label,
2221 path,
2222 range: range_from_lsp(lsp_symbol.location.range),
2223 signature,
2224 })
2225 },
2226 ));
2227 }
2228 })
2229 }
2230
2231 Ok(symbols)
2232 })
2233 } else if let Some(project_id) = self.remote_id() {
2234 let request = self.client.request(proto::GetProjectSymbols {
2235 project_id,
2236 query: query.to_string(),
2237 });
2238 cx.spawn_weak(|this, cx| async move {
2239 let response = request.await?;
2240 let mut symbols = Vec::new();
2241 if let Some(this) = this.upgrade(&cx) {
2242 this.read_with(&cx, |this, _| {
2243 symbols.extend(
2244 response
2245 .symbols
2246 .into_iter()
2247 .filter_map(|symbol| this.deserialize_symbol(symbol).log_err()),
2248 );
2249 })
2250 }
2251 Ok(symbols)
2252 })
2253 } else {
2254 Task::ready(Ok(Default::default()))
2255 }
2256 }
2257
2258 pub fn open_buffer_for_symbol(
2259 &mut self,
2260 symbol: &Symbol,
2261 cx: &mut ModelContext<Self>,
2262 ) -> Task<Result<ModelHandle<Buffer>>> {
2263 if self.is_local() {
2264 let (lsp_adapter, language_server) = if let Some(server) = self.language_servers.get(&(
2265 symbol.source_worktree_id,
2266 symbol.language_server_name.clone(),
2267 )) {
2268 server.clone()
2269 } else {
2270 return Task::ready(Err(anyhow!(
2271 "language server for worktree and language not found"
2272 )));
2273 };
2274
2275 let worktree_abs_path = if let Some(worktree_abs_path) = self
2276 .worktree_for_id(symbol.worktree_id, cx)
2277 .and_then(|worktree| worktree.read(cx).as_local())
2278 .map(|local_worktree| local_worktree.abs_path())
2279 {
2280 worktree_abs_path
2281 } else {
2282 return Task::ready(Err(anyhow!("worktree not found for symbol")));
2283 };
2284 let symbol_abs_path = worktree_abs_path.join(&symbol.path);
2285 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
2286 uri
2287 } else {
2288 return Task::ready(Err(anyhow!("invalid symbol path")));
2289 };
2290
2291 self.open_local_buffer_via_lsp(symbol_uri, lsp_adapter, language_server, cx)
2292 } else if let Some(project_id) = self.remote_id() {
2293 let request = self.client.request(proto::OpenBufferForSymbol {
2294 project_id,
2295 symbol: Some(serialize_symbol(symbol)),
2296 });
2297 cx.spawn(|this, mut cx| async move {
2298 let response = request.await?;
2299 let buffer = response.buffer.ok_or_else(|| anyhow!("invalid buffer"))?;
2300 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
2301 .await
2302 })
2303 } else {
2304 Task::ready(Err(anyhow!("project does not have a remote id")))
2305 }
2306 }
2307
2308 pub fn completions<T: ToPointUtf16>(
2309 &self,
2310 source_buffer_handle: &ModelHandle<Buffer>,
2311 position: T,
2312 cx: &mut ModelContext<Self>,
2313 ) -> Task<Result<Vec<Completion>>> {
2314 let source_buffer_handle = source_buffer_handle.clone();
2315 let source_buffer = source_buffer_handle.read(cx);
2316 let buffer_id = source_buffer.remote_id();
2317 let language = source_buffer.language().cloned();
2318 let worktree;
2319 let buffer_abs_path;
2320 if let Some(file) = File::from_dyn(source_buffer.file()) {
2321 worktree = file.worktree.clone();
2322 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
2323 } else {
2324 return Task::ready(Ok(Default::default()));
2325 };
2326
2327 let position = position.to_point_utf16(source_buffer);
2328 let anchor = source_buffer.anchor_after(position);
2329
2330 if worktree.read(cx).as_local().is_some() {
2331 let buffer_abs_path = buffer_abs_path.unwrap();
2332 let (_, lang_server) =
2333 if let Some(server) = self.language_server_for_buffer(source_buffer, cx) {
2334 server.clone()
2335 } else {
2336 return Task::ready(Ok(Default::default()));
2337 };
2338
2339 cx.spawn(|_, cx| async move {
2340 let clipped_position = source_buffer_handle
2341 .read_with(&cx, |this, _| this.clip_point_utf16(position, Bias::Left));
2342 if clipped_position != position {
2343 log::info!("Completion position out of date");
2344 return Ok(Default::default());
2345 }
2346
2347 let completions = lang_server
2348 .request::<lsp::request::Completion>(lsp::CompletionParams {
2349 text_document_position: lsp::TextDocumentPositionParams::new(
2350 lsp::TextDocumentIdentifier::new(
2351 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
2352 ),
2353 point_to_lsp(position),
2354 ),
2355 context: Default::default(),
2356 work_done_progress_params: Default::default(),
2357 partial_result_params: Default::default(),
2358 })
2359 .await
2360 .context("lsp completion request failed")?;
2361
2362 let completions = if let Some(completions) = completions {
2363 match completions {
2364 lsp::CompletionResponse::Array(completions) => completions,
2365 lsp::CompletionResponse::List(list) => list.items,
2366 }
2367 } else {
2368 Default::default()
2369 };
2370
2371 source_buffer_handle.read_with(&cx, |this, _| {
2372 Ok(completions
2373 .into_iter()
2374 .filter_map(|lsp_completion| {
2375 let (old_range, new_text) = match lsp_completion.text_edit.as_ref() {
2376 Some(lsp::CompletionTextEdit::Edit(edit)) => {
2377 (range_from_lsp(edit.range), edit.new_text.clone())
2378 }
2379 None => (
2380 this.common_prefix_at(position, &lsp_completion.label),
2381 lsp_completion.label.clone(),
2382 ),
2383 Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
2384 log::info!("unsupported insert/replace completion");
2385 return None;
2386 }
2387 };
2388
2389 let clipped_start = this.clip_point_utf16(old_range.start, Bias::Left);
2390 let clipped_end = this.clip_point_utf16(old_range.end, Bias::Left);
2391 if clipped_start == old_range.start && clipped_end == old_range.end {
2392 Some(Completion {
2393 old_range: this.anchor_before(old_range.start)
2394 ..this.anchor_after(old_range.end),
2395 new_text,
2396 label: language
2397 .as_ref()
2398 .and_then(|l| l.label_for_completion(&lsp_completion))
2399 .unwrap_or_else(|| {
2400 CodeLabel::plain(
2401 lsp_completion.label.clone(),
2402 lsp_completion.filter_text.as_deref(),
2403 )
2404 }),
2405 lsp_completion,
2406 })
2407 } else {
2408 log::info!("completion out of expected range");
2409 None
2410 }
2411 })
2412 .collect())
2413 })
2414 })
2415 } else if let Some(project_id) = self.remote_id() {
2416 let rpc = self.client.clone();
2417 let message = proto::GetCompletions {
2418 project_id,
2419 buffer_id,
2420 position: Some(language::proto::serialize_anchor(&anchor)),
2421 version: serialize_version(&source_buffer.version()),
2422 };
2423 cx.spawn_weak(|_, mut cx| async move {
2424 let response = rpc.request(message).await?;
2425
2426 source_buffer_handle
2427 .update(&mut cx, |buffer, _| {
2428 buffer.wait_for_version(deserialize_version(response.version))
2429 })
2430 .await;
2431
2432 response
2433 .completions
2434 .into_iter()
2435 .map(|completion| {
2436 language::proto::deserialize_completion(completion, language.as_ref())
2437 })
2438 .collect()
2439 })
2440 } else {
2441 Task::ready(Ok(Default::default()))
2442 }
2443 }
2444
2445 pub fn apply_additional_edits_for_completion(
2446 &self,
2447 buffer_handle: ModelHandle<Buffer>,
2448 completion: Completion,
2449 push_to_history: bool,
2450 cx: &mut ModelContext<Self>,
2451 ) -> Task<Result<Option<Transaction>>> {
2452 let buffer = buffer_handle.read(cx);
2453 let buffer_id = buffer.remote_id();
2454
2455 if self.is_local() {
2456 let (_, lang_server) = if let Some(server) = self.language_server_for_buffer(buffer, cx)
2457 {
2458 server.clone()
2459 } else {
2460 return Task::ready(Ok(Default::default()));
2461 };
2462
2463 cx.spawn(|this, mut cx| async move {
2464 let resolved_completion = lang_server
2465 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
2466 .await?;
2467 if let Some(edits) = resolved_completion.additional_text_edits {
2468 let edits = this
2469 .update(&mut cx, |this, cx| {
2470 this.edits_from_lsp(&buffer_handle, edits, None, cx)
2471 })
2472 .await?;
2473 buffer_handle.update(&mut cx, |buffer, cx| {
2474 buffer.finalize_last_transaction();
2475 buffer.start_transaction();
2476 for (range, text) in edits {
2477 buffer.edit([range], text, cx);
2478 }
2479 let transaction = if buffer.end_transaction(cx).is_some() {
2480 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2481 if !push_to_history {
2482 buffer.forget_transaction(transaction.id);
2483 }
2484 Some(transaction)
2485 } else {
2486 None
2487 };
2488 Ok(transaction)
2489 })
2490 } else {
2491 Ok(None)
2492 }
2493 })
2494 } else if let Some(project_id) = self.remote_id() {
2495 let client = self.client.clone();
2496 cx.spawn(|_, mut cx| async move {
2497 let response = client
2498 .request(proto::ApplyCompletionAdditionalEdits {
2499 project_id,
2500 buffer_id,
2501 completion: Some(language::proto::serialize_completion(&completion)),
2502 })
2503 .await?;
2504
2505 if let Some(transaction) = response.transaction {
2506 let transaction = language::proto::deserialize_transaction(transaction)?;
2507 buffer_handle
2508 .update(&mut cx, |buffer, _| {
2509 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
2510 })
2511 .await;
2512 if push_to_history {
2513 buffer_handle.update(&mut cx, |buffer, _| {
2514 buffer.push_transaction(transaction.clone(), Instant::now());
2515 });
2516 }
2517 Ok(Some(transaction))
2518 } else {
2519 Ok(None)
2520 }
2521 })
2522 } else {
2523 Task::ready(Err(anyhow!("project does not have a remote id")))
2524 }
2525 }
2526
2527 pub fn code_actions<T: Clone + ToOffset>(
2528 &self,
2529 buffer_handle: &ModelHandle<Buffer>,
2530 range: Range<T>,
2531 cx: &mut ModelContext<Self>,
2532 ) -> Task<Result<Vec<CodeAction>>> {
2533 let buffer_handle = buffer_handle.clone();
2534 let buffer = buffer_handle.read(cx);
2535 let snapshot = buffer.snapshot();
2536 let relevant_diagnostics = snapshot
2537 .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
2538 .map(|entry| entry.to_lsp_diagnostic_stub())
2539 .collect();
2540 let buffer_id = buffer.remote_id();
2541 let worktree;
2542 let buffer_abs_path;
2543 if let Some(file) = File::from_dyn(buffer.file()) {
2544 worktree = file.worktree.clone();
2545 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
2546 } else {
2547 return Task::ready(Ok(Default::default()));
2548 };
2549 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2550
2551 if worktree.read(cx).as_local().is_some() {
2552 let buffer_abs_path = buffer_abs_path.unwrap();
2553 let (_, lang_server) = if let Some(server) = self.language_server_for_buffer(buffer, cx)
2554 {
2555 server.clone()
2556 } else {
2557 return Task::ready(Ok(Default::default()));
2558 };
2559
2560 let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
2561 cx.foreground().spawn(async move {
2562 if !lang_server.capabilities().code_action_provider.is_some() {
2563 return Ok(Default::default());
2564 }
2565
2566 Ok(lang_server
2567 .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
2568 text_document: lsp::TextDocumentIdentifier::new(
2569 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
2570 ),
2571 range: lsp_range,
2572 work_done_progress_params: Default::default(),
2573 partial_result_params: Default::default(),
2574 context: lsp::CodeActionContext {
2575 diagnostics: relevant_diagnostics,
2576 only: Some(vec![
2577 lsp::CodeActionKind::QUICKFIX,
2578 lsp::CodeActionKind::REFACTOR,
2579 lsp::CodeActionKind::REFACTOR_EXTRACT,
2580 lsp::CodeActionKind::SOURCE,
2581 ]),
2582 },
2583 })
2584 .await?
2585 .unwrap_or_default()
2586 .into_iter()
2587 .filter_map(|entry| {
2588 if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
2589 Some(CodeAction {
2590 range: range.clone(),
2591 lsp_action,
2592 })
2593 } else {
2594 None
2595 }
2596 })
2597 .collect())
2598 })
2599 } else if let Some(project_id) = self.remote_id() {
2600 let rpc = self.client.clone();
2601 let version = buffer.version();
2602 cx.spawn_weak(|_, mut cx| async move {
2603 let response = rpc
2604 .request(proto::GetCodeActions {
2605 project_id,
2606 buffer_id,
2607 start: Some(language::proto::serialize_anchor(&range.start)),
2608 end: Some(language::proto::serialize_anchor(&range.end)),
2609 version: serialize_version(&version),
2610 })
2611 .await?;
2612
2613 buffer_handle
2614 .update(&mut cx, |buffer, _| {
2615 buffer.wait_for_version(deserialize_version(response.version))
2616 })
2617 .await;
2618
2619 response
2620 .actions
2621 .into_iter()
2622 .map(language::proto::deserialize_code_action)
2623 .collect()
2624 })
2625 } else {
2626 Task::ready(Ok(Default::default()))
2627 }
2628 }
2629
2630 pub fn apply_code_action(
2631 &self,
2632 buffer_handle: ModelHandle<Buffer>,
2633 mut action: CodeAction,
2634 push_to_history: bool,
2635 cx: &mut ModelContext<Self>,
2636 ) -> Task<Result<ProjectTransaction>> {
2637 if self.is_local() {
2638 let buffer = buffer_handle.read(cx);
2639 let (lsp_adapter, lang_server) =
2640 if let Some(server) = self.language_server_for_buffer(buffer, cx) {
2641 server.clone()
2642 } else {
2643 return Task::ready(Ok(Default::default()));
2644 };
2645 let range = action.range.to_point_utf16(buffer);
2646
2647 cx.spawn(|this, mut cx| async move {
2648 if let Some(lsp_range) = action
2649 .lsp_action
2650 .data
2651 .as_mut()
2652 .and_then(|d| d.get_mut("codeActionParams"))
2653 .and_then(|d| d.get_mut("range"))
2654 {
2655 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
2656 action.lsp_action = lang_server
2657 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
2658 .await?;
2659 } else {
2660 let actions = this
2661 .update(&mut cx, |this, cx| {
2662 this.code_actions(&buffer_handle, action.range, cx)
2663 })
2664 .await?;
2665 action.lsp_action = actions
2666 .into_iter()
2667 .find(|a| a.lsp_action.title == action.lsp_action.title)
2668 .ok_or_else(|| anyhow!("code action is outdated"))?
2669 .lsp_action;
2670 }
2671
2672 if let Some(edit) = action.lsp_action.edit {
2673 Self::deserialize_workspace_edit(
2674 this,
2675 edit,
2676 push_to_history,
2677 lsp_adapter,
2678 lang_server,
2679 &mut cx,
2680 )
2681 .await
2682 } else {
2683 Ok(ProjectTransaction::default())
2684 }
2685 })
2686 } else if let Some(project_id) = self.remote_id() {
2687 let client = self.client.clone();
2688 let request = proto::ApplyCodeAction {
2689 project_id,
2690 buffer_id: buffer_handle.read(cx).remote_id(),
2691 action: Some(language::proto::serialize_code_action(&action)),
2692 };
2693 cx.spawn(|this, mut cx| async move {
2694 let response = client
2695 .request(request)
2696 .await?
2697 .transaction
2698 .ok_or_else(|| anyhow!("missing transaction"))?;
2699 this.update(&mut cx, |this, cx| {
2700 this.deserialize_project_transaction(response, push_to_history, cx)
2701 })
2702 .await
2703 })
2704 } else {
2705 Task::ready(Err(anyhow!("project does not have a remote id")))
2706 }
2707 }
2708
2709 async fn deserialize_workspace_edit(
2710 this: ModelHandle<Self>,
2711 edit: lsp::WorkspaceEdit,
2712 push_to_history: bool,
2713 lsp_adapter: Arc<dyn LspAdapter>,
2714 language_server: Arc<LanguageServer>,
2715 cx: &mut AsyncAppContext,
2716 ) -> Result<ProjectTransaction> {
2717 let fs = this.read_with(cx, |this, _| this.fs.clone());
2718 let mut operations = Vec::new();
2719 if let Some(document_changes) = edit.document_changes {
2720 match document_changes {
2721 lsp::DocumentChanges::Edits(edits) => {
2722 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
2723 }
2724 lsp::DocumentChanges::Operations(ops) => operations = ops,
2725 }
2726 } else if let Some(changes) = edit.changes {
2727 operations.extend(changes.into_iter().map(|(uri, edits)| {
2728 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
2729 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
2730 uri,
2731 version: None,
2732 },
2733 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
2734 })
2735 }));
2736 }
2737
2738 let mut project_transaction = ProjectTransaction::default();
2739 for operation in operations {
2740 match operation {
2741 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
2742 let abs_path = op
2743 .uri
2744 .to_file_path()
2745 .map_err(|_| anyhow!("can't convert URI to path"))?;
2746
2747 if let Some(parent_path) = abs_path.parent() {
2748 fs.create_dir(parent_path).await?;
2749 }
2750 if abs_path.ends_with("/") {
2751 fs.create_dir(&abs_path).await?;
2752 } else {
2753 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
2754 .await?;
2755 }
2756 }
2757 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
2758 let source_abs_path = op
2759 .old_uri
2760 .to_file_path()
2761 .map_err(|_| anyhow!("can't convert URI to path"))?;
2762 let target_abs_path = op
2763 .new_uri
2764 .to_file_path()
2765 .map_err(|_| anyhow!("can't convert URI to path"))?;
2766 fs.rename(
2767 &source_abs_path,
2768 &target_abs_path,
2769 op.options.map(Into::into).unwrap_or_default(),
2770 )
2771 .await?;
2772 }
2773 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
2774 let abs_path = op
2775 .uri
2776 .to_file_path()
2777 .map_err(|_| anyhow!("can't convert URI to path"))?;
2778 let options = op.options.map(Into::into).unwrap_or_default();
2779 if abs_path.ends_with("/") {
2780 fs.remove_dir(&abs_path, options).await?;
2781 } else {
2782 fs.remove_file(&abs_path, options).await?;
2783 }
2784 }
2785 lsp::DocumentChangeOperation::Edit(op) => {
2786 let buffer_to_edit = this
2787 .update(cx, |this, cx| {
2788 this.open_local_buffer_via_lsp(
2789 op.text_document.uri,
2790 lsp_adapter.clone(),
2791 language_server.clone(),
2792 cx,
2793 )
2794 })
2795 .await?;
2796
2797 let edits = this
2798 .update(cx, |this, cx| {
2799 let edits = op.edits.into_iter().map(|edit| match edit {
2800 lsp::OneOf::Left(edit) => edit,
2801 lsp::OneOf::Right(edit) => edit.text_edit,
2802 });
2803 this.edits_from_lsp(
2804 &buffer_to_edit,
2805 edits,
2806 op.text_document.version,
2807 cx,
2808 )
2809 })
2810 .await?;
2811
2812 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
2813 buffer.finalize_last_transaction();
2814 buffer.start_transaction();
2815 for (range, text) in edits {
2816 buffer.edit([range], text, cx);
2817 }
2818 let transaction = if buffer.end_transaction(cx).is_some() {
2819 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2820 if !push_to_history {
2821 buffer.forget_transaction(transaction.id);
2822 }
2823 Some(transaction)
2824 } else {
2825 None
2826 };
2827
2828 transaction
2829 });
2830 if let Some(transaction) = transaction {
2831 project_transaction.0.insert(buffer_to_edit, transaction);
2832 }
2833 }
2834 }
2835 }
2836
2837 Ok(project_transaction)
2838 }
2839
2840 pub fn prepare_rename<T: ToPointUtf16>(
2841 &self,
2842 buffer: ModelHandle<Buffer>,
2843 position: T,
2844 cx: &mut ModelContext<Self>,
2845 ) -> Task<Result<Option<Range<Anchor>>>> {
2846 let position = position.to_point_utf16(buffer.read(cx));
2847 self.request_lsp(buffer, PrepareRename { position }, cx)
2848 }
2849
2850 pub fn perform_rename<T: ToPointUtf16>(
2851 &self,
2852 buffer: ModelHandle<Buffer>,
2853 position: T,
2854 new_name: String,
2855 push_to_history: bool,
2856 cx: &mut ModelContext<Self>,
2857 ) -> Task<Result<ProjectTransaction>> {
2858 let position = position.to_point_utf16(buffer.read(cx));
2859 self.request_lsp(
2860 buffer,
2861 PerformRename {
2862 position,
2863 new_name,
2864 push_to_history,
2865 },
2866 cx,
2867 )
2868 }
2869
2870 pub fn search(
2871 &self,
2872 query: SearchQuery,
2873 cx: &mut ModelContext<Self>,
2874 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
2875 if self.is_local() {
2876 let snapshots = self
2877 .visible_worktrees(cx)
2878 .filter_map(|tree| {
2879 let tree = tree.read(cx).as_local()?;
2880 Some(tree.snapshot())
2881 })
2882 .collect::<Vec<_>>();
2883
2884 let background = cx.background().clone();
2885 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
2886 if path_count == 0 {
2887 return Task::ready(Ok(Default::default()));
2888 }
2889 let workers = background.num_cpus().min(path_count);
2890 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
2891 cx.background()
2892 .spawn({
2893 let fs = self.fs.clone();
2894 let background = cx.background().clone();
2895 let query = query.clone();
2896 async move {
2897 let fs = &fs;
2898 let query = &query;
2899 let matching_paths_tx = &matching_paths_tx;
2900 let paths_per_worker = (path_count + workers - 1) / workers;
2901 let snapshots = &snapshots;
2902 background
2903 .scoped(|scope| {
2904 for worker_ix in 0..workers {
2905 let worker_start_ix = worker_ix * paths_per_worker;
2906 let worker_end_ix = worker_start_ix + paths_per_worker;
2907 scope.spawn(async move {
2908 let mut snapshot_start_ix = 0;
2909 let mut abs_path = PathBuf::new();
2910 for snapshot in snapshots {
2911 let snapshot_end_ix =
2912 snapshot_start_ix + snapshot.visible_file_count();
2913 if worker_end_ix <= snapshot_start_ix {
2914 break;
2915 } else if worker_start_ix > snapshot_end_ix {
2916 snapshot_start_ix = snapshot_end_ix;
2917 continue;
2918 } else {
2919 let start_in_snapshot = worker_start_ix
2920 .saturating_sub(snapshot_start_ix);
2921 let end_in_snapshot =
2922 cmp::min(worker_end_ix, snapshot_end_ix)
2923 - snapshot_start_ix;
2924
2925 for entry in snapshot
2926 .files(false, start_in_snapshot)
2927 .take(end_in_snapshot - start_in_snapshot)
2928 {
2929 if matching_paths_tx.is_closed() {
2930 break;
2931 }
2932
2933 abs_path.clear();
2934 abs_path.push(&snapshot.abs_path());
2935 abs_path.push(&entry.path);
2936 let matches = if let Some(file) =
2937 fs.open_sync(&abs_path).await.log_err()
2938 {
2939 query.detect(file).unwrap_or(false)
2940 } else {
2941 false
2942 };
2943
2944 if matches {
2945 let project_path =
2946 (snapshot.id(), entry.path.clone());
2947 if matching_paths_tx
2948 .send(project_path)
2949 .await
2950 .is_err()
2951 {
2952 break;
2953 }
2954 }
2955 }
2956
2957 snapshot_start_ix = snapshot_end_ix;
2958 }
2959 }
2960 });
2961 }
2962 })
2963 .await;
2964 }
2965 })
2966 .detach();
2967
2968 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
2969 let open_buffers = self
2970 .opened_buffers
2971 .values()
2972 .filter_map(|b| b.upgrade(cx))
2973 .collect::<HashSet<_>>();
2974 cx.spawn(|this, cx| async move {
2975 for buffer in &open_buffers {
2976 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
2977 buffers_tx.send((buffer.clone(), snapshot)).await?;
2978 }
2979
2980 let open_buffers = Rc::new(RefCell::new(open_buffers));
2981 while let Some(project_path) = matching_paths_rx.next().await {
2982 if buffers_tx.is_closed() {
2983 break;
2984 }
2985
2986 let this = this.clone();
2987 let open_buffers = open_buffers.clone();
2988 let buffers_tx = buffers_tx.clone();
2989 cx.spawn(|mut cx| async move {
2990 if let Some(buffer) = this
2991 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
2992 .await
2993 .log_err()
2994 {
2995 if open_buffers.borrow_mut().insert(buffer.clone()) {
2996 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
2997 buffers_tx.send((buffer, snapshot)).await?;
2998 }
2999 }
3000
3001 Ok::<_, anyhow::Error>(())
3002 })
3003 .detach();
3004 }
3005
3006 Ok::<_, anyhow::Error>(())
3007 })
3008 .detach_and_log_err(cx);
3009
3010 let background = cx.background().clone();
3011 cx.background().spawn(async move {
3012 let query = &query;
3013 let mut matched_buffers = Vec::new();
3014 for _ in 0..workers {
3015 matched_buffers.push(HashMap::default());
3016 }
3017 background
3018 .scoped(|scope| {
3019 for worker_matched_buffers in matched_buffers.iter_mut() {
3020 let mut buffers_rx = buffers_rx.clone();
3021 scope.spawn(async move {
3022 while let Some((buffer, snapshot)) = buffers_rx.next().await {
3023 let buffer_matches = query
3024 .search(snapshot.as_rope())
3025 .await
3026 .iter()
3027 .map(|range| {
3028 snapshot.anchor_before(range.start)
3029 ..snapshot.anchor_after(range.end)
3030 })
3031 .collect::<Vec<_>>();
3032 if !buffer_matches.is_empty() {
3033 worker_matched_buffers
3034 .insert(buffer.clone(), buffer_matches);
3035 }
3036 }
3037 });
3038 }
3039 })
3040 .await;
3041 Ok(matched_buffers.into_iter().flatten().collect())
3042 })
3043 } else if let Some(project_id) = self.remote_id() {
3044 let request = self.client.request(query.to_proto(project_id));
3045 cx.spawn(|this, mut cx| async move {
3046 let response = request.await?;
3047 let mut result = HashMap::default();
3048 for location in response.locations {
3049 let buffer = location.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
3050 let target_buffer = this
3051 .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3052 .await?;
3053 let start = location
3054 .start
3055 .and_then(deserialize_anchor)
3056 .ok_or_else(|| anyhow!("missing target start"))?;
3057 let end = location
3058 .end
3059 .and_then(deserialize_anchor)
3060 .ok_or_else(|| anyhow!("missing target end"))?;
3061 result
3062 .entry(target_buffer)
3063 .or_insert(Vec::new())
3064 .push(start..end)
3065 }
3066 Ok(result)
3067 })
3068 } else {
3069 Task::ready(Ok(Default::default()))
3070 }
3071 }
3072
3073 fn request_lsp<R: LspCommand>(
3074 &self,
3075 buffer_handle: ModelHandle<Buffer>,
3076 request: R,
3077 cx: &mut ModelContext<Self>,
3078 ) -> Task<Result<R::Response>>
3079 where
3080 <R::LspRequest as lsp::request::Request>::Result: Send,
3081 {
3082 let buffer = buffer_handle.read(cx);
3083 if self.is_local() {
3084 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
3085 if let Some((file, (_, language_server))) =
3086 file.zip(self.language_server_for_buffer(buffer, cx).cloned())
3087 {
3088 let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
3089 return cx.spawn(|this, cx| async move {
3090 if !request.check_capabilities(&language_server.capabilities()) {
3091 return Ok(Default::default());
3092 }
3093
3094 let response = language_server
3095 .request::<R::LspRequest>(lsp_params)
3096 .await
3097 .context("lsp request failed")?;
3098 request
3099 .response_from_lsp(response, this, buffer_handle, cx)
3100 .await
3101 });
3102 }
3103 } else if let Some(project_id) = self.remote_id() {
3104 let rpc = self.client.clone();
3105 let message = request.to_proto(project_id, buffer);
3106 return cx.spawn(|this, cx| async move {
3107 let response = rpc.request(message).await?;
3108 request
3109 .response_from_proto(response, this, buffer_handle, cx)
3110 .await
3111 });
3112 }
3113 Task::ready(Ok(Default::default()))
3114 }
3115
3116 pub fn find_or_create_local_worktree(
3117 &mut self,
3118 abs_path: impl AsRef<Path>,
3119 visible: bool,
3120 cx: &mut ModelContext<Self>,
3121 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
3122 let abs_path = abs_path.as_ref();
3123 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
3124 Task::ready(Ok((tree.clone(), relative_path.into())))
3125 } else {
3126 let worktree = self.create_local_worktree(abs_path, visible, cx);
3127 cx.foreground()
3128 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
3129 }
3130 }
3131
3132 pub fn find_local_worktree(
3133 &self,
3134 abs_path: &Path,
3135 cx: &AppContext,
3136 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
3137 for tree in self.worktrees(cx) {
3138 if let Some(relative_path) = tree
3139 .read(cx)
3140 .as_local()
3141 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
3142 {
3143 return Some((tree.clone(), relative_path.into()));
3144 }
3145 }
3146 None
3147 }
3148
3149 pub fn is_shared(&self) -> bool {
3150 match &self.client_state {
3151 ProjectClientState::Local { is_shared, .. } => *is_shared,
3152 ProjectClientState::Remote { .. } => false,
3153 }
3154 }
3155
3156 fn create_local_worktree(
3157 &mut self,
3158 abs_path: impl AsRef<Path>,
3159 visible: bool,
3160 cx: &mut ModelContext<Self>,
3161 ) -> Task<Result<ModelHandle<Worktree>>> {
3162 let fs = self.fs.clone();
3163 let client = self.client.clone();
3164 let next_entry_id = self.next_entry_id.clone();
3165 let path: Arc<Path> = abs_path.as_ref().into();
3166 let task = self
3167 .loading_local_worktrees
3168 .entry(path.clone())
3169 .or_insert_with(|| {
3170 cx.spawn(|project, mut cx| {
3171 async move {
3172 let worktree = Worktree::local(
3173 client.clone(),
3174 path.clone(),
3175 visible,
3176 fs,
3177 next_entry_id,
3178 &mut cx,
3179 )
3180 .await;
3181 project.update(&mut cx, |project, _| {
3182 project.loading_local_worktrees.remove(&path);
3183 });
3184 let worktree = worktree?;
3185
3186 let (remote_project_id, is_shared) =
3187 project.update(&mut cx, |project, cx| {
3188 project.add_worktree(&worktree, cx);
3189 (project.remote_id(), project.is_shared())
3190 });
3191
3192 if let Some(project_id) = remote_project_id {
3193 if is_shared {
3194 worktree
3195 .update(&mut cx, |worktree, cx| {
3196 worktree.as_local_mut().unwrap().share(project_id, cx)
3197 })
3198 .await?;
3199 } else {
3200 worktree
3201 .update(&mut cx, |worktree, cx| {
3202 worktree.as_local_mut().unwrap().register(project_id, cx)
3203 })
3204 .await?;
3205 }
3206 }
3207
3208 Ok(worktree)
3209 }
3210 .map_err(|err| Arc::new(err))
3211 })
3212 .shared()
3213 })
3214 .clone();
3215 cx.foreground().spawn(async move {
3216 match task.await {
3217 Ok(worktree) => Ok(worktree),
3218 Err(err) => Err(anyhow!("{}", err)),
3219 }
3220 })
3221 }
3222
3223 pub fn remove_worktree(&mut self, id: WorktreeId, cx: &mut ModelContext<Self>) {
3224 self.worktrees.retain(|worktree| {
3225 worktree
3226 .upgrade(cx)
3227 .map_or(false, |w| w.read(cx).id() != id)
3228 });
3229 cx.notify();
3230 }
3231
3232 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
3233 cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
3234 if worktree.read(cx).is_local() {
3235 cx.subscribe(&worktree, |this, worktree, _, cx| {
3236 this.update_local_worktree_buffers(worktree, cx);
3237 })
3238 .detach();
3239 }
3240
3241 let push_strong_handle = {
3242 let worktree = worktree.read(cx);
3243 self.is_shared() || worktree.is_visible() || worktree.is_remote()
3244 };
3245 if push_strong_handle {
3246 self.worktrees
3247 .push(WorktreeHandle::Strong(worktree.clone()));
3248 } else {
3249 cx.observe_release(&worktree, |this, _, cx| {
3250 this.worktrees
3251 .retain(|worktree| worktree.upgrade(cx).is_some());
3252 cx.notify();
3253 })
3254 .detach();
3255 self.worktrees
3256 .push(WorktreeHandle::Weak(worktree.downgrade()));
3257 }
3258 cx.notify();
3259 }
3260
3261 fn update_local_worktree_buffers(
3262 &mut self,
3263 worktree_handle: ModelHandle<Worktree>,
3264 cx: &mut ModelContext<Self>,
3265 ) {
3266 let snapshot = worktree_handle.read(cx).snapshot();
3267 let mut buffers_to_delete = Vec::new();
3268 for (buffer_id, buffer) in &self.opened_buffers {
3269 if let Some(buffer) = buffer.upgrade(cx) {
3270 buffer.update(cx, |buffer, cx| {
3271 if let Some(old_file) = File::from_dyn(buffer.file()) {
3272 if old_file.worktree != worktree_handle {
3273 return;
3274 }
3275
3276 let new_file = if let Some(entry) = old_file
3277 .entry_id
3278 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
3279 {
3280 File {
3281 is_local: true,
3282 entry_id: Some(entry.id),
3283 mtime: entry.mtime,
3284 path: entry.path.clone(),
3285 worktree: worktree_handle.clone(),
3286 }
3287 } else if let Some(entry) =
3288 snapshot.entry_for_path(old_file.path().as_ref())
3289 {
3290 File {
3291 is_local: true,
3292 entry_id: Some(entry.id),
3293 mtime: entry.mtime,
3294 path: entry.path.clone(),
3295 worktree: worktree_handle.clone(),
3296 }
3297 } else {
3298 File {
3299 is_local: true,
3300 entry_id: None,
3301 path: old_file.path().clone(),
3302 mtime: old_file.mtime(),
3303 worktree: worktree_handle.clone(),
3304 }
3305 };
3306
3307 if let Some(project_id) = self.remote_id() {
3308 self.client
3309 .send(proto::UpdateBufferFile {
3310 project_id,
3311 buffer_id: *buffer_id as u64,
3312 file: Some(new_file.to_proto()),
3313 })
3314 .log_err();
3315 }
3316 buffer.file_updated(Box::new(new_file), cx).detach();
3317 }
3318 });
3319 } else {
3320 buffers_to_delete.push(*buffer_id);
3321 }
3322 }
3323
3324 for buffer_id in buffers_to_delete {
3325 self.opened_buffers.remove(&buffer_id);
3326 }
3327 }
3328
3329 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3330 let new_active_entry = entry.and_then(|project_path| {
3331 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3332 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3333 Some(entry.id)
3334 });
3335 if new_active_entry != self.active_entry {
3336 self.active_entry = new_active_entry;
3337 cx.emit(Event::ActiveEntryChanged(new_active_entry));
3338 }
3339 }
3340
3341 pub fn is_running_disk_based_diagnostics(&self) -> bool {
3342 self.language_servers_with_diagnostics_running > 0
3343 }
3344
3345 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
3346 let mut summary = DiagnosticSummary::default();
3347 for (_, path_summary) in self.diagnostic_summaries(cx) {
3348 summary.error_count += path_summary.error_count;
3349 summary.warning_count += path_summary.warning_count;
3350 summary.info_count += path_summary.info_count;
3351 summary.hint_count += path_summary.hint_count;
3352 }
3353 summary
3354 }
3355
3356 pub fn diagnostic_summaries<'a>(
3357 &'a self,
3358 cx: &'a AppContext,
3359 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
3360 self.worktrees(cx).flat_map(move |worktree| {
3361 let worktree = worktree.read(cx);
3362 let worktree_id = worktree.id();
3363 worktree
3364 .diagnostic_summaries()
3365 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
3366 })
3367 }
3368
3369 pub fn disk_based_diagnostics_started(&mut self, cx: &mut ModelContext<Self>) {
3370 self.language_servers_with_diagnostics_running += 1;
3371 if self.language_servers_with_diagnostics_running == 1 {
3372 cx.emit(Event::DiskBasedDiagnosticsStarted);
3373 }
3374 }
3375
3376 pub fn disk_based_diagnostics_finished(&mut self, cx: &mut ModelContext<Self>) {
3377 cx.emit(Event::DiskBasedDiagnosticsUpdated);
3378 self.language_servers_with_diagnostics_running -= 1;
3379 if self.language_servers_with_diagnostics_running == 0 {
3380 cx.emit(Event::DiskBasedDiagnosticsFinished);
3381 }
3382 }
3383
3384 pub fn active_entry(&self) -> Option<ProjectEntryId> {
3385 self.active_entry
3386 }
3387
3388 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<ProjectEntryId> {
3389 self.worktree_for_id(path.worktree_id, cx)?
3390 .read(cx)
3391 .entry_for_path(&path.path)
3392 .map(|entry| entry.id)
3393 }
3394
3395 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
3396 let worktree = self.worktree_for_entry(entry_id, cx)?;
3397 let worktree = worktree.read(cx);
3398 let worktree_id = worktree.id();
3399 let path = worktree.entry_for_id(entry_id)?.path.clone();
3400 Some(ProjectPath { worktree_id, path })
3401 }
3402
3403 // RPC message handlers
3404
3405 async fn handle_unshare_project(
3406 this: ModelHandle<Self>,
3407 _: TypedEnvelope<proto::UnshareProject>,
3408 _: Arc<Client>,
3409 mut cx: AsyncAppContext,
3410 ) -> Result<()> {
3411 this.update(&mut cx, |this, cx| this.project_unshared(cx));
3412 Ok(())
3413 }
3414
3415 async fn handle_add_collaborator(
3416 this: ModelHandle<Self>,
3417 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3418 _: Arc<Client>,
3419 mut cx: AsyncAppContext,
3420 ) -> Result<()> {
3421 let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
3422 let collaborator = envelope
3423 .payload
3424 .collaborator
3425 .take()
3426 .ok_or_else(|| anyhow!("empty collaborator"))?;
3427
3428 let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
3429 this.update(&mut cx, |this, cx| {
3430 this.collaborators
3431 .insert(collaborator.peer_id, collaborator);
3432 cx.notify();
3433 });
3434
3435 Ok(())
3436 }
3437
3438 async fn handle_remove_collaborator(
3439 this: ModelHandle<Self>,
3440 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3441 _: Arc<Client>,
3442 mut cx: AsyncAppContext,
3443 ) -> Result<()> {
3444 this.update(&mut cx, |this, cx| {
3445 let peer_id = PeerId(envelope.payload.peer_id);
3446 let replica_id = this
3447 .collaborators
3448 .remove(&peer_id)
3449 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3450 .replica_id;
3451 for (_, buffer) in &this.opened_buffers {
3452 if let Some(buffer) = buffer.upgrade(cx) {
3453 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3454 }
3455 }
3456 cx.emit(Event::CollaboratorLeft(peer_id));
3457 cx.notify();
3458 Ok(())
3459 })
3460 }
3461
3462 async fn handle_register_worktree(
3463 this: ModelHandle<Self>,
3464 envelope: TypedEnvelope<proto::RegisterWorktree>,
3465 client: Arc<Client>,
3466 mut cx: AsyncAppContext,
3467 ) -> Result<()> {
3468 this.update(&mut cx, |this, cx| {
3469 let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
3470 let replica_id = this.replica_id();
3471 let worktree = proto::Worktree {
3472 id: envelope.payload.worktree_id,
3473 root_name: envelope.payload.root_name,
3474 entries: Default::default(),
3475 diagnostic_summaries: Default::default(),
3476 visible: envelope.payload.visible,
3477 };
3478 let (worktree, load_task) =
3479 Worktree::remote(remote_id, replica_id, worktree, client, cx);
3480 this.add_worktree(&worktree, cx);
3481 load_task.detach();
3482 Ok(())
3483 })
3484 }
3485
3486 async fn handle_unregister_worktree(
3487 this: ModelHandle<Self>,
3488 envelope: TypedEnvelope<proto::UnregisterWorktree>,
3489 _: Arc<Client>,
3490 mut cx: AsyncAppContext,
3491 ) -> Result<()> {
3492 this.update(&mut cx, |this, cx| {
3493 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3494 this.remove_worktree(worktree_id, cx);
3495 Ok(())
3496 })
3497 }
3498
3499 async fn handle_update_worktree(
3500 this: ModelHandle<Self>,
3501 envelope: TypedEnvelope<proto::UpdateWorktree>,
3502 _: Arc<Client>,
3503 mut cx: AsyncAppContext,
3504 ) -> Result<()> {
3505 this.update(&mut cx, |this, cx| {
3506 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3507 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3508 worktree.update(cx, |worktree, _| {
3509 let worktree = worktree.as_remote_mut().unwrap();
3510 worktree.update_from_remote(envelope)
3511 })?;
3512 }
3513 Ok(())
3514 })
3515 }
3516
3517 async fn handle_update_diagnostic_summary(
3518 this: ModelHandle<Self>,
3519 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
3520 _: Arc<Client>,
3521 mut cx: AsyncAppContext,
3522 ) -> Result<()> {
3523 this.update(&mut cx, |this, cx| {
3524 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3525 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3526 if let Some(summary) = envelope.payload.summary {
3527 let project_path = ProjectPath {
3528 worktree_id,
3529 path: Path::new(&summary.path).into(),
3530 };
3531 worktree.update(cx, |worktree, _| {
3532 worktree
3533 .as_remote_mut()
3534 .unwrap()
3535 .update_diagnostic_summary(project_path.path.clone(), &summary);
3536 });
3537 cx.emit(Event::DiagnosticsUpdated(project_path));
3538 }
3539 }
3540 Ok(())
3541 })
3542 }
3543
3544 async fn handle_start_language_server(
3545 this: ModelHandle<Self>,
3546 envelope: TypedEnvelope<proto::StartLanguageServer>,
3547 _: Arc<Client>,
3548 mut cx: AsyncAppContext,
3549 ) -> Result<()> {
3550 let server = envelope
3551 .payload
3552 .server
3553 .ok_or_else(|| anyhow!("invalid server"))?;
3554 this.update(&mut cx, |this, cx| {
3555 this.language_server_statuses.insert(
3556 server.id as usize,
3557 LanguageServerStatus {
3558 name: server.name,
3559 pending_work: Default::default(),
3560 pending_diagnostic_updates: 0,
3561 },
3562 );
3563 cx.notify();
3564 });
3565 Ok(())
3566 }
3567
3568 async fn handle_update_language_server(
3569 this: ModelHandle<Self>,
3570 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
3571 _: Arc<Client>,
3572 mut cx: AsyncAppContext,
3573 ) -> Result<()> {
3574 let language_server_id = envelope.payload.language_server_id as usize;
3575 match envelope
3576 .payload
3577 .variant
3578 .ok_or_else(|| anyhow!("invalid variant"))?
3579 {
3580 proto::update_language_server::Variant::WorkStart(payload) => {
3581 this.update(&mut cx, |this, cx| {
3582 this.on_lsp_work_start(language_server_id, payload.token, cx);
3583 })
3584 }
3585 proto::update_language_server::Variant::WorkProgress(payload) => {
3586 this.update(&mut cx, |this, cx| {
3587 this.on_lsp_work_progress(
3588 language_server_id,
3589 payload.token,
3590 LanguageServerProgress {
3591 message: payload.message,
3592 percentage: payload.percentage.map(|p| p as usize),
3593 last_update_at: Instant::now(),
3594 },
3595 cx,
3596 );
3597 })
3598 }
3599 proto::update_language_server::Variant::WorkEnd(payload) => {
3600 this.update(&mut cx, |this, cx| {
3601 this.on_lsp_work_end(language_server_id, payload.token, cx);
3602 })
3603 }
3604 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
3605 this.update(&mut cx, |this, cx| {
3606 this.disk_based_diagnostics_started(cx);
3607 })
3608 }
3609 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
3610 this.update(&mut cx, |this, cx| this.disk_based_diagnostics_finished(cx));
3611 }
3612 }
3613
3614 Ok(())
3615 }
3616
3617 async fn handle_update_buffer(
3618 this: ModelHandle<Self>,
3619 envelope: TypedEnvelope<proto::UpdateBuffer>,
3620 _: Arc<Client>,
3621 mut cx: AsyncAppContext,
3622 ) -> Result<()> {
3623 this.update(&mut cx, |this, cx| {
3624 let payload = envelope.payload.clone();
3625 let buffer_id = payload.buffer_id;
3626 let ops = payload
3627 .operations
3628 .into_iter()
3629 .map(|op| language::proto::deserialize_operation(op))
3630 .collect::<Result<Vec<_>, _>>()?;
3631 match this.opened_buffers.entry(buffer_id) {
3632 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
3633 OpenBuffer::Strong(buffer) => {
3634 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
3635 }
3636 OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
3637 OpenBuffer::Weak(_) => {}
3638 },
3639 hash_map::Entry::Vacant(e) => {
3640 e.insert(OpenBuffer::Loading(ops));
3641 }
3642 }
3643 Ok(())
3644 })
3645 }
3646
3647 async fn handle_update_buffer_file(
3648 this: ModelHandle<Self>,
3649 envelope: TypedEnvelope<proto::UpdateBufferFile>,
3650 _: Arc<Client>,
3651 mut cx: AsyncAppContext,
3652 ) -> Result<()> {
3653 this.update(&mut cx, |this, cx| {
3654 let payload = envelope.payload.clone();
3655 let buffer_id = payload.buffer_id;
3656 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
3657 let worktree = this
3658 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
3659 .ok_or_else(|| anyhow!("no such worktree"))?;
3660 let file = File::from_proto(file, worktree.clone(), cx)?;
3661 let buffer = this
3662 .opened_buffers
3663 .get_mut(&buffer_id)
3664 .and_then(|b| b.upgrade(cx))
3665 .ok_or_else(|| anyhow!("no such buffer"))?;
3666 buffer.update(cx, |buffer, cx| {
3667 buffer.file_updated(Box::new(file), cx).detach();
3668 });
3669 Ok(())
3670 })
3671 }
3672
3673 async fn handle_save_buffer(
3674 this: ModelHandle<Self>,
3675 envelope: TypedEnvelope<proto::SaveBuffer>,
3676 _: Arc<Client>,
3677 mut cx: AsyncAppContext,
3678 ) -> Result<proto::BufferSaved> {
3679 let buffer_id = envelope.payload.buffer_id;
3680 let requested_version = deserialize_version(envelope.payload.version);
3681
3682 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
3683 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
3684 let buffer = this
3685 .opened_buffers
3686 .get(&buffer_id)
3687 .map(|buffer| buffer.upgrade(cx).unwrap())
3688 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
3689 Ok::<_, anyhow::Error>((project_id, buffer))
3690 })?;
3691 buffer
3692 .update(&mut cx, |buffer, _| {
3693 buffer.wait_for_version(requested_version)
3694 })
3695 .await;
3696
3697 let (saved_version, mtime) = buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
3698 Ok(proto::BufferSaved {
3699 project_id,
3700 buffer_id,
3701 version: serialize_version(&saved_version),
3702 mtime: Some(mtime.into()),
3703 })
3704 }
3705
3706 async fn handle_format_buffers(
3707 this: ModelHandle<Self>,
3708 envelope: TypedEnvelope<proto::FormatBuffers>,
3709 _: Arc<Client>,
3710 mut cx: AsyncAppContext,
3711 ) -> Result<proto::FormatBuffersResponse> {
3712 let sender_id = envelope.original_sender_id()?;
3713 let format = this.update(&mut cx, |this, cx| {
3714 let mut buffers = HashSet::default();
3715 for buffer_id in &envelope.payload.buffer_ids {
3716 buffers.insert(
3717 this.opened_buffers
3718 .get(buffer_id)
3719 .map(|buffer| buffer.upgrade(cx).unwrap())
3720 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
3721 );
3722 }
3723 Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
3724 })?;
3725
3726 let project_transaction = format.await?;
3727 let project_transaction = this.update(&mut cx, |this, cx| {
3728 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
3729 });
3730 Ok(proto::FormatBuffersResponse {
3731 transaction: Some(project_transaction),
3732 })
3733 }
3734
3735 async fn handle_get_completions(
3736 this: ModelHandle<Self>,
3737 envelope: TypedEnvelope<proto::GetCompletions>,
3738 _: Arc<Client>,
3739 mut cx: AsyncAppContext,
3740 ) -> Result<proto::GetCompletionsResponse> {
3741 let position = envelope
3742 .payload
3743 .position
3744 .and_then(language::proto::deserialize_anchor)
3745 .ok_or_else(|| anyhow!("invalid position"))?;
3746 let version = deserialize_version(envelope.payload.version);
3747 let buffer = this.read_with(&cx, |this, cx| {
3748 this.opened_buffers
3749 .get(&envelope.payload.buffer_id)
3750 .map(|buffer| buffer.upgrade(cx).unwrap())
3751 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
3752 })?;
3753 buffer
3754 .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
3755 .await;
3756 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
3757 let completions = this
3758 .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
3759 .await?;
3760
3761 Ok(proto::GetCompletionsResponse {
3762 completions: completions
3763 .iter()
3764 .map(language::proto::serialize_completion)
3765 .collect(),
3766 version: serialize_version(&version),
3767 })
3768 }
3769
3770 async fn handle_apply_additional_edits_for_completion(
3771 this: ModelHandle<Self>,
3772 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
3773 _: Arc<Client>,
3774 mut cx: AsyncAppContext,
3775 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
3776 let apply_additional_edits = this.update(&mut cx, |this, cx| {
3777 let buffer = this
3778 .opened_buffers
3779 .get(&envelope.payload.buffer_id)
3780 .map(|buffer| buffer.upgrade(cx).unwrap())
3781 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
3782 let language = buffer.read(cx).language();
3783 let completion = language::proto::deserialize_completion(
3784 envelope
3785 .payload
3786 .completion
3787 .ok_or_else(|| anyhow!("invalid completion"))?,
3788 language,
3789 )?;
3790 Ok::<_, anyhow::Error>(
3791 this.apply_additional_edits_for_completion(buffer, completion, false, cx),
3792 )
3793 })?;
3794
3795 Ok(proto::ApplyCompletionAdditionalEditsResponse {
3796 transaction: apply_additional_edits
3797 .await?
3798 .as_ref()
3799 .map(language::proto::serialize_transaction),
3800 })
3801 }
3802
3803 async fn handle_get_code_actions(
3804 this: ModelHandle<Self>,
3805 envelope: TypedEnvelope<proto::GetCodeActions>,
3806 _: Arc<Client>,
3807 mut cx: AsyncAppContext,
3808 ) -> Result<proto::GetCodeActionsResponse> {
3809 let start = envelope
3810 .payload
3811 .start
3812 .and_then(language::proto::deserialize_anchor)
3813 .ok_or_else(|| anyhow!("invalid start"))?;
3814 let end = envelope
3815 .payload
3816 .end
3817 .and_then(language::proto::deserialize_anchor)
3818 .ok_or_else(|| anyhow!("invalid end"))?;
3819 let buffer = this.update(&mut cx, |this, cx| {
3820 this.opened_buffers
3821 .get(&envelope.payload.buffer_id)
3822 .map(|buffer| buffer.upgrade(cx).unwrap())
3823 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
3824 })?;
3825 buffer
3826 .update(&mut cx, |buffer, _| {
3827 buffer.wait_for_version(deserialize_version(envelope.payload.version))
3828 })
3829 .await;
3830
3831 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
3832 let code_actions = this.update(&mut cx, |this, cx| {
3833 Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
3834 })?;
3835
3836 Ok(proto::GetCodeActionsResponse {
3837 actions: code_actions
3838 .await?
3839 .iter()
3840 .map(language::proto::serialize_code_action)
3841 .collect(),
3842 version: serialize_version(&version),
3843 })
3844 }
3845
3846 async fn handle_apply_code_action(
3847 this: ModelHandle<Self>,
3848 envelope: TypedEnvelope<proto::ApplyCodeAction>,
3849 _: Arc<Client>,
3850 mut cx: AsyncAppContext,
3851 ) -> Result<proto::ApplyCodeActionResponse> {
3852 let sender_id = envelope.original_sender_id()?;
3853 let action = language::proto::deserialize_code_action(
3854 envelope
3855 .payload
3856 .action
3857 .ok_or_else(|| anyhow!("invalid action"))?,
3858 )?;
3859 let apply_code_action = this.update(&mut cx, |this, cx| {
3860 let buffer = this
3861 .opened_buffers
3862 .get(&envelope.payload.buffer_id)
3863 .map(|buffer| buffer.upgrade(cx).unwrap())
3864 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
3865 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
3866 })?;
3867
3868 let project_transaction = apply_code_action.await?;
3869 let project_transaction = this.update(&mut cx, |this, cx| {
3870 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
3871 });
3872 Ok(proto::ApplyCodeActionResponse {
3873 transaction: Some(project_transaction),
3874 })
3875 }
3876
3877 async fn handle_lsp_command<T: LspCommand>(
3878 this: ModelHandle<Self>,
3879 envelope: TypedEnvelope<T::ProtoRequest>,
3880 _: Arc<Client>,
3881 mut cx: AsyncAppContext,
3882 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
3883 where
3884 <T::LspRequest as lsp::request::Request>::Result: Send,
3885 {
3886 let sender_id = envelope.original_sender_id()?;
3887 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
3888 let buffer_handle = this.read_with(&cx, |this, _| {
3889 this.opened_buffers
3890 .get(&buffer_id)
3891 .and_then(|buffer| buffer.upgrade(&cx))
3892 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
3893 })?;
3894 let request = T::from_proto(
3895 envelope.payload,
3896 this.clone(),
3897 buffer_handle.clone(),
3898 cx.clone(),
3899 )
3900 .await?;
3901 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
3902 let response = this
3903 .update(&mut cx, |this, cx| {
3904 this.request_lsp(buffer_handle, request, cx)
3905 })
3906 .await?;
3907 this.update(&mut cx, |this, cx| {
3908 Ok(T::response_to_proto(
3909 response,
3910 this,
3911 sender_id,
3912 &buffer_version,
3913 cx,
3914 ))
3915 })
3916 }
3917
3918 async fn handle_get_project_symbols(
3919 this: ModelHandle<Self>,
3920 envelope: TypedEnvelope<proto::GetProjectSymbols>,
3921 _: Arc<Client>,
3922 mut cx: AsyncAppContext,
3923 ) -> Result<proto::GetProjectSymbolsResponse> {
3924 let symbols = this
3925 .update(&mut cx, |this, cx| {
3926 this.symbols(&envelope.payload.query, cx)
3927 })
3928 .await?;
3929
3930 Ok(proto::GetProjectSymbolsResponse {
3931 symbols: symbols.iter().map(serialize_symbol).collect(),
3932 })
3933 }
3934
3935 async fn handle_search_project(
3936 this: ModelHandle<Self>,
3937 envelope: TypedEnvelope<proto::SearchProject>,
3938 _: Arc<Client>,
3939 mut cx: AsyncAppContext,
3940 ) -> Result<proto::SearchProjectResponse> {
3941 let peer_id = envelope.original_sender_id()?;
3942 let query = SearchQuery::from_proto(envelope.payload)?;
3943 let result = this
3944 .update(&mut cx, |this, cx| this.search(query, cx))
3945 .await?;
3946
3947 this.update(&mut cx, |this, cx| {
3948 let mut locations = Vec::new();
3949 for (buffer, ranges) in result {
3950 for range in ranges {
3951 let start = serialize_anchor(&range.start);
3952 let end = serialize_anchor(&range.end);
3953 let buffer = this.serialize_buffer_for_peer(&buffer, peer_id, cx);
3954 locations.push(proto::Location {
3955 buffer: Some(buffer),
3956 start: Some(start),
3957 end: Some(end),
3958 });
3959 }
3960 }
3961 Ok(proto::SearchProjectResponse { locations })
3962 })
3963 }
3964
3965 async fn handle_open_buffer_for_symbol(
3966 this: ModelHandle<Self>,
3967 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
3968 _: Arc<Client>,
3969 mut cx: AsyncAppContext,
3970 ) -> Result<proto::OpenBufferForSymbolResponse> {
3971 let peer_id = envelope.original_sender_id()?;
3972 let symbol = envelope
3973 .payload
3974 .symbol
3975 .ok_or_else(|| anyhow!("invalid symbol"))?;
3976 let symbol = this.read_with(&cx, |this, _| {
3977 let symbol = this.deserialize_symbol(symbol)?;
3978 let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
3979 if signature == symbol.signature {
3980 Ok(symbol)
3981 } else {
3982 Err(anyhow!("invalid symbol signature"))
3983 }
3984 })?;
3985 let buffer = this
3986 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
3987 .await?;
3988
3989 Ok(proto::OpenBufferForSymbolResponse {
3990 buffer: Some(this.update(&mut cx, |this, cx| {
3991 this.serialize_buffer_for_peer(&buffer, peer_id, cx)
3992 })),
3993 })
3994 }
3995
3996 fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
3997 let mut hasher = Sha256::new();
3998 hasher.update(worktree_id.to_proto().to_be_bytes());
3999 hasher.update(path.to_string_lossy().as_bytes());
4000 hasher.update(self.nonce.to_be_bytes());
4001 hasher.finalize().as_slice().try_into().unwrap()
4002 }
4003
4004 async fn handle_open_buffer_by_id(
4005 this: ModelHandle<Self>,
4006 envelope: TypedEnvelope<proto::OpenBufferById>,
4007 _: Arc<Client>,
4008 mut cx: AsyncAppContext,
4009 ) -> Result<proto::OpenBufferResponse> {
4010 let peer_id = envelope.original_sender_id()?;
4011 let buffer = this
4012 .update(&mut cx, |this, cx| {
4013 this.open_buffer_by_id(envelope.payload.id, cx)
4014 })
4015 .await?;
4016 this.update(&mut cx, |this, cx| {
4017 Ok(proto::OpenBufferResponse {
4018 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
4019 })
4020 })
4021 }
4022
4023 async fn handle_open_buffer_by_path(
4024 this: ModelHandle<Self>,
4025 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4026 _: Arc<Client>,
4027 mut cx: AsyncAppContext,
4028 ) -> Result<proto::OpenBufferResponse> {
4029 let peer_id = envelope.original_sender_id()?;
4030 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4031 let open_buffer = this.update(&mut cx, |this, cx| {
4032 this.open_buffer(
4033 ProjectPath {
4034 worktree_id,
4035 path: PathBuf::from(envelope.payload.path).into(),
4036 },
4037 cx,
4038 )
4039 });
4040
4041 let buffer = open_buffer.await?;
4042 this.update(&mut cx, |this, cx| {
4043 Ok(proto::OpenBufferResponse {
4044 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
4045 })
4046 })
4047 }
4048
4049 fn serialize_project_transaction_for_peer(
4050 &mut self,
4051 project_transaction: ProjectTransaction,
4052 peer_id: PeerId,
4053 cx: &AppContext,
4054 ) -> proto::ProjectTransaction {
4055 let mut serialized_transaction = proto::ProjectTransaction {
4056 buffers: Default::default(),
4057 transactions: Default::default(),
4058 };
4059 for (buffer, transaction) in project_transaction.0 {
4060 serialized_transaction
4061 .buffers
4062 .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
4063 serialized_transaction
4064 .transactions
4065 .push(language::proto::serialize_transaction(&transaction));
4066 }
4067 serialized_transaction
4068 }
4069
4070 fn deserialize_project_transaction(
4071 &mut self,
4072 message: proto::ProjectTransaction,
4073 push_to_history: bool,
4074 cx: &mut ModelContext<Self>,
4075 ) -> Task<Result<ProjectTransaction>> {
4076 cx.spawn(|this, mut cx| async move {
4077 let mut project_transaction = ProjectTransaction::default();
4078 for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
4079 let buffer = this
4080 .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
4081 .await?;
4082 let transaction = language::proto::deserialize_transaction(transaction)?;
4083 project_transaction.0.insert(buffer, transaction);
4084 }
4085
4086 for (buffer, transaction) in &project_transaction.0 {
4087 buffer
4088 .update(&mut cx, |buffer, _| {
4089 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4090 })
4091 .await;
4092
4093 if push_to_history {
4094 buffer.update(&mut cx, |buffer, _| {
4095 buffer.push_transaction(transaction.clone(), Instant::now());
4096 });
4097 }
4098 }
4099
4100 Ok(project_transaction)
4101 })
4102 }
4103
4104 fn serialize_buffer_for_peer(
4105 &mut self,
4106 buffer: &ModelHandle<Buffer>,
4107 peer_id: PeerId,
4108 cx: &AppContext,
4109 ) -> proto::Buffer {
4110 let buffer_id = buffer.read(cx).remote_id();
4111 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
4112 if shared_buffers.insert(buffer_id) {
4113 proto::Buffer {
4114 variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
4115 }
4116 } else {
4117 proto::Buffer {
4118 variant: Some(proto::buffer::Variant::Id(buffer_id)),
4119 }
4120 }
4121 }
4122
4123 fn deserialize_buffer(
4124 &mut self,
4125 buffer: proto::Buffer,
4126 cx: &mut ModelContext<Self>,
4127 ) -> Task<Result<ModelHandle<Buffer>>> {
4128 let replica_id = self.replica_id();
4129
4130 let opened_buffer_tx = self.opened_buffer.0.clone();
4131 let mut opened_buffer_rx = self.opened_buffer.1.clone();
4132 cx.spawn(|this, mut cx| async move {
4133 match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
4134 proto::buffer::Variant::Id(id) => {
4135 let buffer = loop {
4136 let buffer = this.read_with(&cx, |this, cx| {
4137 this.opened_buffers
4138 .get(&id)
4139 .and_then(|buffer| buffer.upgrade(cx))
4140 });
4141 if let Some(buffer) = buffer {
4142 break buffer;
4143 }
4144 opened_buffer_rx
4145 .next()
4146 .await
4147 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
4148 };
4149 Ok(buffer)
4150 }
4151 proto::buffer::Variant::State(mut buffer) => {
4152 let mut buffer_worktree = None;
4153 let mut buffer_file = None;
4154 if let Some(file) = buffer.file.take() {
4155 this.read_with(&cx, |this, cx| {
4156 let worktree_id = WorktreeId::from_proto(file.worktree_id);
4157 let worktree =
4158 this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
4159 anyhow!("no worktree found for id {}", file.worktree_id)
4160 })?;
4161 buffer_file =
4162 Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
4163 as Box<dyn language::File>);
4164 buffer_worktree = Some(worktree);
4165 Ok::<_, anyhow::Error>(())
4166 })?;
4167 }
4168
4169 let buffer = cx.add_model(|cx| {
4170 Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
4171 });
4172
4173 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
4174
4175 *opened_buffer_tx.borrow_mut().borrow_mut() = ();
4176 Ok(buffer)
4177 }
4178 }
4179 })
4180 }
4181
4182 fn deserialize_symbol(&self, serialized_symbol: proto::Symbol) -> Result<Symbol> {
4183 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
4184 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
4185 let start = serialized_symbol
4186 .start
4187 .ok_or_else(|| anyhow!("invalid start"))?;
4188 let end = serialized_symbol
4189 .end
4190 .ok_or_else(|| anyhow!("invalid end"))?;
4191 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
4192 let path = PathBuf::from(serialized_symbol.path);
4193 let language = self.languages.select_language(&path);
4194 Ok(Symbol {
4195 source_worktree_id,
4196 worktree_id,
4197 language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
4198 label: language
4199 .and_then(|language| language.label_for_symbol(&serialized_symbol.name, kind))
4200 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None)),
4201 name: serialized_symbol.name,
4202 path,
4203 range: PointUtf16::new(start.row, start.column)..PointUtf16::new(end.row, end.column),
4204 kind,
4205 signature: serialized_symbol
4206 .signature
4207 .try_into()
4208 .map_err(|_| anyhow!("invalid signature"))?,
4209 })
4210 }
4211
4212 async fn handle_buffer_saved(
4213 this: ModelHandle<Self>,
4214 envelope: TypedEnvelope<proto::BufferSaved>,
4215 _: Arc<Client>,
4216 mut cx: AsyncAppContext,
4217 ) -> Result<()> {
4218 let version = deserialize_version(envelope.payload.version);
4219 let mtime = envelope
4220 .payload
4221 .mtime
4222 .ok_or_else(|| anyhow!("missing mtime"))?
4223 .into();
4224
4225 this.update(&mut cx, |this, cx| {
4226 let buffer = this
4227 .opened_buffers
4228 .get(&envelope.payload.buffer_id)
4229 .and_then(|buffer| buffer.upgrade(cx));
4230 if let Some(buffer) = buffer {
4231 buffer.update(cx, |buffer, cx| {
4232 buffer.did_save(version, mtime, None, cx);
4233 });
4234 }
4235 Ok(())
4236 })
4237 }
4238
4239 async fn handle_buffer_reloaded(
4240 this: ModelHandle<Self>,
4241 envelope: TypedEnvelope<proto::BufferReloaded>,
4242 _: Arc<Client>,
4243 mut cx: AsyncAppContext,
4244 ) -> Result<()> {
4245 let payload = envelope.payload.clone();
4246 let version = deserialize_version(payload.version);
4247 let mtime = payload
4248 .mtime
4249 .ok_or_else(|| anyhow!("missing mtime"))?
4250 .into();
4251 this.update(&mut cx, |this, cx| {
4252 let buffer = this
4253 .opened_buffers
4254 .get(&payload.buffer_id)
4255 .and_then(|buffer| buffer.upgrade(cx));
4256 if let Some(buffer) = buffer {
4257 buffer.update(cx, |buffer, cx| {
4258 buffer.did_reload(version, mtime, cx);
4259 });
4260 }
4261 Ok(())
4262 })
4263 }
4264
4265 pub fn match_paths<'a>(
4266 &self,
4267 query: &'a str,
4268 include_ignored: bool,
4269 smart_case: bool,
4270 max_results: usize,
4271 cancel_flag: &'a AtomicBool,
4272 cx: &AppContext,
4273 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
4274 let worktrees = self
4275 .worktrees(cx)
4276 .filter(|worktree| worktree.read(cx).is_visible())
4277 .collect::<Vec<_>>();
4278 let include_root_name = worktrees.len() > 1;
4279 let candidate_sets = worktrees
4280 .into_iter()
4281 .map(|worktree| CandidateSet {
4282 snapshot: worktree.read(cx).snapshot(),
4283 include_ignored,
4284 include_root_name,
4285 })
4286 .collect::<Vec<_>>();
4287
4288 let background = cx.background().clone();
4289 async move {
4290 fuzzy::match_paths(
4291 candidate_sets.as_slice(),
4292 query,
4293 smart_case,
4294 max_results,
4295 cancel_flag,
4296 background,
4297 )
4298 .await
4299 }
4300 }
4301
4302 fn edits_from_lsp(
4303 &mut self,
4304 buffer: &ModelHandle<Buffer>,
4305 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
4306 version: Option<i32>,
4307 cx: &mut ModelContext<Self>,
4308 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
4309 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
4310 cx.background().spawn(async move {
4311 let snapshot = snapshot?;
4312 let mut lsp_edits = lsp_edits
4313 .into_iter()
4314 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
4315 .peekable();
4316
4317 let mut edits = Vec::new();
4318 while let Some((mut range, mut new_text)) = lsp_edits.next() {
4319 // Combine any LSP edits that are adjacent.
4320 //
4321 // Also, combine LSP edits that are separated from each other by only
4322 // a newline. This is important because for some code actions,
4323 // Rust-analyzer rewrites the entire buffer via a series of edits that
4324 // are separated by unchanged newline characters.
4325 //
4326 // In order for the diffing logic below to work properly, any edits that
4327 // cancel each other out must be combined into one.
4328 while let Some((next_range, next_text)) = lsp_edits.peek() {
4329 if next_range.start > range.end {
4330 if next_range.start.row > range.end.row + 1
4331 || next_range.start.column > 0
4332 || snapshot.clip_point_utf16(
4333 PointUtf16::new(range.end.row, u32::MAX),
4334 Bias::Left,
4335 ) > range.end
4336 {
4337 break;
4338 }
4339 new_text.push('\n');
4340 }
4341 range.end = next_range.end;
4342 new_text.push_str(&next_text);
4343 lsp_edits.next();
4344 }
4345
4346 if snapshot.clip_point_utf16(range.start, Bias::Left) != range.start
4347 || snapshot.clip_point_utf16(range.end, Bias::Left) != range.end
4348 {
4349 return Err(anyhow!("invalid edits received from language server"));
4350 }
4351
4352 // For multiline edits, perform a diff of the old and new text so that
4353 // we can identify the changes more precisely, preserving the locations
4354 // of any anchors positioned in the unchanged regions.
4355 if range.end.row > range.start.row {
4356 let mut offset = range.start.to_offset(&snapshot);
4357 let old_text = snapshot.text_for_range(range).collect::<String>();
4358
4359 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
4360 let mut moved_since_edit = true;
4361 for change in diff.iter_all_changes() {
4362 let tag = change.tag();
4363 let value = change.value();
4364 match tag {
4365 ChangeTag::Equal => {
4366 offset += value.len();
4367 moved_since_edit = true;
4368 }
4369 ChangeTag::Delete => {
4370 let start = snapshot.anchor_after(offset);
4371 let end = snapshot.anchor_before(offset + value.len());
4372 if moved_since_edit {
4373 edits.push((start..end, String::new()));
4374 } else {
4375 edits.last_mut().unwrap().0.end = end;
4376 }
4377 offset += value.len();
4378 moved_since_edit = false;
4379 }
4380 ChangeTag::Insert => {
4381 if moved_since_edit {
4382 let anchor = snapshot.anchor_after(offset);
4383 edits.push((anchor.clone()..anchor, value.to_string()));
4384 } else {
4385 edits.last_mut().unwrap().1.push_str(value);
4386 }
4387 moved_since_edit = false;
4388 }
4389 }
4390 }
4391 } else if range.end == range.start {
4392 let anchor = snapshot.anchor_after(range.start);
4393 edits.push((anchor.clone()..anchor, new_text));
4394 } else {
4395 let edit_start = snapshot.anchor_after(range.start);
4396 let edit_end = snapshot.anchor_before(range.end);
4397 edits.push((edit_start..edit_end, new_text));
4398 }
4399 }
4400
4401 Ok(edits)
4402 })
4403 }
4404
4405 fn buffer_snapshot_for_lsp_version(
4406 &mut self,
4407 buffer: &ModelHandle<Buffer>,
4408 version: Option<i32>,
4409 cx: &AppContext,
4410 ) -> Result<TextBufferSnapshot> {
4411 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
4412
4413 if let Some(version) = version {
4414 let buffer_id = buffer.read(cx).remote_id();
4415 let snapshots = self
4416 .buffer_snapshots
4417 .get_mut(&buffer_id)
4418 .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
4419 let mut found_snapshot = None;
4420 snapshots.retain(|(snapshot_version, snapshot)| {
4421 if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
4422 false
4423 } else {
4424 if *snapshot_version == version {
4425 found_snapshot = Some(snapshot.clone());
4426 }
4427 true
4428 }
4429 });
4430
4431 found_snapshot.ok_or_else(|| {
4432 anyhow!(
4433 "snapshot not found for buffer {} at version {}",
4434 buffer_id,
4435 version
4436 )
4437 })
4438 } else {
4439 Ok((buffer.read(cx)).text_snapshot())
4440 }
4441 }
4442
4443 fn language_server_for_buffer(
4444 &self,
4445 buffer: &Buffer,
4446 cx: &AppContext,
4447 ) -> Option<&(Arc<dyn LspAdapter>, Arc<LanguageServer>)> {
4448 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
4449 let worktree_id = file.worktree_id(cx);
4450 self.language_servers
4451 .get(&(worktree_id, language.lsp_adapter()?.name()))
4452 } else {
4453 None
4454 }
4455 }
4456}
4457
4458impl WorktreeHandle {
4459 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
4460 match self {
4461 WorktreeHandle::Strong(handle) => Some(handle.clone()),
4462 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
4463 }
4464 }
4465}
4466
4467impl OpenBuffer {
4468 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
4469 match self {
4470 OpenBuffer::Strong(handle) => Some(handle.clone()),
4471 OpenBuffer::Weak(handle) => handle.upgrade(cx),
4472 OpenBuffer::Loading(_) => None,
4473 }
4474 }
4475}
4476
4477struct CandidateSet {
4478 snapshot: Snapshot,
4479 include_ignored: bool,
4480 include_root_name: bool,
4481}
4482
4483impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
4484 type Candidates = CandidateSetIter<'a>;
4485
4486 fn id(&self) -> usize {
4487 self.snapshot.id().to_usize()
4488 }
4489
4490 fn len(&self) -> usize {
4491 if self.include_ignored {
4492 self.snapshot.file_count()
4493 } else {
4494 self.snapshot.visible_file_count()
4495 }
4496 }
4497
4498 fn prefix(&self) -> Arc<str> {
4499 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4500 self.snapshot.root_name().into()
4501 } else if self.include_root_name {
4502 format!("{}/", self.snapshot.root_name()).into()
4503 } else {
4504 "".into()
4505 }
4506 }
4507
4508 fn candidates(&'a self, start: usize) -> Self::Candidates {
4509 CandidateSetIter {
4510 traversal: self.snapshot.files(self.include_ignored, start),
4511 }
4512 }
4513}
4514
4515struct CandidateSetIter<'a> {
4516 traversal: Traversal<'a>,
4517}
4518
4519impl<'a> Iterator for CandidateSetIter<'a> {
4520 type Item = PathMatchCandidate<'a>;
4521
4522 fn next(&mut self) -> Option<Self::Item> {
4523 self.traversal.next().map(|entry| {
4524 if let EntryKind::File(char_bag) = entry.kind {
4525 PathMatchCandidate {
4526 path: &entry.path,
4527 char_bag,
4528 }
4529 } else {
4530 unreachable!()
4531 }
4532 })
4533 }
4534}
4535
4536impl Entity for Project {
4537 type Event = Event;
4538
4539 fn release(&mut self, _: &mut gpui::MutableAppContext) {
4540 match &self.client_state {
4541 ProjectClientState::Local { remote_id_rx, .. } => {
4542 if let Some(project_id) = *remote_id_rx.borrow() {
4543 self.client
4544 .send(proto::UnregisterProject { project_id })
4545 .log_err();
4546 }
4547 }
4548 ProjectClientState::Remote { remote_id, .. } => {
4549 self.client
4550 .send(proto::LeaveProject {
4551 project_id: *remote_id,
4552 })
4553 .log_err();
4554 }
4555 }
4556 }
4557
4558 fn app_will_quit(
4559 &mut self,
4560 _: &mut MutableAppContext,
4561 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
4562 let shutdown_futures = self
4563 .language_servers
4564 .drain()
4565 .filter_map(|(_, (_, server))| server.shutdown())
4566 .collect::<Vec<_>>();
4567 Some(
4568 async move {
4569 futures::future::join_all(shutdown_futures).await;
4570 }
4571 .boxed(),
4572 )
4573 }
4574}
4575
4576impl Collaborator {
4577 fn from_proto(
4578 message: proto::Collaborator,
4579 user_store: &ModelHandle<UserStore>,
4580 cx: &mut AsyncAppContext,
4581 ) -> impl Future<Output = Result<Self>> {
4582 let user = user_store.update(cx, |user_store, cx| {
4583 user_store.fetch_user(message.user_id, cx)
4584 });
4585
4586 async move {
4587 Ok(Self {
4588 peer_id: PeerId(message.peer_id),
4589 user: user.await?,
4590 replica_id: message.replica_id as ReplicaId,
4591 })
4592 }
4593 }
4594}
4595
4596impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4597 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4598 Self {
4599 worktree_id,
4600 path: path.as_ref().into(),
4601 }
4602 }
4603}
4604
4605impl From<lsp::CreateFileOptions> for fs::CreateOptions {
4606 fn from(options: lsp::CreateFileOptions) -> Self {
4607 Self {
4608 overwrite: options.overwrite.unwrap_or(false),
4609 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
4610 }
4611 }
4612}
4613
4614impl From<lsp::RenameFileOptions> for fs::RenameOptions {
4615 fn from(options: lsp::RenameFileOptions) -> Self {
4616 Self {
4617 overwrite: options.overwrite.unwrap_or(false),
4618 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
4619 }
4620 }
4621}
4622
4623impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
4624 fn from(options: lsp::DeleteFileOptions) -> Self {
4625 Self {
4626 recursive: options.recursive.unwrap_or(false),
4627 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
4628 }
4629 }
4630}
4631
4632fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
4633 proto::Symbol {
4634 source_worktree_id: symbol.source_worktree_id.to_proto(),
4635 worktree_id: symbol.worktree_id.to_proto(),
4636 language_server_name: symbol.language_server_name.0.to_string(),
4637 name: symbol.name.clone(),
4638 kind: unsafe { mem::transmute(symbol.kind) },
4639 path: symbol.path.to_string_lossy().to_string(),
4640 start: Some(proto::Point {
4641 row: symbol.range.start.row,
4642 column: symbol.range.start.column,
4643 }),
4644 end: Some(proto::Point {
4645 row: symbol.range.end.row,
4646 column: symbol.range.end.column,
4647 }),
4648 signature: symbol.signature.to_vec(),
4649 }
4650}
4651
4652fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4653 let mut path_components = path.components();
4654 let mut base_components = base.components();
4655 let mut components: Vec<Component> = Vec::new();
4656 loop {
4657 match (path_components.next(), base_components.next()) {
4658 (None, None) => break,
4659 (Some(a), None) => {
4660 components.push(a);
4661 components.extend(path_components.by_ref());
4662 break;
4663 }
4664 (None, _) => components.push(Component::ParentDir),
4665 (Some(a), Some(b)) if components.is_empty() && a == b => (),
4666 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
4667 (Some(a), Some(_)) => {
4668 components.push(Component::ParentDir);
4669 for _ in base_components {
4670 components.push(Component::ParentDir);
4671 }
4672 components.push(a);
4673 components.extend(path_components.by_ref());
4674 break;
4675 }
4676 }
4677 }
4678 components.iter().map(|c| c.as_os_str()).collect()
4679}
4680
4681impl Item for Buffer {
4682 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
4683 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4684 }
4685}
4686
4687#[cfg(test)]
4688mod tests {
4689 use super::{Event, *};
4690 use fs::RealFs;
4691 use futures::{future, StreamExt};
4692 use gpui::test::subscribe;
4693 use language::{
4694 tree_sitter_rust, Diagnostic, FakeLspAdapter, LanguageConfig, OffsetRangeExt, Point,
4695 ToPoint,
4696 };
4697 use lsp::Url;
4698 use serde_json::json;
4699 use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
4700 use unindent::Unindent as _;
4701 use util::{assert_set_eq, test::temp_tree};
4702 use worktree::WorktreeHandle as _;
4703
4704 #[gpui::test]
4705 async fn test_populate_and_search(cx: &mut gpui::TestAppContext) {
4706 let dir = temp_tree(json!({
4707 "root": {
4708 "apple": "",
4709 "banana": {
4710 "carrot": {
4711 "date": "",
4712 "endive": "",
4713 }
4714 },
4715 "fennel": {
4716 "grape": "",
4717 }
4718 }
4719 }));
4720
4721 let root_link_path = dir.path().join("root_link");
4722 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
4723 unix::fs::symlink(
4724 &dir.path().join("root/fennel"),
4725 &dir.path().join("root/finnochio"),
4726 )
4727 .unwrap();
4728
4729 let project = Project::test(Arc::new(RealFs), cx);
4730
4731 let (tree, _) = project
4732 .update(cx, |project, cx| {
4733 project.find_or_create_local_worktree(&root_link_path, true, cx)
4734 })
4735 .await
4736 .unwrap();
4737
4738 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4739 .await;
4740 cx.read(|cx| {
4741 let tree = tree.read(cx);
4742 assert_eq!(tree.file_count(), 5);
4743 assert_eq!(
4744 tree.inode_for_path("fennel/grape"),
4745 tree.inode_for_path("finnochio/grape")
4746 );
4747 });
4748
4749 let cancel_flag = Default::default();
4750 let results = project
4751 .read_with(cx, |project, cx| {
4752 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
4753 })
4754 .await;
4755 assert_eq!(
4756 results
4757 .into_iter()
4758 .map(|result| result.path)
4759 .collect::<Vec<Arc<Path>>>(),
4760 vec![
4761 PathBuf::from("banana/carrot/date").into(),
4762 PathBuf::from("banana/carrot/endive").into(),
4763 ]
4764 );
4765 }
4766
4767 #[gpui::test]
4768 async fn test_managing_language_servers(cx: &mut gpui::TestAppContext) {
4769 cx.foreground().forbid_parking();
4770
4771 let mut rust_language = Language::new(
4772 LanguageConfig {
4773 name: "Rust".into(),
4774 path_suffixes: vec!["rs".to_string()],
4775 ..Default::default()
4776 },
4777 Some(tree_sitter_rust::language()),
4778 );
4779 let mut json_language = Language::new(
4780 LanguageConfig {
4781 name: "JSON".into(),
4782 path_suffixes: vec!["json".to_string()],
4783 ..Default::default()
4784 },
4785 None,
4786 );
4787 let mut fake_rust_servers = rust_language.set_fake_lsp_adapter(FakeLspAdapter {
4788 name: "the-rust-language-server",
4789 capabilities: lsp::ServerCapabilities {
4790 completion_provider: Some(lsp::CompletionOptions {
4791 trigger_characters: Some(vec![".".to_string(), "::".to_string()]),
4792 ..Default::default()
4793 }),
4794 ..Default::default()
4795 },
4796 ..Default::default()
4797 });
4798 let mut fake_json_servers = json_language.set_fake_lsp_adapter(FakeLspAdapter {
4799 name: "the-json-language-server",
4800 capabilities: lsp::ServerCapabilities {
4801 completion_provider: Some(lsp::CompletionOptions {
4802 trigger_characters: Some(vec![":".to_string()]),
4803 ..Default::default()
4804 }),
4805 ..Default::default()
4806 },
4807 ..Default::default()
4808 });
4809
4810 let fs = FakeFs::new(cx.background());
4811 fs.insert_tree(
4812 "/the-root",
4813 json!({
4814 "test.rs": "const A: i32 = 1;",
4815 "test2.rs": "",
4816 "Cargo.toml": "a = 1",
4817 "package.json": "{\"a\": 1}",
4818 }),
4819 )
4820 .await;
4821
4822 let project = Project::test(fs, cx);
4823 project.update(cx, |project, _| {
4824 project.languages.add(Arc::new(rust_language));
4825 project.languages.add(Arc::new(json_language));
4826 });
4827
4828 let worktree_id = project
4829 .update(cx, |project, cx| {
4830 project.find_or_create_local_worktree("/the-root", true, cx)
4831 })
4832 .await
4833 .unwrap()
4834 .0
4835 .read_with(cx, |tree, _| tree.id());
4836
4837 // Open a buffer without an associated language server.
4838 let toml_buffer = project
4839 .update(cx, |project, cx| {
4840 project.open_buffer((worktree_id, "Cargo.toml"), cx)
4841 })
4842 .await
4843 .unwrap();
4844
4845 // Open a buffer with an associated language server.
4846 let rust_buffer = project
4847 .update(cx, |project, cx| {
4848 project.open_buffer((worktree_id, "test.rs"), cx)
4849 })
4850 .await
4851 .unwrap();
4852
4853 // A server is started up, and it is notified about Rust files.
4854 let mut fake_rust_server = fake_rust_servers.next().await.unwrap();
4855 assert_eq!(
4856 fake_rust_server
4857 .receive_notification::<lsp::notification::DidOpenTextDocument>()
4858 .await
4859 .text_document,
4860 lsp::TextDocumentItem {
4861 uri: lsp::Url::from_file_path("/the-root/test.rs").unwrap(),
4862 version: 0,
4863 text: "const A: i32 = 1;".to_string(),
4864 language_id: Default::default()
4865 }
4866 );
4867
4868 // The buffer is configured based on the language server's capabilities.
4869 rust_buffer.read_with(cx, |buffer, _| {
4870 assert_eq!(
4871 buffer.completion_triggers(),
4872 &[".".to_string(), "::".to_string()]
4873 );
4874 });
4875 toml_buffer.read_with(cx, |buffer, _| {
4876 assert!(buffer.completion_triggers().is_empty());
4877 });
4878
4879 // Edit a buffer. The changes are reported to the language server.
4880 rust_buffer.update(cx, |buffer, cx| buffer.edit([16..16], "2", cx));
4881 assert_eq!(
4882 fake_rust_server
4883 .receive_notification::<lsp::notification::DidChangeTextDocument>()
4884 .await
4885 .text_document,
4886 lsp::VersionedTextDocumentIdentifier::new(
4887 lsp::Url::from_file_path("/the-root/test.rs").unwrap(),
4888 1
4889 )
4890 );
4891
4892 // Open a third buffer with a different associated language server.
4893 let json_buffer = project
4894 .update(cx, |project, cx| {
4895 project.open_buffer((worktree_id, "package.json"), cx)
4896 })
4897 .await
4898 .unwrap();
4899
4900 // A json language server is started up and is only notified about the json buffer.
4901 let mut fake_json_server = fake_json_servers.next().await.unwrap();
4902 assert_eq!(
4903 fake_json_server
4904 .receive_notification::<lsp::notification::DidOpenTextDocument>()
4905 .await
4906 .text_document,
4907 lsp::TextDocumentItem {
4908 uri: lsp::Url::from_file_path("/the-root/package.json").unwrap(),
4909 version: 0,
4910 text: "{\"a\": 1}".to_string(),
4911 language_id: Default::default()
4912 }
4913 );
4914
4915 // This buffer is configured based on the second language server's
4916 // capabilities.
4917 json_buffer.read_with(cx, |buffer, _| {
4918 assert_eq!(buffer.completion_triggers(), &[":".to_string()]);
4919 });
4920
4921 // When opening another buffer whose language server is already running,
4922 // it is also configured based on the existing language server's capabilities.
4923 let rust_buffer2 = project
4924 .update(cx, |project, cx| {
4925 project.open_buffer((worktree_id, "test2.rs"), cx)
4926 })
4927 .await
4928 .unwrap();
4929 rust_buffer2.read_with(cx, |buffer, _| {
4930 assert_eq!(
4931 buffer.completion_triggers(),
4932 &[".".to_string(), "::".to_string()]
4933 );
4934 });
4935
4936 // Changes are reported only to servers matching the buffer's language.
4937 toml_buffer.update(cx, |buffer, cx| buffer.edit([5..5], "23", cx));
4938 rust_buffer2.update(cx, |buffer, cx| buffer.edit([0..0], "let x = 1;", cx));
4939 assert_eq!(
4940 fake_rust_server
4941 .receive_notification::<lsp::notification::DidChangeTextDocument>()
4942 .await
4943 .text_document,
4944 lsp::VersionedTextDocumentIdentifier::new(
4945 lsp::Url::from_file_path("/the-root/test2.rs").unwrap(),
4946 1
4947 )
4948 );
4949
4950 // Save notifications are reported to all servers.
4951 toml_buffer
4952 .update(cx, |buffer, cx| buffer.save(cx))
4953 .await
4954 .unwrap();
4955 assert_eq!(
4956 fake_rust_server
4957 .receive_notification::<lsp::notification::DidSaveTextDocument>()
4958 .await
4959 .text_document,
4960 lsp::TextDocumentIdentifier::new(
4961 lsp::Url::from_file_path("/the-root/Cargo.toml").unwrap()
4962 )
4963 );
4964 assert_eq!(
4965 fake_json_server
4966 .receive_notification::<lsp::notification::DidSaveTextDocument>()
4967 .await
4968 .text_document,
4969 lsp::TextDocumentIdentifier::new(
4970 lsp::Url::from_file_path("/the-root/Cargo.toml").unwrap()
4971 )
4972 );
4973
4974 // Restart language servers
4975 project.update(cx, |project, cx| {
4976 project.restart_language_servers_for_buffers(
4977 vec![rust_buffer.clone(), json_buffer.clone()],
4978 cx,
4979 );
4980 });
4981
4982 let mut rust_shutdown_requests = fake_rust_server
4983 .handle_request::<lsp::request::Shutdown, _, _>(|_, _| future::ready(Ok(())));
4984 let mut json_shutdown_requests = fake_json_server
4985 .handle_request::<lsp::request::Shutdown, _, _>(|_, _| future::ready(Ok(())));
4986 futures::join!(rust_shutdown_requests.next(), json_shutdown_requests.next());
4987
4988 let mut fake_rust_server = fake_rust_servers.next().await.unwrap();
4989 let mut fake_json_server = fake_json_servers.next().await.unwrap();
4990
4991 // Ensure both rust documents are reopened in new rust language server without worrying about order
4992 assert_set_eq!(
4993 [
4994 fake_rust_server
4995 .receive_notification::<lsp::notification::DidOpenTextDocument>()
4996 .await
4997 .text_document,
4998 fake_rust_server
4999 .receive_notification::<lsp::notification::DidOpenTextDocument>()
5000 .await
5001 .text_document,
5002 ],
5003 [
5004 lsp::TextDocumentItem {
5005 uri: lsp::Url::from_file_path("/the-root/test.rs").unwrap(),
5006 version: 1,
5007 text: rust_buffer.read_with(cx, |buffer, _| buffer.text()),
5008 language_id: Default::default()
5009 },
5010 lsp::TextDocumentItem {
5011 uri: lsp::Url::from_file_path("/the-root/test2.rs").unwrap(),
5012 version: 1,
5013 text: rust_buffer2.read_with(cx, |buffer, _| buffer.text()),
5014 language_id: Default::default()
5015 },
5016 ]
5017 );
5018
5019 // Ensure json document is reopened in new json language server
5020 assert_eq!(
5021 fake_json_server
5022 .receive_notification::<lsp::notification::DidOpenTextDocument>()
5023 .await
5024 .text_document,
5025 lsp::TextDocumentItem {
5026 uri: lsp::Url::from_file_path("/the-root/package.json").unwrap(),
5027 version: 0,
5028 text: json_buffer.read_with(cx, |buffer, _| buffer.text()),
5029 language_id: Default::default()
5030 }
5031 );
5032
5033 // Close notifications are reported only to servers matching the buffer's language.
5034 cx.update(|_| drop(json_buffer));
5035 let close_message = lsp::DidCloseTextDocumentParams {
5036 text_document: lsp::TextDocumentIdentifier::new(
5037 lsp::Url::from_file_path("/the-root/package.json").unwrap(),
5038 ),
5039 };
5040 assert_eq!(
5041 fake_json_server
5042 .receive_notification::<lsp::notification::DidCloseTextDocument>()
5043 .await,
5044 close_message,
5045 );
5046 }
5047
5048 #[gpui::test]
5049 async fn test_disk_based_diagnostics_progress(cx: &mut gpui::TestAppContext) {
5050 cx.foreground().forbid_parking();
5051
5052 let progress_token = "the-progress-token";
5053 let mut language = Language::new(
5054 LanguageConfig {
5055 name: "Rust".into(),
5056 path_suffixes: vec!["rs".to_string()],
5057 ..Default::default()
5058 },
5059 Some(tree_sitter_rust::language()),
5060 );
5061 let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
5062 disk_based_diagnostics_progress_token: Some(progress_token),
5063 disk_based_diagnostics_sources: &["disk"],
5064 ..Default::default()
5065 });
5066
5067 let fs = FakeFs::new(cx.background());
5068 fs.insert_tree(
5069 "/dir",
5070 json!({
5071 "a.rs": "fn a() { A }",
5072 "b.rs": "const y: i32 = 1",
5073 }),
5074 )
5075 .await;
5076
5077 let project = Project::test(fs, cx);
5078 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
5079
5080 let (tree, _) = project
5081 .update(cx, |project, cx| {
5082 project.find_or_create_local_worktree("/dir", true, cx)
5083 })
5084 .await
5085 .unwrap();
5086 let worktree_id = tree.read_with(cx, |tree, _| tree.id());
5087
5088 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5089 .await;
5090
5091 // Cause worktree to start the fake language server
5092 let _buffer = project
5093 .update(cx, |project, cx| {
5094 project.open_buffer((worktree_id, Path::new("b.rs")), cx)
5095 })
5096 .await
5097 .unwrap();
5098
5099 let mut events = subscribe(&project, cx);
5100
5101 let mut fake_server = fake_servers.next().await.unwrap();
5102 fake_server.start_progress(progress_token).await;
5103 assert_eq!(
5104 events.next().await.unwrap(),
5105 Event::DiskBasedDiagnosticsStarted
5106 );
5107
5108 fake_server.start_progress(progress_token).await;
5109 fake_server.end_progress(progress_token).await;
5110 fake_server.start_progress(progress_token).await;
5111
5112 fake_server.notify::<lsp::notification::PublishDiagnostics>(
5113 lsp::PublishDiagnosticsParams {
5114 uri: Url::from_file_path("/dir/a.rs").unwrap(),
5115 version: None,
5116 diagnostics: vec![lsp::Diagnostic {
5117 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
5118 severity: Some(lsp::DiagnosticSeverity::ERROR),
5119 message: "undefined variable 'A'".to_string(),
5120 ..Default::default()
5121 }],
5122 },
5123 );
5124 assert_eq!(
5125 events.next().await.unwrap(),
5126 Event::DiagnosticsUpdated((worktree_id, Path::new("a.rs")).into())
5127 );
5128
5129 fake_server.end_progress(progress_token).await;
5130 fake_server.end_progress(progress_token).await;
5131 assert_eq!(
5132 events.next().await.unwrap(),
5133 Event::DiskBasedDiagnosticsUpdated
5134 );
5135 assert_eq!(
5136 events.next().await.unwrap(),
5137 Event::DiskBasedDiagnosticsFinished
5138 );
5139
5140 let buffer = project
5141 .update(cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
5142 .await
5143 .unwrap();
5144
5145 buffer.read_with(cx, |buffer, _| {
5146 let snapshot = buffer.snapshot();
5147 let diagnostics = snapshot
5148 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
5149 .collect::<Vec<_>>();
5150 assert_eq!(
5151 diagnostics,
5152 &[DiagnosticEntry {
5153 range: Point::new(0, 9)..Point::new(0, 10),
5154 diagnostic: Diagnostic {
5155 severity: lsp::DiagnosticSeverity::ERROR,
5156 message: "undefined variable 'A'".to_string(),
5157 group_id: 0,
5158 is_primary: true,
5159 ..Default::default()
5160 }
5161 }]
5162 )
5163 });
5164 }
5165
5166 #[gpui::test]
5167 async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
5168 cx.foreground().forbid_parking();
5169
5170 let mut language = Language::new(
5171 LanguageConfig {
5172 name: "Rust".into(),
5173 path_suffixes: vec!["rs".to_string()],
5174 ..Default::default()
5175 },
5176 Some(tree_sitter_rust::language()),
5177 );
5178 let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
5179 disk_based_diagnostics_sources: &["disk"],
5180 ..Default::default()
5181 });
5182
5183 let text = "
5184 fn a() { A }
5185 fn b() { BB }
5186 fn c() { CCC }
5187 "
5188 .unindent();
5189
5190 let fs = FakeFs::new(cx.background());
5191 fs.insert_tree("/dir", json!({ "a.rs": text })).await;
5192
5193 let project = Project::test(fs, cx);
5194 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
5195
5196 let worktree_id = project
5197 .update(cx, |project, cx| {
5198 project.find_or_create_local_worktree("/dir", true, cx)
5199 })
5200 .await
5201 .unwrap()
5202 .0
5203 .read_with(cx, |tree, _| tree.id());
5204
5205 let buffer = project
5206 .update(cx, |project, cx| {
5207 project.open_buffer((worktree_id, "a.rs"), cx)
5208 })
5209 .await
5210 .unwrap();
5211
5212 let mut fake_server = fake_servers.next().await.unwrap();
5213 let open_notification = fake_server
5214 .receive_notification::<lsp::notification::DidOpenTextDocument>()
5215 .await;
5216
5217 // Edit the buffer, moving the content down
5218 buffer.update(cx, |buffer, cx| buffer.edit([0..0], "\n\n", cx));
5219 let change_notification_1 = fake_server
5220 .receive_notification::<lsp::notification::DidChangeTextDocument>()
5221 .await;
5222 assert!(
5223 change_notification_1.text_document.version > open_notification.text_document.version
5224 );
5225
5226 // Report some diagnostics for the initial version of the buffer
5227 fake_server.notify::<lsp::notification::PublishDiagnostics>(
5228 lsp::PublishDiagnosticsParams {
5229 uri: lsp::Url::from_file_path("/dir/a.rs").unwrap(),
5230 version: Some(open_notification.text_document.version),
5231 diagnostics: vec![
5232 lsp::Diagnostic {
5233 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
5234 severity: Some(DiagnosticSeverity::ERROR),
5235 message: "undefined variable 'A'".to_string(),
5236 source: Some("disk".to_string()),
5237 ..Default::default()
5238 },
5239 lsp::Diagnostic {
5240 range: lsp::Range::new(lsp::Position::new(1, 9), lsp::Position::new(1, 11)),
5241 severity: Some(DiagnosticSeverity::ERROR),
5242 message: "undefined variable 'BB'".to_string(),
5243 source: Some("disk".to_string()),
5244 ..Default::default()
5245 },
5246 lsp::Diagnostic {
5247 range: lsp::Range::new(lsp::Position::new(2, 9), lsp::Position::new(2, 12)),
5248 severity: Some(DiagnosticSeverity::ERROR),
5249 source: Some("disk".to_string()),
5250 message: "undefined variable 'CCC'".to_string(),
5251 ..Default::default()
5252 },
5253 ],
5254 },
5255 );
5256
5257 // The diagnostics have moved down since they were created.
5258 buffer.next_notification(cx).await;
5259 buffer.read_with(cx, |buffer, _| {
5260 assert_eq!(
5261 buffer
5262 .snapshot()
5263 .diagnostics_in_range::<_, Point>(Point::new(3, 0)..Point::new(5, 0), false)
5264 .collect::<Vec<_>>(),
5265 &[
5266 DiagnosticEntry {
5267 range: Point::new(3, 9)..Point::new(3, 11),
5268 diagnostic: Diagnostic {
5269 severity: DiagnosticSeverity::ERROR,
5270 message: "undefined variable 'BB'".to_string(),
5271 is_disk_based: true,
5272 group_id: 1,
5273 is_primary: true,
5274 ..Default::default()
5275 },
5276 },
5277 DiagnosticEntry {
5278 range: Point::new(4, 9)..Point::new(4, 12),
5279 diagnostic: Diagnostic {
5280 severity: DiagnosticSeverity::ERROR,
5281 message: "undefined variable 'CCC'".to_string(),
5282 is_disk_based: true,
5283 group_id: 2,
5284 is_primary: true,
5285 ..Default::default()
5286 }
5287 }
5288 ]
5289 );
5290 assert_eq!(
5291 chunks_with_diagnostics(buffer, 0..buffer.len()),
5292 [
5293 ("\n\nfn a() { ".to_string(), None),
5294 ("A".to_string(), Some(DiagnosticSeverity::ERROR)),
5295 (" }\nfn b() { ".to_string(), None),
5296 ("BB".to_string(), Some(DiagnosticSeverity::ERROR)),
5297 (" }\nfn c() { ".to_string(), None),
5298 ("CCC".to_string(), Some(DiagnosticSeverity::ERROR)),
5299 (" }\n".to_string(), None),
5300 ]
5301 );
5302 assert_eq!(
5303 chunks_with_diagnostics(buffer, Point::new(3, 10)..Point::new(4, 11)),
5304 [
5305 ("B".to_string(), Some(DiagnosticSeverity::ERROR)),
5306 (" }\nfn c() { ".to_string(), None),
5307 ("CC".to_string(), Some(DiagnosticSeverity::ERROR)),
5308 ]
5309 );
5310 });
5311
5312 // Ensure overlapping diagnostics are highlighted correctly.
5313 fake_server.notify::<lsp::notification::PublishDiagnostics>(
5314 lsp::PublishDiagnosticsParams {
5315 uri: lsp::Url::from_file_path("/dir/a.rs").unwrap(),
5316 version: Some(open_notification.text_document.version),
5317 diagnostics: vec![
5318 lsp::Diagnostic {
5319 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
5320 severity: Some(DiagnosticSeverity::ERROR),
5321 message: "undefined variable 'A'".to_string(),
5322 source: Some("disk".to_string()),
5323 ..Default::default()
5324 },
5325 lsp::Diagnostic {
5326 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 12)),
5327 severity: Some(DiagnosticSeverity::WARNING),
5328 message: "unreachable statement".to_string(),
5329 source: Some("disk".to_string()),
5330 ..Default::default()
5331 },
5332 ],
5333 },
5334 );
5335
5336 buffer.next_notification(cx).await;
5337 buffer.read_with(cx, |buffer, _| {
5338 assert_eq!(
5339 buffer
5340 .snapshot()
5341 .diagnostics_in_range::<_, Point>(Point::new(2, 0)..Point::new(3, 0), false)
5342 .collect::<Vec<_>>(),
5343 &[
5344 DiagnosticEntry {
5345 range: Point::new(2, 9)..Point::new(2, 12),
5346 diagnostic: Diagnostic {
5347 severity: DiagnosticSeverity::WARNING,
5348 message: "unreachable statement".to_string(),
5349 is_disk_based: true,
5350 group_id: 1,
5351 is_primary: true,
5352 ..Default::default()
5353 }
5354 },
5355 DiagnosticEntry {
5356 range: Point::new(2, 9)..Point::new(2, 10),
5357 diagnostic: Diagnostic {
5358 severity: DiagnosticSeverity::ERROR,
5359 message: "undefined variable 'A'".to_string(),
5360 is_disk_based: true,
5361 group_id: 0,
5362 is_primary: true,
5363 ..Default::default()
5364 },
5365 }
5366 ]
5367 );
5368 assert_eq!(
5369 chunks_with_diagnostics(buffer, Point::new(2, 0)..Point::new(3, 0)),
5370 [
5371 ("fn a() { ".to_string(), None),
5372 ("A".to_string(), Some(DiagnosticSeverity::ERROR)),
5373 (" }".to_string(), Some(DiagnosticSeverity::WARNING)),
5374 ("\n".to_string(), None),
5375 ]
5376 );
5377 assert_eq!(
5378 chunks_with_diagnostics(buffer, Point::new(2, 10)..Point::new(3, 0)),
5379 [
5380 (" }".to_string(), Some(DiagnosticSeverity::WARNING)),
5381 ("\n".to_string(), None),
5382 ]
5383 );
5384 });
5385
5386 // Keep editing the buffer and ensure disk-based diagnostics get translated according to the
5387 // changes since the last save.
5388 buffer.update(cx, |buffer, cx| {
5389 buffer.edit(Some(Point::new(2, 0)..Point::new(2, 0)), " ", cx);
5390 buffer.edit(Some(Point::new(2, 8)..Point::new(2, 10)), "(x: usize)", cx);
5391 buffer.edit(Some(Point::new(3, 10)..Point::new(3, 10)), "xxx", cx);
5392 });
5393 let change_notification_2 = fake_server
5394 .receive_notification::<lsp::notification::DidChangeTextDocument>()
5395 .await;
5396 assert!(
5397 change_notification_2.text_document.version
5398 > change_notification_1.text_document.version
5399 );
5400
5401 // Handle out-of-order diagnostics
5402 fake_server.notify::<lsp::notification::PublishDiagnostics>(
5403 lsp::PublishDiagnosticsParams {
5404 uri: lsp::Url::from_file_path("/dir/a.rs").unwrap(),
5405 version: Some(change_notification_2.text_document.version),
5406 diagnostics: vec![
5407 lsp::Diagnostic {
5408 range: lsp::Range::new(lsp::Position::new(1, 9), lsp::Position::new(1, 11)),
5409 severity: Some(DiagnosticSeverity::ERROR),
5410 message: "undefined variable 'BB'".to_string(),
5411 source: Some("disk".to_string()),
5412 ..Default::default()
5413 },
5414 lsp::Diagnostic {
5415 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
5416 severity: Some(DiagnosticSeverity::WARNING),
5417 message: "undefined variable 'A'".to_string(),
5418 source: Some("disk".to_string()),
5419 ..Default::default()
5420 },
5421 ],
5422 },
5423 );
5424
5425 buffer.next_notification(cx).await;
5426 buffer.read_with(cx, |buffer, _| {
5427 assert_eq!(
5428 buffer
5429 .snapshot()
5430 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
5431 .collect::<Vec<_>>(),
5432 &[
5433 DiagnosticEntry {
5434 range: Point::new(2, 21)..Point::new(2, 22),
5435 diagnostic: Diagnostic {
5436 severity: DiagnosticSeverity::WARNING,
5437 message: "undefined variable 'A'".to_string(),
5438 is_disk_based: true,
5439 group_id: 1,
5440 is_primary: true,
5441 ..Default::default()
5442 }
5443 },
5444 DiagnosticEntry {
5445 range: Point::new(3, 9)..Point::new(3, 14),
5446 diagnostic: Diagnostic {
5447 severity: DiagnosticSeverity::ERROR,
5448 message: "undefined variable 'BB'".to_string(),
5449 is_disk_based: true,
5450 group_id: 0,
5451 is_primary: true,
5452 ..Default::default()
5453 },
5454 }
5455 ]
5456 );
5457 });
5458 }
5459
5460 #[gpui::test]
5461 async fn test_empty_diagnostic_ranges(cx: &mut gpui::TestAppContext) {
5462 cx.foreground().forbid_parking();
5463
5464 let text = concat!(
5465 "let one = ;\n", //
5466 "let two = \n",
5467 "let three = 3;\n",
5468 );
5469
5470 let fs = FakeFs::new(cx.background());
5471 fs.insert_tree("/dir", json!({ "a.rs": text })).await;
5472
5473 let project = Project::test(fs, cx);
5474 let worktree_id = project
5475 .update(cx, |project, cx| {
5476 project.find_or_create_local_worktree("/dir", true, cx)
5477 })
5478 .await
5479 .unwrap()
5480 .0
5481 .read_with(cx, |tree, _| tree.id());
5482
5483 let buffer = project
5484 .update(cx, |project, cx| {
5485 project.open_buffer((worktree_id, "a.rs"), cx)
5486 })
5487 .await
5488 .unwrap();
5489
5490 project.update(cx, |project, cx| {
5491 project
5492 .update_buffer_diagnostics(
5493 &buffer,
5494 vec![
5495 DiagnosticEntry {
5496 range: PointUtf16::new(0, 10)..PointUtf16::new(0, 10),
5497 diagnostic: Diagnostic {
5498 severity: DiagnosticSeverity::ERROR,
5499 message: "syntax error 1".to_string(),
5500 ..Default::default()
5501 },
5502 },
5503 DiagnosticEntry {
5504 range: PointUtf16::new(1, 10)..PointUtf16::new(1, 10),
5505 diagnostic: Diagnostic {
5506 severity: DiagnosticSeverity::ERROR,
5507 message: "syntax error 2".to_string(),
5508 ..Default::default()
5509 },
5510 },
5511 ],
5512 None,
5513 cx,
5514 )
5515 .unwrap();
5516 });
5517
5518 // An empty range is extended forward to include the following character.
5519 // At the end of a line, an empty range is extended backward to include
5520 // the preceding character.
5521 buffer.read_with(cx, |buffer, _| {
5522 let chunks = chunks_with_diagnostics(&buffer, 0..buffer.len());
5523 assert_eq!(
5524 chunks
5525 .iter()
5526 .map(|(s, d)| (s.as_str(), *d))
5527 .collect::<Vec<_>>(),
5528 &[
5529 ("let one = ", None),
5530 (";", Some(DiagnosticSeverity::ERROR)),
5531 ("\nlet two =", None),
5532 (" ", Some(DiagnosticSeverity::ERROR)),
5533 ("\nlet three = 3;\n", None)
5534 ]
5535 );
5536 });
5537 }
5538
5539 #[gpui::test]
5540 async fn test_edits_from_lsp_with_past_version(cx: &mut gpui::TestAppContext) {
5541 cx.foreground().forbid_parking();
5542
5543 let mut language = Language::new(
5544 LanguageConfig {
5545 name: "Rust".into(),
5546 path_suffixes: vec!["rs".to_string()],
5547 ..Default::default()
5548 },
5549 Some(tree_sitter_rust::language()),
5550 );
5551 let mut fake_servers = language.set_fake_lsp_adapter(Default::default());
5552
5553 let text = "
5554 fn a() {
5555 f1();
5556 }
5557 fn b() {
5558 f2();
5559 }
5560 fn c() {
5561 f3();
5562 }
5563 "
5564 .unindent();
5565
5566 let fs = FakeFs::new(cx.background());
5567 fs.insert_tree(
5568 "/dir",
5569 json!({
5570 "a.rs": text.clone(),
5571 }),
5572 )
5573 .await;
5574
5575 let project = Project::test(fs, cx);
5576 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
5577
5578 let worktree_id = project
5579 .update(cx, |project, cx| {
5580 project.find_or_create_local_worktree("/dir", true, cx)
5581 })
5582 .await
5583 .unwrap()
5584 .0
5585 .read_with(cx, |tree, _| tree.id());
5586
5587 let buffer = project
5588 .update(cx, |project, cx| {
5589 project.open_buffer((worktree_id, "a.rs"), cx)
5590 })
5591 .await
5592 .unwrap();
5593
5594 let mut fake_server = fake_servers.next().await.unwrap();
5595 let lsp_document_version = fake_server
5596 .receive_notification::<lsp::notification::DidOpenTextDocument>()
5597 .await
5598 .text_document
5599 .version;
5600
5601 // Simulate editing the buffer after the language server computes some edits.
5602 buffer.update(cx, |buffer, cx| {
5603 buffer.edit(
5604 [Point::new(0, 0)..Point::new(0, 0)],
5605 "// above first function\n",
5606 cx,
5607 );
5608 buffer.edit(
5609 [Point::new(2, 0)..Point::new(2, 0)],
5610 " // inside first function\n",
5611 cx,
5612 );
5613 buffer.edit(
5614 [Point::new(6, 4)..Point::new(6, 4)],
5615 "// inside second function ",
5616 cx,
5617 );
5618
5619 assert_eq!(
5620 buffer.text(),
5621 "
5622 // above first function
5623 fn a() {
5624 // inside first function
5625 f1();
5626 }
5627 fn b() {
5628 // inside second function f2();
5629 }
5630 fn c() {
5631 f3();
5632 }
5633 "
5634 .unindent()
5635 );
5636 });
5637
5638 let edits = project
5639 .update(cx, |project, cx| {
5640 project.edits_from_lsp(
5641 &buffer,
5642 vec![
5643 // replace body of first function
5644 lsp::TextEdit {
5645 range: lsp::Range::new(
5646 lsp::Position::new(0, 0),
5647 lsp::Position::new(3, 0),
5648 ),
5649 new_text: "
5650 fn a() {
5651 f10();
5652 }
5653 "
5654 .unindent(),
5655 },
5656 // edit inside second function
5657 lsp::TextEdit {
5658 range: lsp::Range::new(
5659 lsp::Position::new(4, 6),
5660 lsp::Position::new(4, 6),
5661 ),
5662 new_text: "00".into(),
5663 },
5664 // edit inside third function via two distinct edits
5665 lsp::TextEdit {
5666 range: lsp::Range::new(
5667 lsp::Position::new(7, 5),
5668 lsp::Position::new(7, 5),
5669 ),
5670 new_text: "4000".into(),
5671 },
5672 lsp::TextEdit {
5673 range: lsp::Range::new(
5674 lsp::Position::new(7, 5),
5675 lsp::Position::new(7, 6),
5676 ),
5677 new_text: "".into(),
5678 },
5679 ],
5680 Some(lsp_document_version),
5681 cx,
5682 )
5683 })
5684 .await
5685 .unwrap();
5686
5687 buffer.update(cx, |buffer, cx| {
5688 for (range, new_text) in edits {
5689 buffer.edit([range], new_text, cx);
5690 }
5691 assert_eq!(
5692 buffer.text(),
5693 "
5694 // above first function
5695 fn a() {
5696 // inside first function
5697 f10();
5698 }
5699 fn b() {
5700 // inside second function f200();
5701 }
5702 fn c() {
5703 f4000();
5704 }
5705 "
5706 .unindent()
5707 );
5708 });
5709 }
5710
5711 #[gpui::test]
5712 async fn test_edits_from_lsp_with_edits_on_adjacent_lines(cx: &mut gpui::TestAppContext) {
5713 cx.foreground().forbid_parking();
5714
5715 let text = "
5716 use a::b;
5717 use a::c;
5718
5719 fn f() {
5720 b();
5721 c();
5722 }
5723 "
5724 .unindent();
5725
5726 let fs = FakeFs::new(cx.background());
5727 fs.insert_tree(
5728 "/dir",
5729 json!({
5730 "a.rs": text.clone(),
5731 }),
5732 )
5733 .await;
5734
5735 let project = Project::test(fs, cx);
5736 let worktree_id = project
5737 .update(cx, |project, cx| {
5738 project.find_or_create_local_worktree("/dir", true, cx)
5739 })
5740 .await
5741 .unwrap()
5742 .0
5743 .read_with(cx, |tree, _| tree.id());
5744
5745 let buffer = project
5746 .update(cx, |project, cx| {
5747 project.open_buffer((worktree_id, "a.rs"), cx)
5748 })
5749 .await
5750 .unwrap();
5751
5752 // Simulate the language server sending us a small edit in the form of a very large diff.
5753 // Rust-analyzer does this when performing a merge-imports code action.
5754 let edits = project
5755 .update(cx, |project, cx| {
5756 project.edits_from_lsp(
5757 &buffer,
5758 [
5759 // Replace the first use statement without editing the semicolon.
5760 lsp::TextEdit {
5761 range: lsp::Range::new(
5762 lsp::Position::new(0, 4),
5763 lsp::Position::new(0, 8),
5764 ),
5765 new_text: "a::{b, c}".into(),
5766 },
5767 // Reinsert the remainder of the file between the semicolon and the final
5768 // newline of the file.
5769 lsp::TextEdit {
5770 range: lsp::Range::new(
5771 lsp::Position::new(0, 9),
5772 lsp::Position::new(0, 9),
5773 ),
5774 new_text: "\n\n".into(),
5775 },
5776 lsp::TextEdit {
5777 range: lsp::Range::new(
5778 lsp::Position::new(0, 9),
5779 lsp::Position::new(0, 9),
5780 ),
5781 new_text: "
5782 fn f() {
5783 b();
5784 c();
5785 }"
5786 .unindent(),
5787 },
5788 // Delete everything after the first newline of the file.
5789 lsp::TextEdit {
5790 range: lsp::Range::new(
5791 lsp::Position::new(1, 0),
5792 lsp::Position::new(7, 0),
5793 ),
5794 new_text: "".into(),
5795 },
5796 ],
5797 None,
5798 cx,
5799 )
5800 })
5801 .await
5802 .unwrap();
5803
5804 buffer.update(cx, |buffer, cx| {
5805 let edits = edits
5806 .into_iter()
5807 .map(|(range, text)| {
5808 (
5809 range.start.to_point(&buffer)..range.end.to_point(&buffer),
5810 text,
5811 )
5812 })
5813 .collect::<Vec<_>>();
5814
5815 assert_eq!(
5816 edits,
5817 [
5818 (Point::new(0, 4)..Point::new(0, 8), "a::{b, c}".into()),
5819 (Point::new(1, 0)..Point::new(2, 0), "".into())
5820 ]
5821 );
5822
5823 for (range, new_text) in edits {
5824 buffer.edit([range], new_text, cx);
5825 }
5826 assert_eq!(
5827 buffer.text(),
5828 "
5829 use a::{b, c};
5830
5831 fn f() {
5832 b();
5833 c();
5834 }
5835 "
5836 .unindent()
5837 );
5838 });
5839 }
5840
5841 fn chunks_with_diagnostics<T: ToOffset + ToPoint>(
5842 buffer: &Buffer,
5843 range: Range<T>,
5844 ) -> Vec<(String, Option<DiagnosticSeverity>)> {
5845 let mut chunks: Vec<(String, Option<DiagnosticSeverity>)> = Vec::new();
5846 for chunk in buffer.snapshot().chunks(range, true) {
5847 if chunks.last().map_or(false, |prev_chunk| {
5848 prev_chunk.1 == chunk.diagnostic_severity
5849 }) {
5850 chunks.last_mut().unwrap().0.push_str(chunk.text);
5851 } else {
5852 chunks.push((chunk.text.to_string(), chunk.diagnostic_severity));
5853 }
5854 }
5855 chunks
5856 }
5857
5858 #[gpui::test]
5859 async fn test_search_worktree_without_files(cx: &mut gpui::TestAppContext) {
5860 let dir = temp_tree(json!({
5861 "root": {
5862 "dir1": {},
5863 "dir2": {
5864 "dir3": {}
5865 }
5866 }
5867 }));
5868
5869 let project = Project::test(Arc::new(RealFs), cx);
5870 let (tree, _) = project
5871 .update(cx, |project, cx| {
5872 project.find_or_create_local_worktree(&dir.path(), true, cx)
5873 })
5874 .await
5875 .unwrap();
5876
5877 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5878 .await;
5879
5880 let cancel_flag = Default::default();
5881 let results = project
5882 .read_with(cx, |project, cx| {
5883 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
5884 })
5885 .await;
5886
5887 assert!(results.is_empty());
5888 }
5889
5890 #[gpui::test]
5891 async fn test_definition(cx: &mut gpui::TestAppContext) {
5892 let mut language = Language::new(
5893 LanguageConfig {
5894 name: "Rust".into(),
5895 path_suffixes: vec!["rs".to_string()],
5896 ..Default::default()
5897 },
5898 Some(tree_sitter_rust::language()),
5899 );
5900 let mut fake_servers = language.set_fake_lsp_adapter(Default::default());
5901
5902 let fs = FakeFs::new(cx.background());
5903 fs.insert_tree(
5904 "/dir",
5905 json!({
5906 "a.rs": "const fn a() { A }",
5907 "b.rs": "const y: i32 = crate::a()",
5908 }),
5909 )
5910 .await;
5911
5912 let project = Project::test(fs, cx);
5913 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
5914
5915 let (tree, _) = project
5916 .update(cx, |project, cx| {
5917 project.find_or_create_local_worktree("/dir/b.rs", true, cx)
5918 })
5919 .await
5920 .unwrap();
5921 let worktree_id = tree.read_with(cx, |tree, _| tree.id());
5922 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5923 .await;
5924
5925 let buffer = project
5926 .update(cx, |project, cx| project.open_buffer((worktree_id, ""), cx))
5927 .await
5928 .unwrap();
5929
5930 let fake_server = fake_servers.next().await.unwrap();
5931 fake_server.handle_request::<lsp::request::GotoDefinition, _, _>(|params, _| async move {
5932 let params = params.text_document_position_params;
5933 assert_eq!(
5934 params.text_document.uri.to_file_path().unwrap(),
5935 Path::new("/dir/b.rs"),
5936 );
5937 assert_eq!(params.position, lsp::Position::new(0, 22));
5938
5939 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
5940 lsp::Location::new(
5941 lsp::Url::from_file_path("/dir/a.rs").unwrap(),
5942 lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
5943 ),
5944 )))
5945 });
5946
5947 let mut definitions = project
5948 .update(cx, |project, cx| project.definition(&buffer, 22, cx))
5949 .await
5950 .unwrap();
5951
5952 assert_eq!(definitions.len(), 1);
5953 let definition = definitions.pop().unwrap();
5954 cx.update(|cx| {
5955 let target_buffer = definition.buffer.read(cx);
5956 assert_eq!(
5957 target_buffer
5958 .file()
5959 .unwrap()
5960 .as_local()
5961 .unwrap()
5962 .abs_path(cx),
5963 Path::new("/dir/a.rs"),
5964 );
5965 assert_eq!(definition.range.to_offset(target_buffer), 9..10);
5966 assert_eq!(
5967 list_worktrees(&project, cx),
5968 [("/dir/b.rs".as_ref(), true), ("/dir/a.rs".as_ref(), false)]
5969 );
5970
5971 drop(definition);
5972 });
5973 cx.read(|cx| {
5974 assert_eq!(list_worktrees(&project, cx), [("/dir/b.rs".as_ref(), true)]);
5975 });
5976
5977 fn list_worktrees<'a>(
5978 project: &'a ModelHandle<Project>,
5979 cx: &'a AppContext,
5980 ) -> Vec<(&'a Path, bool)> {
5981 project
5982 .read(cx)
5983 .worktrees(cx)
5984 .map(|worktree| {
5985 let worktree = worktree.read(cx);
5986 (
5987 worktree.as_local().unwrap().abs_path().as_ref(),
5988 worktree.is_visible(),
5989 )
5990 })
5991 .collect::<Vec<_>>()
5992 }
5993 }
5994
5995 #[gpui::test]
5996 async fn test_save_file(cx: &mut gpui::TestAppContext) {
5997 let fs = FakeFs::new(cx.background());
5998 fs.insert_tree(
5999 "/dir",
6000 json!({
6001 "file1": "the old contents",
6002 }),
6003 )
6004 .await;
6005
6006 let project = Project::test(fs.clone(), cx);
6007 let worktree_id = project
6008 .update(cx, |p, cx| {
6009 p.find_or_create_local_worktree("/dir", true, cx)
6010 })
6011 .await
6012 .unwrap()
6013 .0
6014 .read_with(cx, |tree, _| tree.id());
6015
6016 let buffer = project
6017 .update(cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
6018 .await
6019 .unwrap();
6020 buffer
6021 .update(cx, |buffer, cx| {
6022 assert_eq!(buffer.text(), "the old contents");
6023 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
6024 buffer.save(cx)
6025 })
6026 .await
6027 .unwrap();
6028
6029 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
6030 assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
6031 }
6032
6033 #[gpui::test]
6034 async fn test_save_in_single_file_worktree(cx: &mut gpui::TestAppContext) {
6035 let fs = FakeFs::new(cx.background());
6036 fs.insert_tree(
6037 "/dir",
6038 json!({
6039 "file1": "the old contents",
6040 }),
6041 )
6042 .await;
6043
6044 let project = Project::test(fs.clone(), cx);
6045 let worktree_id = project
6046 .update(cx, |p, cx| {
6047 p.find_or_create_local_worktree("/dir/file1", true, cx)
6048 })
6049 .await
6050 .unwrap()
6051 .0
6052 .read_with(cx, |tree, _| tree.id());
6053
6054 let buffer = project
6055 .update(cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
6056 .await
6057 .unwrap();
6058 buffer
6059 .update(cx, |buffer, cx| {
6060 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
6061 buffer.save(cx)
6062 })
6063 .await
6064 .unwrap();
6065
6066 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
6067 assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
6068 }
6069
6070 #[gpui::test]
6071 async fn test_save_as(cx: &mut gpui::TestAppContext) {
6072 let fs = FakeFs::new(cx.background());
6073 fs.insert_tree("/dir", json!({})).await;
6074
6075 let project = Project::test(fs.clone(), cx);
6076 let (worktree, _) = project
6077 .update(cx, |project, cx| {
6078 project.find_or_create_local_worktree("/dir", true, cx)
6079 })
6080 .await
6081 .unwrap();
6082 let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
6083
6084 let buffer = project.update(cx, |project, cx| project.create_buffer(cx).unwrap());
6085 buffer.update(cx, |buffer, cx| {
6086 buffer.edit([0..0], "abc", cx);
6087 assert!(buffer.is_dirty());
6088 assert!(!buffer.has_conflict());
6089 });
6090 project
6091 .update(cx, |project, cx| {
6092 project.save_buffer_as(buffer.clone(), "/dir/file1".into(), cx)
6093 })
6094 .await
6095 .unwrap();
6096 assert_eq!(fs.load(Path::new("/dir/file1")).await.unwrap(), "abc");
6097 buffer.read_with(cx, |buffer, cx| {
6098 assert_eq!(buffer.file().unwrap().full_path(cx), Path::new("dir/file1"));
6099 assert!(!buffer.is_dirty());
6100 assert!(!buffer.has_conflict());
6101 });
6102
6103 let opened_buffer = project
6104 .update(cx, |project, cx| {
6105 project.open_buffer((worktree_id, "file1"), cx)
6106 })
6107 .await
6108 .unwrap();
6109 assert_eq!(opened_buffer, buffer);
6110 }
6111
6112 #[gpui::test(retries = 5)]
6113 async fn test_rescan_and_remote_updates(cx: &mut gpui::TestAppContext) {
6114 let dir = temp_tree(json!({
6115 "a": {
6116 "file1": "",
6117 "file2": "",
6118 "file3": "",
6119 },
6120 "b": {
6121 "c": {
6122 "file4": "",
6123 "file5": "",
6124 }
6125 }
6126 }));
6127
6128 let project = Project::test(Arc::new(RealFs), cx);
6129 let rpc = project.read_with(cx, |p, _| p.client.clone());
6130
6131 let (tree, _) = project
6132 .update(cx, |p, cx| {
6133 p.find_or_create_local_worktree(dir.path(), true, cx)
6134 })
6135 .await
6136 .unwrap();
6137 let worktree_id = tree.read_with(cx, |tree, _| tree.id());
6138
6139 let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
6140 let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
6141 async move { buffer.await.unwrap() }
6142 };
6143 let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
6144 tree.read_with(cx, |tree, _| {
6145 tree.entry_for_path(path)
6146 .expect(&format!("no entry for path {}", path))
6147 .id
6148 })
6149 };
6150
6151 let buffer2 = buffer_for_path("a/file2", cx).await;
6152 let buffer3 = buffer_for_path("a/file3", cx).await;
6153 let buffer4 = buffer_for_path("b/c/file4", cx).await;
6154 let buffer5 = buffer_for_path("b/c/file5", cx).await;
6155
6156 let file2_id = id_for_path("a/file2", &cx);
6157 let file3_id = id_for_path("a/file3", &cx);
6158 let file4_id = id_for_path("b/c/file4", &cx);
6159
6160 // Wait for the initial scan.
6161 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
6162 .await;
6163
6164 // Create a remote copy of this worktree.
6165 let initial_snapshot = tree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
6166 let (remote, load_task) = cx.update(|cx| {
6167 Worktree::remote(
6168 1,
6169 1,
6170 initial_snapshot.to_proto(&Default::default(), true),
6171 rpc.clone(),
6172 cx,
6173 )
6174 });
6175 load_task.await;
6176
6177 cx.read(|cx| {
6178 assert!(!buffer2.read(cx).is_dirty());
6179 assert!(!buffer3.read(cx).is_dirty());
6180 assert!(!buffer4.read(cx).is_dirty());
6181 assert!(!buffer5.read(cx).is_dirty());
6182 });
6183
6184 // Rename and delete files and directories.
6185 tree.flush_fs_events(&cx).await;
6186 std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
6187 std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
6188 std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
6189 std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
6190 tree.flush_fs_events(&cx).await;
6191
6192 let expected_paths = vec![
6193 "a",
6194 "a/file1",
6195 "a/file2.new",
6196 "b",
6197 "d",
6198 "d/file3",
6199 "d/file4",
6200 ];
6201
6202 cx.read(|app| {
6203 assert_eq!(
6204 tree.read(app)
6205 .paths()
6206 .map(|p| p.to_str().unwrap())
6207 .collect::<Vec<_>>(),
6208 expected_paths
6209 );
6210
6211 assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
6212 assert_eq!(id_for_path("d/file3", &cx), file3_id);
6213 assert_eq!(id_for_path("d/file4", &cx), file4_id);
6214
6215 assert_eq!(
6216 buffer2.read(app).file().unwrap().path().as_ref(),
6217 Path::new("a/file2.new")
6218 );
6219 assert_eq!(
6220 buffer3.read(app).file().unwrap().path().as_ref(),
6221 Path::new("d/file3")
6222 );
6223 assert_eq!(
6224 buffer4.read(app).file().unwrap().path().as_ref(),
6225 Path::new("d/file4")
6226 );
6227 assert_eq!(
6228 buffer5.read(app).file().unwrap().path().as_ref(),
6229 Path::new("b/c/file5")
6230 );
6231
6232 assert!(!buffer2.read(app).file().unwrap().is_deleted());
6233 assert!(!buffer3.read(app).file().unwrap().is_deleted());
6234 assert!(!buffer4.read(app).file().unwrap().is_deleted());
6235 assert!(buffer5.read(app).file().unwrap().is_deleted());
6236 });
6237
6238 // Update the remote worktree. Check that it becomes consistent with the
6239 // local worktree.
6240 remote.update(cx, |remote, cx| {
6241 let update_message = tree.read(cx).as_local().unwrap().snapshot().build_update(
6242 &initial_snapshot,
6243 1,
6244 1,
6245 true,
6246 );
6247 remote
6248 .as_remote_mut()
6249 .unwrap()
6250 .snapshot
6251 .apply_remote_update(update_message)
6252 .unwrap();
6253
6254 assert_eq!(
6255 remote
6256 .paths()
6257 .map(|p| p.to_str().unwrap())
6258 .collect::<Vec<_>>(),
6259 expected_paths
6260 );
6261 });
6262 }
6263
6264 #[gpui::test]
6265 async fn test_buffer_deduping(cx: &mut gpui::TestAppContext) {
6266 let fs = FakeFs::new(cx.background());
6267 fs.insert_tree(
6268 "/the-dir",
6269 json!({
6270 "a.txt": "a-contents",
6271 "b.txt": "b-contents",
6272 }),
6273 )
6274 .await;
6275
6276 let project = Project::test(fs.clone(), cx);
6277 let worktree_id = project
6278 .update(cx, |p, cx| {
6279 p.find_or_create_local_worktree("/the-dir", true, cx)
6280 })
6281 .await
6282 .unwrap()
6283 .0
6284 .read_with(cx, |tree, _| tree.id());
6285
6286 // Spawn multiple tasks to open paths, repeating some paths.
6287 let (buffer_a_1, buffer_b, buffer_a_2) = project.update(cx, |p, cx| {
6288 (
6289 p.open_buffer((worktree_id, "a.txt"), cx),
6290 p.open_buffer((worktree_id, "b.txt"), cx),
6291 p.open_buffer((worktree_id, "a.txt"), cx),
6292 )
6293 });
6294
6295 let buffer_a_1 = buffer_a_1.await.unwrap();
6296 let buffer_a_2 = buffer_a_2.await.unwrap();
6297 let buffer_b = buffer_b.await.unwrap();
6298 assert_eq!(buffer_a_1.read_with(cx, |b, _| b.text()), "a-contents");
6299 assert_eq!(buffer_b.read_with(cx, |b, _| b.text()), "b-contents");
6300
6301 // There is only one buffer per path.
6302 let buffer_a_id = buffer_a_1.id();
6303 assert_eq!(buffer_a_2.id(), buffer_a_id);
6304
6305 // Open the same path again while it is still open.
6306 drop(buffer_a_1);
6307 let buffer_a_3 = project
6308 .update(cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
6309 .await
6310 .unwrap();
6311
6312 // There's still only one buffer per path.
6313 assert_eq!(buffer_a_3.id(), buffer_a_id);
6314 }
6315
6316 #[gpui::test]
6317 async fn test_buffer_is_dirty(cx: &mut gpui::TestAppContext) {
6318 use std::fs;
6319
6320 let dir = temp_tree(json!({
6321 "file1": "abc",
6322 "file2": "def",
6323 "file3": "ghi",
6324 }));
6325
6326 let project = Project::test(Arc::new(RealFs), cx);
6327 let (worktree, _) = project
6328 .update(cx, |p, cx| {
6329 p.find_or_create_local_worktree(dir.path(), true, cx)
6330 })
6331 .await
6332 .unwrap();
6333 let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
6334
6335 worktree.flush_fs_events(&cx).await;
6336 worktree
6337 .read_with(cx, |t, _| t.as_local().unwrap().scan_complete())
6338 .await;
6339
6340 let buffer1 = project
6341 .update(cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
6342 .await
6343 .unwrap();
6344 let events = Rc::new(RefCell::new(Vec::new()));
6345
6346 // initially, the buffer isn't dirty.
6347 buffer1.update(cx, |buffer, cx| {
6348 cx.subscribe(&buffer1, {
6349 let events = events.clone();
6350 move |_, _, event, _| match event {
6351 BufferEvent::Operation(_) => {}
6352 _ => events.borrow_mut().push(event.clone()),
6353 }
6354 })
6355 .detach();
6356
6357 assert!(!buffer.is_dirty());
6358 assert!(events.borrow().is_empty());
6359
6360 buffer.edit(vec![1..2], "", cx);
6361 });
6362
6363 // after the first edit, the buffer is dirty, and emits a dirtied event.
6364 buffer1.update(cx, |buffer, cx| {
6365 assert!(buffer.text() == "ac");
6366 assert!(buffer.is_dirty());
6367 assert_eq!(
6368 *events.borrow(),
6369 &[language::Event::Edited, language::Event::Dirtied]
6370 );
6371 events.borrow_mut().clear();
6372 buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
6373 });
6374
6375 // after saving, the buffer is not dirty, and emits a saved event.
6376 buffer1.update(cx, |buffer, cx| {
6377 assert!(!buffer.is_dirty());
6378 assert_eq!(*events.borrow(), &[language::Event::Saved]);
6379 events.borrow_mut().clear();
6380
6381 buffer.edit(vec![1..1], "B", cx);
6382 buffer.edit(vec![2..2], "D", cx);
6383 });
6384
6385 // after editing again, the buffer is dirty, and emits another dirty event.
6386 buffer1.update(cx, |buffer, cx| {
6387 assert!(buffer.text() == "aBDc");
6388 assert!(buffer.is_dirty());
6389 assert_eq!(
6390 *events.borrow(),
6391 &[
6392 language::Event::Edited,
6393 language::Event::Dirtied,
6394 language::Event::Edited,
6395 ],
6396 );
6397 events.borrow_mut().clear();
6398
6399 // TODO - currently, after restoring the buffer to its
6400 // previously-saved state, the is still considered dirty.
6401 buffer.edit([1..3], "", cx);
6402 assert!(buffer.text() == "ac");
6403 assert!(buffer.is_dirty());
6404 });
6405
6406 assert_eq!(*events.borrow(), &[language::Event::Edited]);
6407
6408 // When a file is deleted, the buffer is considered dirty.
6409 let events = Rc::new(RefCell::new(Vec::new()));
6410 let buffer2 = project
6411 .update(cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
6412 .await
6413 .unwrap();
6414 buffer2.update(cx, |_, cx| {
6415 cx.subscribe(&buffer2, {
6416 let events = events.clone();
6417 move |_, _, event, _| events.borrow_mut().push(event.clone())
6418 })
6419 .detach();
6420 });
6421
6422 fs::remove_file(dir.path().join("file2")).unwrap();
6423 buffer2.condition(&cx, |b, _| b.is_dirty()).await;
6424 assert_eq!(
6425 *events.borrow(),
6426 &[language::Event::Dirtied, language::Event::FileHandleChanged]
6427 );
6428
6429 // When a file is already dirty when deleted, we don't emit a Dirtied event.
6430 let events = Rc::new(RefCell::new(Vec::new()));
6431 let buffer3 = project
6432 .update(cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
6433 .await
6434 .unwrap();
6435 buffer3.update(cx, |_, cx| {
6436 cx.subscribe(&buffer3, {
6437 let events = events.clone();
6438 move |_, _, event, _| events.borrow_mut().push(event.clone())
6439 })
6440 .detach();
6441 });
6442
6443 worktree.flush_fs_events(&cx).await;
6444 buffer3.update(cx, |buffer, cx| {
6445 buffer.edit(Some(0..0), "x", cx);
6446 });
6447 events.borrow_mut().clear();
6448 fs::remove_file(dir.path().join("file3")).unwrap();
6449 buffer3
6450 .condition(&cx, |_, _| !events.borrow().is_empty())
6451 .await;
6452 assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
6453 cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
6454 }
6455
6456 #[gpui::test]
6457 async fn test_buffer_file_changes_on_disk(cx: &mut gpui::TestAppContext) {
6458 use std::fs;
6459
6460 let initial_contents = "aaa\nbbbbb\nc\n";
6461 let dir = temp_tree(json!({ "the-file": initial_contents }));
6462
6463 let project = Project::test(Arc::new(RealFs), cx);
6464 let (worktree, _) = project
6465 .update(cx, |p, cx| {
6466 p.find_or_create_local_worktree(dir.path(), true, cx)
6467 })
6468 .await
6469 .unwrap();
6470 let worktree_id = worktree.read_with(cx, |tree, _| tree.id());
6471
6472 worktree
6473 .read_with(cx, |t, _| t.as_local().unwrap().scan_complete())
6474 .await;
6475
6476 let abs_path = dir.path().join("the-file");
6477 let buffer = project
6478 .update(cx, |p, cx| p.open_buffer((worktree_id, "the-file"), cx))
6479 .await
6480 .unwrap();
6481
6482 // TODO
6483 // Add a cursor on each row.
6484 // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
6485 // assert!(!buffer.is_dirty());
6486 // buffer.add_selection_set(
6487 // &(0..3)
6488 // .map(|row| Selection {
6489 // id: row as usize,
6490 // start: Point::new(row, 1),
6491 // end: Point::new(row, 1),
6492 // reversed: false,
6493 // goal: SelectionGoal::None,
6494 // })
6495 // .collect::<Vec<_>>(),
6496 // cx,
6497 // )
6498 // });
6499
6500 // Change the file on disk, adding two new lines of text, and removing
6501 // one line.
6502 buffer.read_with(cx, |buffer, _| {
6503 assert!(!buffer.is_dirty());
6504 assert!(!buffer.has_conflict());
6505 });
6506 let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
6507 fs::write(&abs_path, new_contents).unwrap();
6508
6509 // Because the buffer was not modified, it is reloaded from disk. Its
6510 // contents are edited according to the diff between the old and new
6511 // file contents.
6512 buffer
6513 .condition(&cx, |buffer, _| buffer.text() == new_contents)
6514 .await;
6515
6516 buffer.update(cx, |buffer, _| {
6517 assert_eq!(buffer.text(), new_contents);
6518 assert!(!buffer.is_dirty());
6519 assert!(!buffer.has_conflict());
6520
6521 // TODO
6522 // let cursor_positions = buffer
6523 // .selection_set(selection_set_id)
6524 // .unwrap()
6525 // .selections::<Point>(&*buffer)
6526 // .map(|selection| {
6527 // assert_eq!(selection.start, selection.end);
6528 // selection.start
6529 // })
6530 // .collect::<Vec<_>>();
6531 // assert_eq!(
6532 // cursor_positions,
6533 // [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
6534 // );
6535 });
6536
6537 // Modify the buffer
6538 buffer.update(cx, |buffer, cx| {
6539 buffer.edit(vec![0..0], " ", cx);
6540 assert!(buffer.is_dirty());
6541 assert!(!buffer.has_conflict());
6542 });
6543
6544 // Change the file on disk again, adding blank lines to the beginning.
6545 fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
6546
6547 // Because the buffer is modified, it doesn't reload from disk, but is
6548 // marked as having a conflict.
6549 buffer
6550 .condition(&cx, |buffer, _| buffer.has_conflict())
6551 .await;
6552 }
6553
6554 #[gpui::test]
6555 async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
6556 cx.foreground().forbid_parking();
6557
6558 let fs = FakeFs::new(cx.background());
6559 fs.insert_tree(
6560 "/the-dir",
6561 json!({
6562 "a.rs": "
6563 fn foo(mut v: Vec<usize>) {
6564 for x in &v {
6565 v.push(1);
6566 }
6567 }
6568 "
6569 .unindent(),
6570 }),
6571 )
6572 .await;
6573
6574 let project = Project::test(fs.clone(), cx);
6575 let (worktree, _) = project
6576 .update(cx, |p, cx| {
6577 p.find_or_create_local_worktree("/the-dir", true, cx)
6578 })
6579 .await
6580 .unwrap();
6581 let worktree_id = worktree.read_with(cx, |tree, _| tree.id());
6582
6583 let buffer = project
6584 .update(cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
6585 .await
6586 .unwrap();
6587
6588 let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
6589 let message = lsp::PublishDiagnosticsParams {
6590 uri: buffer_uri.clone(),
6591 diagnostics: vec![
6592 lsp::Diagnostic {
6593 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
6594 severity: Some(DiagnosticSeverity::WARNING),
6595 message: "error 1".to_string(),
6596 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
6597 location: lsp::Location {
6598 uri: buffer_uri.clone(),
6599 range: lsp::Range::new(
6600 lsp::Position::new(1, 8),
6601 lsp::Position::new(1, 9),
6602 ),
6603 },
6604 message: "error 1 hint 1".to_string(),
6605 }]),
6606 ..Default::default()
6607 },
6608 lsp::Diagnostic {
6609 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
6610 severity: Some(DiagnosticSeverity::HINT),
6611 message: "error 1 hint 1".to_string(),
6612 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
6613 location: lsp::Location {
6614 uri: buffer_uri.clone(),
6615 range: lsp::Range::new(
6616 lsp::Position::new(1, 8),
6617 lsp::Position::new(1, 9),
6618 ),
6619 },
6620 message: "original diagnostic".to_string(),
6621 }]),
6622 ..Default::default()
6623 },
6624 lsp::Diagnostic {
6625 range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
6626 severity: Some(DiagnosticSeverity::ERROR),
6627 message: "error 2".to_string(),
6628 related_information: Some(vec![
6629 lsp::DiagnosticRelatedInformation {
6630 location: lsp::Location {
6631 uri: buffer_uri.clone(),
6632 range: lsp::Range::new(
6633 lsp::Position::new(1, 13),
6634 lsp::Position::new(1, 15),
6635 ),
6636 },
6637 message: "error 2 hint 1".to_string(),
6638 },
6639 lsp::DiagnosticRelatedInformation {
6640 location: lsp::Location {
6641 uri: buffer_uri.clone(),
6642 range: lsp::Range::new(
6643 lsp::Position::new(1, 13),
6644 lsp::Position::new(1, 15),
6645 ),
6646 },
6647 message: "error 2 hint 2".to_string(),
6648 },
6649 ]),
6650 ..Default::default()
6651 },
6652 lsp::Diagnostic {
6653 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
6654 severity: Some(DiagnosticSeverity::HINT),
6655 message: "error 2 hint 1".to_string(),
6656 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
6657 location: lsp::Location {
6658 uri: buffer_uri.clone(),
6659 range: lsp::Range::new(
6660 lsp::Position::new(2, 8),
6661 lsp::Position::new(2, 17),
6662 ),
6663 },
6664 message: "original diagnostic".to_string(),
6665 }]),
6666 ..Default::default()
6667 },
6668 lsp::Diagnostic {
6669 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
6670 severity: Some(DiagnosticSeverity::HINT),
6671 message: "error 2 hint 2".to_string(),
6672 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
6673 location: lsp::Location {
6674 uri: buffer_uri.clone(),
6675 range: lsp::Range::new(
6676 lsp::Position::new(2, 8),
6677 lsp::Position::new(2, 17),
6678 ),
6679 },
6680 message: "original diagnostic".to_string(),
6681 }]),
6682 ..Default::default()
6683 },
6684 ],
6685 version: None,
6686 };
6687
6688 project
6689 .update(cx, |p, cx| p.update_diagnostics(message, &[], cx))
6690 .unwrap();
6691 let buffer = buffer.read_with(cx, |buffer, _| buffer.snapshot());
6692
6693 assert_eq!(
6694 buffer
6695 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
6696 .collect::<Vec<_>>(),
6697 &[
6698 DiagnosticEntry {
6699 range: Point::new(1, 8)..Point::new(1, 9),
6700 diagnostic: Diagnostic {
6701 severity: DiagnosticSeverity::WARNING,
6702 message: "error 1".to_string(),
6703 group_id: 0,
6704 is_primary: true,
6705 ..Default::default()
6706 }
6707 },
6708 DiagnosticEntry {
6709 range: Point::new(1, 8)..Point::new(1, 9),
6710 diagnostic: Diagnostic {
6711 severity: DiagnosticSeverity::HINT,
6712 message: "error 1 hint 1".to_string(),
6713 group_id: 0,
6714 is_primary: false,
6715 ..Default::default()
6716 }
6717 },
6718 DiagnosticEntry {
6719 range: Point::new(1, 13)..Point::new(1, 15),
6720 diagnostic: Diagnostic {
6721 severity: DiagnosticSeverity::HINT,
6722 message: "error 2 hint 1".to_string(),
6723 group_id: 1,
6724 is_primary: false,
6725 ..Default::default()
6726 }
6727 },
6728 DiagnosticEntry {
6729 range: Point::new(1, 13)..Point::new(1, 15),
6730 diagnostic: Diagnostic {
6731 severity: DiagnosticSeverity::HINT,
6732 message: "error 2 hint 2".to_string(),
6733 group_id: 1,
6734 is_primary: false,
6735 ..Default::default()
6736 }
6737 },
6738 DiagnosticEntry {
6739 range: Point::new(2, 8)..Point::new(2, 17),
6740 diagnostic: Diagnostic {
6741 severity: DiagnosticSeverity::ERROR,
6742 message: "error 2".to_string(),
6743 group_id: 1,
6744 is_primary: true,
6745 ..Default::default()
6746 }
6747 }
6748 ]
6749 );
6750
6751 assert_eq!(
6752 buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
6753 &[
6754 DiagnosticEntry {
6755 range: Point::new(1, 8)..Point::new(1, 9),
6756 diagnostic: Diagnostic {
6757 severity: DiagnosticSeverity::WARNING,
6758 message: "error 1".to_string(),
6759 group_id: 0,
6760 is_primary: true,
6761 ..Default::default()
6762 }
6763 },
6764 DiagnosticEntry {
6765 range: Point::new(1, 8)..Point::new(1, 9),
6766 diagnostic: Diagnostic {
6767 severity: DiagnosticSeverity::HINT,
6768 message: "error 1 hint 1".to_string(),
6769 group_id: 0,
6770 is_primary: false,
6771 ..Default::default()
6772 }
6773 },
6774 ]
6775 );
6776 assert_eq!(
6777 buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
6778 &[
6779 DiagnosticEntry {
6780 range: Point::new(1, 13)..Point::new(1, 15),
6781 diagnostic: Diagnostic {
6782 severity: DiagnosticSeverity::HINT,
6783 message: "error 2 hint 1".to_string(),
6784 group_id: 1,
6785 is_primary: false,
6786 ..Default::default()
6787 }
6788 },
6789 DiagnosticEntry {
6790 range: Point::new(1, 13)..Point::new(1, 15),
6791 diagnostic: Diagnostic {
6792 severity: DiagnosticSeverity::HINT,
6793 message: "error 2 hint 2".to_string(),
6794 group_id: 1,
6795 is_primary: false,
6796 ..Default::default()
6797 }
6798 },
6799 DiagnosticEntry {
6800 range: Point::new(2, 8)..Point::new(2, 17),
6801 diagnostic: Diagnostic {
6802 severity: DiagnosticSeverity::ERROR,
6803 message: "error 2".to_string(),
6804 group_id: 1,
6805 is_primary: true,
6806 ..Default::default()
6807 }
6808 }
6809 ]
6810 );
6811 }
6812
6813 #[gpui::test]
6814 async fn test_rename(cx: &mut gpui::TestAppContext) {
6815 cx.foreground().forbid_parking();
6816
6817 let mut language = Language::new(
6818 LanguageConfig {
6819 name: "Rust".into(),
6820 path_suffixes: vec!["rs".to_string()],
6821 ..Default::default()
6822 },
6823 Some(tree_sitter_rust::language()),
6824 );
6825 let mut fake_servers = language.set_fake_lsp_adapter(Default::default());
6826
6827 let fs = FakeFs::new(cx.background());
6828 fs.insert_tree(
6829 "/dir",
6830 json!({
6831 "one.rs": "const ONE: usize = 1;",
6832 "two.rs": "const TWO: usize = one::ONE + one::ONE;"
6833 }),
6834 )
6835 .await;
6836
6837 let project = Project::test(fs.clone(), cx);
6838 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
6839
6840 let (tree, _) = project
6841 .update(cx, |project, cx| {
6842 project.find_or_create_local_worktree("/dir", true, cx)
6843 })
6844 .await
6845 .unwrap();
6846 let worktree_id = tree.read_with(cx, |tree, _| tree.id());
6847 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
6848 .await;
6849
6850 let buffer = project
6851 .update(cx, |project, cx| {
6852 project.open_buffer((worktree_id, Path::new("one.rs")), cx)
6853 })
6854 .await
6855 .unwrap();
6856
6857 let fake_server = fake_servers.next().await.unwrap();
6858
6859 let response = project.update(cx, |project, cx| {
6860 project.prepare_rename(buffer.clone(), 7, cx)
6861 });
6862 fake_server
6863 .handle_request::<lsp::request::PrepareRenameRequest, _, _>(|params, _| async move {
6864 assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
6865 assert_eq!(params.position, lsp::Position::new(0, 7));
6866 Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
6867 lsp::Position::new(0, 6),
6868 lsp::Position::new(0, 9),
6869 ))))
6870 })
6871 .next()
6872 .await
6873 .unwrap();
6874 let range = response.await.unwrap().unwrap();
6875 let range = buffer.read_with(cx, |buffer, _| range.to_offset(buffer));
6876 assert_eq!(range, 6..9);
6877
6878 let response = project.update(cx, |project, cx| {
6879 project.perform_rename(buffer.clone(), 7, "THREE".to_string(), true, cx)
6880 });
6881 fake_server
6882 .handle_request::<lsp::request::Rename, _, _>(|params, _| async move {
6883 assert_eq!(
6884 params.text_document_position.text_document.uri.as_str(),
6885 "file:///dir/one.rs"
6886 );
6887 assert_eq!(
6888 params.text_document_position.position,
6889 lsp::Position::new(0, 7)
6890 );
6891 assert_eq!(params.new_name, "THREE");
6892 Ok(Some(lsp::WorkspaceEdit {
6893 changes: Some(
6894 [
6895 (
6896 lsp::Url::from_file_path("/dir/one.rs").unwrap(),
6897 vec![lsp::TextEdit::new(
6898 lsp::Range::new(
6899 lsp::Position::new(0, 6),
6900 lsp::Position::new(0, 9),
6901 ),
6902 "THREE".to_string(),
6903 )],
6904 ),
6905 (
6906 lsp::Url::from_file_path("/dir/two.rs").unwrap(),
6907 vec![
6908 lsp::TextEdit::new(
6909 lsp::Range::new(
6910 lsp::Position::new(0, 24),
6911 lsp::Position::new(0, 27),
6912 ),
6913 "THREE".to_string(),
6914 ),
6915 lsp::TextEdit::new(
6916 lsp::Range::new(
6917 lsp::Position::new(0, 35),
6918 lsp::Position::new(0, 38),
6919 ),
6920 "THREE".to_string(),
6921 ),
6922 ],
6923 ),
6924 ]
6925 .into_iter()
6926 .collect(),
6927 ),
6928 ..Default::default()
6929 }))
6930 })
6931 .next()
6932 .await
6933 .unwrap();
6934 let mut transaction = response.await.unwrap().0;
6935 assert_eq!(transaction.len(), 2);
6936 assert_eq!(
6937 transaction
6938 .remove_entry(&buffer)
6939 .unwrap()
6940 .0
6941 .read_with(cx, |buffer, _| buffer.text()),
6942 "const THREE: usize = 1;"
6943 );
6944 assert_eq!(
6945 transaction
6946 .into_keys()
6947 .next()
6948 .unwrap()
6949 .read_with(cx, |buffer, _| buffer.text()),
6950 "const TWO: usize = one::THREE + one::THREE;"
6951 );
6952 }
6953
6954 #[gpui::test]
6955 async fn test_search(cx: &mut gpui::TestAppContext) {
6956 let fs = FakeFs::new(cx.background());
6957 fs.insert_tree(
6958 "/dir",
6959 json!({
6960 "one.rs": "const ONE: usize = 1;",
6961 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
6962 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
6963 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
6964 }),
6965 )
6966 .await;
6967 let project = Project::test(fs.clone(), cx);
6968 let (tree, _) = project
6969 .update(cx, |project, cx| {
6970 project.find_or_create_local_worktree("/dir", true, cx)
6971 })
6972 .await
6973 .unwrap();
6974 let worktree_id = tree.read_with(cx, |tree, _| tree.id());
6975 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
6976 .await;
6977
6978 assert_eq!(
6979 search(&project, SearchQuery::text("TWO", false, true), cx)
6980 .await
6981 .unwrap(),
6982 HashMap::from_iter([
6983 ("two.rs".to_string(), vec![6..9]),
6984 ("three.rs".to_string(), vec![37..40])
6985 ])
6986 );
6987
6988 let buffer_4 = project
6989 .update(cx, |project, cx| {
6990 project.open_buffer((worktree_id, "four.rs"), cx)
6991 })
6992 .await
6993 .unwrap();
6994 buffer_4.update(cx, |buffer, cx| {
6995 buffer.edit([20..28, 31..43], "two::TWO", cx);
6996 });
6997
6998 assert_eq!(
6999 search(&project, SearchQuery::text("TWO", false, true), cx)
7000 .await
7001 .unwrap(),
7002 HashMap::from_iter([
7003 ("two.rs".to_string(), vec![6..9]),
7004 ("three.rs".to_string(), vec![37..40]),
7005 ("four.rs".to_string(), vec![25..28, 36..39])
7006 ])
7007 );
7008
7009 async fn search(
7010 project: &ModelHandle<Project>,
7011 query: SearchQuery,
7012 cx: &mut gpui::TestAppContext,
7013 ) -> Result<HashMap<String, Vec<Range<usize>>>> {
7014 let results = project
7015 .update(cx, |project, cx| project.search(query, cx))
7016 .await?;
7017
7018 Ok(results
7019 .into_iter()
7020 .map(|(buffer, ranges)| {
7021 buffer.read_with(cx, |buffer, _| {
7022 let path = buffer.file().unwrap().path().to_string_lossy().to_string();
7023 let ranges = ranges
7024 .into_iter()
7025 .map(|range| range.to_offset(buffer))
7026 .collect::<Vec<_>>();
7027 (path, ranges)
7028 })
7029 })
7030 .collect())
7031 }
7032 }
7033}