1pub mod fs;
2mod ignore;
3pub mod worktree;
4
5use anyhow::{anyhow, Result};
6use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
7use clock::ReplicaId;
8use collections::{hash_map, HashMap, HashSet};
9use futures::Future;
10use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
11use gpui::{
12 AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext, Task,
13 WeakModelHandle,
14};
15use language::{
16 range_from_lsp, Bias, Buffer, Diagnostic, DiagnosticEntry, File as _, Language,
17 LanguageRegistry, Operation, ToOffset, ToPointUtf16,
18};
19use lsp::{DiagnosticSeverity, LanguageServer};
20use postage::{prelude::Stream, watch};
21use smol::block_on;
22use std::{
23 convert::TryInto,
24 ops::Range,
25 path::{Path, PathBuf},
26 sync::{
27 atomic::{AtomicBool, Ordering::SeqCst},
28 Arc,
29 },
30};
31use util::{post_inc, ResultExt, TryFutureExt as _};
32
33pub use fs::*;
34pub use worktree::*;
35
36pub struct Project {
37 worktrees: Vec<WorktreeHandle>,
38 active_entry: Option<ProjectEntry>,
39 languages: Arc<LanguageRegistry>,
40 language_servers: HashMap<(WorktreeId, String), Arc<LanguageServer>>,
41 client: Arc<client::Client>,
42 user_store: ModelHandle<UserStore>,
43 fs: Arc<dyn Fs>,
44 client_state: ProjectClientState,
45 collaborators: HashMap<PeerId, Collaborator>,
46 subscriptions: Vec<client::Subscription>,
47 language_servers_with_diagnostics_running: isize,
48 open_buffers: HashMap<usize, OpenBuffer>,
49 loading_buffers: HashMap<
50 ProjectPath,
51 postage::watch::Receiver<
52 Option<Result<(ModelHandle<Buffer>, Arc<AtomicBool>), Arc<anyhow::Error>>>,
53 >,
54 >,
55 shared_buffers: HashMap<PeerId, HashMap<u64, ModelHandle<Buffer>>>,
56}
57
58enum OpenBuffer {
59 Operations(Vec<Operation>),
60 Loaded(WeakModelHandle<Buffer>),
61}
62
63enum WorktreeHandle {
64 Strong(ModelHandle<Worktree>),
65 Weak(WeakModelHandle<Worktree>),
66}
67
68enum ProjectClientState {
69 Local {
70 is_shared: bool,
71 remote_id_tx: watch::Sender<Option<u64>>,
72 remote_id_rx: watch::Receiver<Option<u64>>,
73 _maintain_remote_id_task: Task<Option<()>>,
74 },
75 Remote {
76 sharing_has_stopped: bool,
77 remote_id: u64,
78 replica_id: ReplicaId,
79 },
80}
81
82#[derive(Clone, Debug)]
83pub struct Collaborator {
84 pub user: Arc<User>,
85 pub peer_id: PeerId,
86 pub replica_id: ReplicaId,
87}
88
89#[derive(Clone, Debug, PartialEq)]
90pub enum Event {
91 ActiveEntryChanged(Option<ProjectEntry>),
92 WorktreeRemoved(WorktreeId),
93 DiskBasedDiagnosticsStarted,
94 DiskBasedDiagnosticsUpdated,
95 DiskBasedDiagnosticsFinished,
96 DiagnosticsUpdated(ProjectPath),
97}
98
99#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
100pub struct ProjectPath {
101 pub worktree_id: WorktreeId,
102 pub path: Arc<Path>,
103}
104
105#[derive(Clone, Debug, Default, PartialEq)]
106pub struct DiagnosticSummary {
107 pub error_count: usize,
108 pub warning_count: usize,
109 pub info_count: usize,
110 pub hint_count: usize,
111}
112
113#[derive(Debug)]
114pub struct Definition {
115 pub target_buffer: ModelHandle<Buffer>,
116 pub target_range: Range<language::Anchor>,
117}
118
119impl DiagnosticSummary {
120 fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
121 let mut this = Self {
122 error_count: 0,
123 warning_count: 0,
124 info_count: 0,
125 hint_count: 0,
126 };
127
128 for entry in diagnostics {
129 if entry.diagnostic.is_primary {
130 match entry.diagnostic.severity {
131 DiagnosticSeverity::ERROR => this.error_count += 1,
132 DiagnosticSeverity::WARNING => this.warning_count += 1,
133 DiagnosticSeverity::INFORMATION => this.info_count += 1,
134 DiagnosticSeverity::HINT => this.hint_count += 1,
135 _ => {}
136 }
137 }
138 }
139
140 this
141 }
142
143 pub fn to_proto(&self, path: Arc<Path>) -> proto::DiagnosticSummary {
144 proto::DiagnosticSummary {
145 path: path.to_string_lossy().to_string(),
146 error_count: self.error_count as u32,
147 warning_count: self.warning_count as u32,
148 info_count: self.info_count as u32,
149 hint_count: self.hint_count as u32,
150 }
151 }
152}
153
154#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
155pub struct ProjectEntry {
156 pub worktree_id: WorktreeId,
157 pub entry_id: usize,
158}
159
160impl Project {
161 pub fn local(
162 client: Arc<Client>,
163 user_store: ModelHandle<UserStore>,
164 languages: Arc<LanguageRegistry>,
165 fs: Arc<dyn Fs>,
166 cx: &mut MutableAppContext,
167 ) -> ModelHandle<Self> {
168 cx.add_model(|cx: &mut ModelContext<Self>| {
169 let (remote_id_tx, remote_id_rx) = watch::channel();
170 let _maintain_remote_id_task = cx.spawn_weak({
171 let rpc = client.clone();
172 move |this, mut cx| {
173 async move {
174 let mut status = rpc.status();
175 while let Some(status) = status.recv().await {
176 if let Some(this) = this.upgrade(&cx) {
177 let remote_id = if let client::Status::Connected { .. } = status {
178 let response = rpc.request(proto::RegisterProject {}).await?;
179 Some(response.project_id)
180 } else {
181 None
182 };
183
184 if let Some(project_id) = remote_id {
185 let mut registrations = Vec::new();
186 this.update(&mut cx, |this, cx| {
187 for worktree in this.worktrees(cx).collect::<Vec<_>>() {
188 registrations.push(worktree.update(
189 cx,
190 |worktree, cx| {
191 let worktree = worktree.as_local_mut().unwrap();
192 worktree.register(project_id, cx)
193 },
194 ));
195 }
196 });
197 for registration in registrations {
198 registration.await?;
199 }
200 }
201 this.update(&mut cx, |this, cx| this.set_remote_id(remote_id, cx));
202 }
203 }
204 Ok(())
205 }
206 .log_err()
207 }
208 });
209
210 Self {
211 worktrees: Default::default(),
212 collaborators: Default::default(),
213 open_buffers: Default::default(),
214 loading_buffers: Default::default(),
215 shared_buffers: Default::default(),
216 client_state: ProjectClientState::Local {
217 is_shared: false,
218 remote_id_tx,
219 remote_id_rx,
220 _maintain_remote_id_task,
221 },
222 subscriptions: Vec::new(),
223 active_entry: None,
224 languages,
225 client,
226 user_store,
227 fs,
228 language_servers_with_diagnostics_running: 0,
229 language_servers: Default::default(),
230 }
231 })
232 }
233
234 pub async fn remote(
235 remote_id: u64,
236 client: Arc<Client>,
237 user_store: ModelHandle<UserStore>,
238 languages: Arc<LanguageRegistry>,
239 fs: Arc<dyn Fs>,
240 cx: &mut AsyncAppContext,
241 ) -> Result<ModelHandle<Self>> {
242 client.authenticate_and_connect(&cx).await?;
243
244 let response = client
245 .request(proto::JoinProject {
246 project_id: remote_id,
247 })
248 .await?;
249
250 let replica_id = response.replica_id as ReplicaId;
251
252 let mut worktrees = Vec::new();
253 for worktree in response.worktrees {
254 worktrees
255 .push(Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx).await?);
256 }
257
258 let user_ids = response
259 .collaborators
260 .iter()
261 .map(|peer| peer.user_id)
262 .collect();
263 user_store
264 .update(cx, |user_store, cx| user_store.load_users(user_ids, cx))
265 .await?;
266 let mut collaborators = HashMap::default();
267 for message in response.collaborators {
268 let collaborator = Collaborator::from_proto(message, &user_store, cx).await?;
269 collaborators.insert(collaborator.peer_id, collaborator);
270 }
271
272 Ok(cx.add_model(|cx| {
273 let mut this = Self {
274 worktrees: Vec::new(),
275 open_buffers: Default::default(),
276 loading_buffers: Default::default(),
277 shared_buffers: Default::default(),
278 active_entry: None,
279 collaborators,
280 languages,
281 user_store,
282 fs,
283 subscriptions: vec![
284 client.subscribe_to_entity(remote_id, cx, Self::handle_unshare_project),
285 client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator),
286 client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator),
287 client.subscribe_to_entity(remote_id, cx, Self::handle_share_worktree),
288 client.subscribe_to_entity(remote_id, cx, Self::handle_unregister_worktree),
289 client.subscribe_to_entity(remote_id, cx, Self::handle_update_worktree),
290 client.subscribe_to_entity(
291 remote_id,
292 cx,
293 Self::handle_update_diagnostic_summary,
294 ),
295 client.subscribe_to_entity(
296 remote_id,
297 cx,
298 Self::handle_disk_based_diagnostics_updating,
299 ),
300 client.subscribe_to_entity(
301 remote_id,
302 cx,
303 Self::handle_disk_based_diagnostics_updated,
304 ),
305 client.subscribe_to_entity(remote_id, cx, Self::handle_update_buffer),
306 client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_saved),
307 ],
308 client,
309 client_state: ProjectClientState::Remote {
310 sharing_has_stopped: false,
311 remote_id,
312 replica_id,
313 },
314 language_servers_with_diagnostics_running: 0,
315 language_servers: Default::default(),
316 };
317 for worktree in worktrees {
318 this.add_worktree(&worktree, cx);
319 }
320 this
321 }))
322 }
323
324 fn set_remote_id(&mut self, remote_id: Option<u64>, cx: &mut ModelContext<Self>) {
325 if let ProjectClientState::Local { remote_id_tx, .. } = &mut self.client_state {
326 *remote_id_tx.borrow_mut() = remote_id;
327 }
328
329 self.subscriptions.clear();
330 if let Some(remote_id) = remote_id {
331 let client = &self.client;
332 self.subscriptions.extend([
333 client.subscribe_to_entity(remote_id, cx, Self::handle_open_buffer),
334 client.subscribe_to_entity(remote_id, cx, Self::handle_close_buffer),
335 client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator),
336 client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator),
337 client.subscribe_to_entity(remote_id, cx, Self::handle_update_worktree),
338 client.subscribe_to_entity(remote_id, cx, Self::handle_update_buffer),
339 client.subscribe_to_entity(remote_id, cx, Self::handle_save_buffer),
340 client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_saved),
341 client.subscribe_to_entity(remote_id, cx, Self::handle_format_buffer),
342 ]);
343 }
344 }
345
346 pub fn remote_id(&self) -> Option<u64> {
347 match &self.client_state {
348 ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
349 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
350 }
351 }
352
353 pub fn next_remote_id(&self) -> impl Future<Output = u64> {
354 let mut id = None;
355 let mut watch = None;
356 match &self.client_state {
357 ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
358 ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
359 }
360
361 async move {
362 if let Some(id) = id {
363 return id;
364 }
365 let mut watch = watch.unwrap();
366 loop {
367 let id = *watch.borrow();
368 if let Some(id) = id {
369 return id;
370 }
371 watch.recv().await;
372 }
373 }
374 }
375
376 pub fn replica_id(&self) -> ReplicaId {
377 match &self.client_state {
378 ProjectClientState::Local { .. } => 0,
379 ProjectClientState::Remote { replica_id, .. } => *replica_id,
380 }
381 }
382
383 pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
384 &self.collaborators
385 }
386
387 pub fn worktrees<'a>(
388 &'a self,
389 cx: &'a AppContext,
390 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
391 self.worktrees
392 .iter()
393 .filter_map(move |worktree| worktree.upgrade(cx))
394 }
395
396 pub fn worktree_for_id(
397 &self,
398 id: WorktreeId,
399 cx: &AppContext,
400 ) -> Option<ModelHandle<Worktree>> {
401 self.worktrees(cx)
402 .find(|worktree| worktree.read(cx).id() == id)
403 }
404
405 pub fn share(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
406 let rpc = self.client.clone();
407 cx.spawn(|this, mut cx| async move {
408 let project_id = this.update(&mut cx, |this, _| {
409 if let ProjectClientState::Local {
410 is_shared,
411 remote_id_rx,
412 ..
413 } = &mut this.client_state
414 {
415 *is_shared = true;
416 remote_id_rx
417 .borrow()
418 .ok_or_else(|| anyhow!("no project id"))
419 } else {
420 Err(anyhow!("can't share a remote project"))
421 }
422 })?;
423
424 rpc.request(proto::ShareProject { project_id }).await?;
425 let mut tasks = Vec::new();
426 this.update(&mut cx, |this, cx| {
427 for worktree in this.worktrees(cx).collect::<Vec<_>>() {
428 worktree.update(cx, |worktree, cx| {
429 let worktree = worktree.as_local_mut().unwrap();
430 tasks.push(worktree.share(project_id, cx));
431 });
432 }
433 });
434 for task in tasks {
435 task.await?;
436 }
437 this.update(&mut cx, |_, cx| cx.notify());
438 Ok(())
439 })
440 }
441
442 pub fn unshare(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
443 let rpc = self.client.clone();
444 cx.spawn(|this, mut cx| async move {
445 let project_id = this.update(&mut cx, |this, _| {
446 if let ProjectClientState::Local {
447 is_shared,
448 remote_id_rx,
449 ..
450 } = &mut this.client_state
451 {
452 *is_shared = false;
453 remote_id_rx
454 .borrow()
455 .ok_or_else(|| anyhow!("no project id"))
456 } else {
457 Err(anyhow!("can't share a remote project"))
458 }
459 })?;
460
461 rpc.send(proto::UnshareProject { project_id }).await?;
462 this.update(&mut cx, |this, cx| {
463 this.collaborators.clear();
464 for worktree in this.worktrees(cx).collect::<Vec<_>>() {
465 worktree.update(cx, |worktree, _| {
466 worktree.as_local_mut().unwrap().unshare();
467 });
468 }
469 cx.notify()
470 });
471 Ok(())
472 })
473 }
474
475 pub fn is_read_only(&self) -> bool {
476 match &self.client_state {
477 ProjectClientState::Local { .. } => false,
478 ProjectClientState::Remote {
479 sharing_has_stopped,
480 ..
481 } => *sharing_has_stopped,
482 }
483 }
484
485 pub fn is_local(&self) -> bool {
486 match &self.client_state {
487 ProjectClientState::Local { .. } => true,
488 ProjectClientState::Remote { .. } => false,
489 }
490 }
491
492 pub fn open_buffer(
493 &mut self,
494 path: impl Into<ProjectPath>,
495 cx: &mut ModelContext<Self>,
496 ) -> Task<Result<ModelHandle<Buffer>>> {
497 let path = path.into();
498 let worktree = if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
499 worktree
500 } else {
501 return cx
502 .foreground()
503 .spawn(async move { Err(anyhow!("no such worktree")) });
504 };
505
506 // If there is already a buffer for the given path, then return it.
507 let existing_buffer = self.get_open_buffer(&path, cx);
508 if let Some(existing_buffer) = existing_buffer {
509 return cx.foreground().spawn(async move { Ok(existing_buffer) });
510 }
511
512 let mut loading_watch = match self.loading_buffers.entry(path.clone()) {
513 // If the given path is already being loaded, then wait for that existing
514 // task to complete and return the same buffer.
515 hash_map::Entry::Occupied(e) => e.get().clone(),
516
517 // Otherwise, record the fact that this path is now being loaded.
518 hash_map::Entry::Vacant(entry) => {
519 let (mut tx, rx) = postage::watch::channel();
520 entry.insert(rx.clone());
521
522 let load_buffer = worktree.update(cx, |worktree, cx| match worktree {
523 Worktree::Local(worktree) => worktree.open_buffer(&path.path, cx),
524 Worktree::Remote(worktree) => worktree.open_buffer(&path.path, cx),
525 });
526
527 cx.spawn(move |this, mut cx| async move {
528 let load_result = load_buffer.await;
529 *tx.borrow_mut() = Some(this.update(&mut cx, |this, cx| {
530 // Record the fact that the buffer is no longer loading.
531 this.loading_buffers.remove(&path);
532 let buffer = load_result.map_err(Arc::new)?;
533 this.open_buffers.insert(
534 buffer.read(cx).remote_id() as usize,
535 OpenBuffer::Loaded(buffer.downgrade()),
536 );
537 Ok((buffer, Arc::new(AtomicBool::new(true))))
538 }));
539 })
540 .detach();
541 rx
542 }
543 };
544
545 cx.spawn(|this, mut cx| async move {
546 let (buffer, buffer_is_new) = loop {
547 if let Some(result) = loading_watch.borrow().as_ref() {
548 break match result {
549 Ok((buf, is_new)) => Ok((buf.clone(), is_new.fetch_and(false, SeqCst))),
550 Err(error) => Err(anyhow!("{}", error)),
551 };
552 }
553 loading_watch.recv().await;
554 }?;
555
556 if buffer_is_new {
557 this.update(&mut cx, |this, cx| {
558 this.assign_language_to_buffer(worktree, buffer.clone(), cx)
559 });
560 }
561 Ok(buffer)
562 })
563 }
564
565 pub fn save_buffer_as(
566 &self,
567 buffer: ModelHandle<Buffer>,
568 abs_path: PathBuf,
569 cx: &mut ModelContext<Project>,
570 ) -> Task<Result<()>> {
571 let worktree_task = self.find_or_create_worktree_for_abs_path(&abs_path, false, cx);
572 cx.spawn(|this, mut cx| async move {
573 let (worktree, path) = worktree_task.await?;
574 worktree
575 .update(&mut cx, |worktree, cx| {
576 worktree
577 .as_local_mut()
578 .unwrap()
579 .save_buffer_as(buffer.clone(), path, cx)
580 })
581 .await?;
582 this.update(&mut cx, |this, cx| {
583 this.open_buffers
584 .insert(buffer.id(), OpenBuffer::Loaded(buffer.downgrade()));
585 this.assign_language_to_buffer(worktree, buffer, cx)
586 });
587 Ok(())
588 })
589 }
590
591 #[cfg(any(test, feature = "test-support"))]
592 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
593 let path = path.into();
594 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
595 self.open_buffers.iter().any(|(_, buffer)| {
596 if let Some(buffer) = buffer.upgrade(cx) {
597 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
598 if file.worktree == worktree && file.path() == &path.path {
599 return true;
600 }
601 }
602 }
603 false
604 })
605 } else {
606 false
607 }
608 }
609
610 fn get_open_buffer(
611 &mut self,
612 path: &ProjectPath,
613 cx: &mut ModelContext<Self>,
614 ) -> Option<ModelHandle<Buffer>> {
615 let mut result = None;
616 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
617 self.open_buffers.retain(|_, buffer| {
618 if let OpenBuffer::Loaded(buffer) = buffer {
619 if let Some(buffer) = buffer.upgrade(cx) {
620 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
621 if file.worktree == worktree && file.path() == &path.path {
622 result = Some(buffer);
623 }
624 }
625 return true;
626 }
627 }
628 false
629 });
630 result
631 }
632
633 fn assign_language_to_buffer(
634 &mut self,
635 worktree: ModelHandle<Worktree>,
636 buffer: ModelHandle<Buffer>,
637 cx: &mut ModelContext<Self>,
638 ) -> Option<()> {
639 // Set the buffer's language
640 let full_path = buffer.read(cx).file()?.full_path();
641 let language = self.languages.select_language(&full_path)?.clone();
642 buffer.update(cx, |buffer, cx| {
643 buffer.set_language(Some(language.clone()), cx);
644 });
645
646 // For local worktrees, start a language server if needed.
647 let worktree = worktree.read(cx);
648 let worktree_id = worktree.id();
649 let worktree_abs_path = worktree.as_local()?.abs_path().clone();
650 let language_server = match self
651 .language_servers
652 .entry((worktree_id, language.name().to_string()))
653 {
654 hash_map::Entry::Occupied(e) => Some(e.get().clone()),
655 hash_map::Entry::Vacant(e) => {
656 Self::start_language_server(self.client.clone(), language, &worktree_abs_path, cx)
657 .map(|server| e.insert(server).clone())
658 }
659 };
660
661 buffer.update(cx, |buffer, cx| {
662 buffer.set_language_server(language_server, cx)
663 });
664
665 None
666 }
667
668 fn start_language_server(
669 rpc: Arc<Client>,
670 language: Arc<Language>,
671 worktree_path: &Path,
672 cx: &mut ModelContext<Self>,
673 ) -> Option<Arc<LanguageServer>> {
674 enum LspEvent {
675 DiagnosticsStart,
676 DiagnosticsUpdate(lsp::PublishDiagnosticsParams),
677 DiagnosticsFinish,
678 }
679
680 let language_server = language
681 .start_server(worktree_path, cx)
682 .log_err()
683 .flatten()?;
684 let disk_based_sources = language
685 .disk_based_diagnostic_sources()
686 .cloned()
687 .unwrap_or_default();
688 let disk_based_diagnostics_progress_token =
689 language.disk_based_diagnostics_progress_token().cloned();
690 let has_disk_based_diagnostic_progress_token =
691 disk_based_diagnostics_progress_token.is_some();
692 let (diagnostics_tx, diagnostics_rx) = smol::channel::unbounded();
693
694 // Listen for `PublishDiagnostics` notifications.
695 language_server
696 .on_notification::<lsp::notification::PublishDiagnostics, _>({
697 let diagnostics_tx = diagnostics_tx.clone();
698 move |params| {
699 if !has_disk_based_diagnostic_progress_token {
700 block_on(diagnostics_tx.send(LspEvent::DiagnosticsStart)).ok();
701 }
702 block_on(diagnostics_tx.send(LspEvent::DiagnosticsUpdate(params))).ok();
703 if !has_disk_based_diagnostic_progress_token {
704 block_on(diagnostics_tx.send(LspEvent::DiagnosticsFinish)).ok();
705 }
706 }
707 })
708 .detach();
709
710 // Listen for `Progress` notifications. Send an event when the language server
711 // transitions between running jobs and not running any jobs.
712 let mut running_jobs_for_this_server: i32 = 0;
713 language_server
714 .on_notification::<lsp::notification::Progress, _>(move |params| {
715 let token = match params.token {
716 lsp::NumberOrString::Number(_) => None,
717 lsp::NumberOrString::String(token) => Some(token),
718 };
719
720 if token == disk_based_diagnostics_progress_token {
721 match params.value {
722 lsp::ProgressParamsValue::WorkDone(progress) => match progress {
723 lsp::WorkDoneProgress::Begin(_) => {
724 running_jobs_for_this_server += 1;
725 if running_jobs_for_this_server == 1 {
726 block_on(diagnostics_tx.send(LspEvent::DiagnosticsStart)).ok();
727 }
728 }
729 lsp::WorkDoneProgress::End(_) => {
730 running_jobs_for_this_server -= 1;
731 if running_jobs_for_this_server == 0 {
732 block_on(diagnostics_tx.send(LspEvent::DiagnosticsFinish)).ok();
733 }
734 }
735 _ => {}
736 },
737 }
738 }
739 })
740 .detach();
741
742 // Process all the LSP events.
743 cx.spawn_weak(|this, mut cx| async move {
744 while let Ok(message) = diagnostics_rx.recv().await {
745 let this = cx.read(|cx| this.upgrade(cx))?;
746 match message {
747 LspEvent::DiagnosticsStart => {
748 let send = this.update(&mut cx, |this, cx| {
749 this.disk_based_diagnostics_started(cx);
750 this.remote_id().map(|project_id| {
751 rpc.send(proto::DiskBasedDiagnosticsUpdating { project_id })
752 })
753 });
754 if let Some(send) = send {
755 send.await.log_err();
756 }
757 }
758 LspEvent::DiagnosticsUpdate(params) => {
759 this.update(&mut cx, |this, cx| {
760 this.update_diagnostics(params, &disk_based_sources, cx)
761 .log_err();
762 });
763 }
764 LspEvent::DiagnosticsFinish => {
765 let send = this.update(&mut cx, |this, cx| {
766 this.disk_based_diagnostics_finished(cx);
767 this.remote_id().map(|project_id| {
768 rpc.send(proto::DiskBasedDiagnosticsUpdated { project_id })
769 })
770 });
771 if let Some(send) = send {
772 send.await.log_err();
773 }
774 }
775 }
776 }
777 Some(())
778 })
779 .detach();
780
781 Some(language_server)
782 }
783
784 pub fn update_diagnostics(
785 &mut self,
786 params: lsp::PublishDiagnosticsParams,
787 disk_based_sources: &HashSet<String>,
788 cx: &mut ModelContext<Self>,
789 ) -> Result<()> {
790 let path = params
791 .uri
792 .to_file_path()
793 .map_err(|_| anyhow!("URI is not a file"))?;
794 let (worktree, relative_path) = self
795 .find_worktree_for_abs_path(&path, cx)
796 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
797 let project_path = ProjectPath {
798 worktree_id: worktree.read(cx).id(),
799 path: relative_path.into(),
800 };
801 let mut next_group_id = 0;
802 let mut diagnostics = Vec::default();
803 let mut primary_diagnostic_group_ids = HashMap::default();
804 let mut sources_by_group_id = HashMap::default();
805 let mut supporting_diagnostic_severities = HashMap::default();
806 for diagnostic in ¶ms.diagnostics {
807 let source = diagnostic.source.as_ref();
808 let code = diagnostic.code.as_ref().map(|code| match code {
809 lsp::NumberOrString::Number(code) => code.to_string(),
810 lsp::NumberOrString::String(code) => code.clone(),
811 });
812 let range = range_from_lsp(diagnostic.range);
813 let is_supporting = diagnostic
814 .related_information
815 .as_ref()
816 .map_or(false, |infos| {
817 infos.iter().any(|info| {
818 primary_diagnostic_group_ids.contains_key(&(
819 source,
820 code.clone(),
821 range_from_lsp(info.location.range),
822 ))
823 })
824 });
825
826 if is_supporting {
827 if let Some(severity) = diagnostic.severity {
828 supporting_diagnostic_severities
829 .insert((source, code.clone(), range), severity);
830 }
831 } else {
832 let group_id = post_inc(&mut next_group_id);
833 let is_disk_based =
834 source.map_or(false, |source| disk_based_sources.contains(source));
835
836 sources_by_group_id.insert(group_id, source);
837 primary_diagnostic_group_ids
838 .insert((source, code.clone(), range.clone()), group_id);
839
840 diagnostics.push(DiagnosticEntry {
841 range,
842 diagnostic: Diagnostic {
843 code: code.clone(),
844 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
845 message: diagnostic.message.clone(),
846 group_id,
847 is_primary: true,
848 is_valid: true,
849 is_disk_based,
850 },
851 });
852 if let Some(infos) = &diagnostic.related_information {
853 for info in infos {
854 if info.location.uri == params.uri {
855 let range = range_from_lsp(info.location.range);
856 diagnostics.push(DiagnosticEntry {
857 range,
858 diagnostic: Diagnostic {
859 code: code.clone(),
860 severity: DiagnosticSeverity::INFORMATION,
861 message: info.message.clone(),
862 group_id,
863 is_primary: false,
864 is_valid: true,
865 is_disk_based,
866 },
867 });
868 }
869 }
870 }
871 }
872 }
873
874 for entry in &mut diagnostics {
875 let diagnostic = &mut entry.diagnostic;
876 if !diagnostic.is_primary {
877 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
878 if let Some(&severity) = supporting_diagnostic_severities.get(&(
879 source,
880 diagnostic.code.clone(),
881 entry.range.clone(),
882 )) {
883 diagnostic.severity = severity;
884 }
885 }
886 }
887
888 for buffer in self.open_buffers.values() {
889 if let Some(buffer) = buffer.upgrade(cx) {
890 if buffer
891 .read(cx)
892 .file()
893 .map_or(false, |file| *file.path() == project_path.path)
894 {
895 buffer.update(cx, |buffer, cx| {
896 buffer.update_diagnostics(params.version, diagnostics.clone(), cx)
897 })?;
898 break;
899 }
900 }
901 }
902
903 worktree.update(cx, |worktree, cx| {
904 worktree
905 .as_local_mut()
906 .ok_or_else(|| anyhow!("not a local worktree"))?
907 .update_diagnostics(project_path.path.clone(), diagnostics, cx)
908 })?;
909 cx.emit(Event::DiagnosticsUpdated(project_path));
910 Ok(())
911 }
912
913 pub fn definition<T: ToOffset>(
914 &self,
915 source_buffer_handle: &ModelHandle<Buffer>,
916 position: T,
917 cx: &mut ModelContext<Self>,
918 ) -> Task<Result<Vec<Definition>>> {
919 let source_buffer_handle = source_buffer_handle.clone();
920 let buffer = source_buffer_handle.read(cx);
921 let worktree;
922 let buffer_abs_path;
923 if let Some(file) = File::from_dyn(buffer.file()) {
924 worktree = file.worktree.clone();
925 buffer_abs_path = file.abs_path();
926 } else {
927 return Task::ready(Err(anyhow!("buffer does not belong to any worktree")));
928 };
929
930 if worktree.read(cx).as_local().is_some() {
931 let point = buffer.offset_to_point_utf16(position.to_offset(buffer));
932 let buffer_abs_path = buffer_abs_path.unwrap();
933 let lang_name;
934 let lang_server;
935 if let Some(lang) = buffer.language() {
936 lang_name = lang.name().to_string();
937 if let Some(server) = self
938 .language_servers
939 .get(&(worktree.read(cx).id(), lang_name.clone()))
940 {
941 lang_server = server.clone();
942 } else {
943 return Task::ready(Err(anyhow!("buffer does not have a language server")));
944 };
945 } else {
946 return Task::ready(Err(anyhow!("buffer does not have a language")));
947 }
948
949 cx.spawn(|this, mut cx| async move {
950 let response = lang_server
951 .request::<lsp::request::GotoDefinition>(lsp::GotoDefinitionParams {
952 text_document_position_params: lsp::TextDocumentPositionParams {
953 text_document: lsp::TextDocumentIdentifier::new(
954 lsp::Url::from_file_path(&buffer_abs_path).unwrap(),
955 ),
956 position: lsp::Position::new(point.row, point.column),
957 },
958 work_done_progress_params: Default::default(),
959 partial_result_params: Default::default(),
960 })
961 .await?;
962
963 let mut definitions = Vec::new();
964 if let Some(response) = response {
965 let mut unresolved_locations = Vec::new();
966 match response {
967 lsp::GotoDefinitionResponse::Scalar(loc) => {
968 unresolved_locations.push((loc.uri, loc.range));
969 }
970 lsp::GotoDefinitionResponse::Array(locs) => {
971 unresolved_locations.extend(locs.into_iter().map(|l| (l.uri, l.range)));
972 }
973 lsp::GotoDefinitionResponse::Link(links) => {
974 unresolved_locations.extend(
975 links
976 .into_iter()
977 .map(|l| (l.target_uri, l.target_selection_range)),
978 );
979 }
980 }
981
982 for (target_uri, target_range) in unresolved_locations {
983 let abs_path = target_uri
984 .to_file_path()
985 .map_err(|_| anyhow!("invalid target path"))?;
986
987 let (worktree, relative_path) = if let Some(result) = this
988 .read_with(&cx, |this, cx| {
989 this.find_worktree_for_abs_path(&abs_path, cx)
990 }) {
991 result
992 } else {
993 let (worktree, relative_path) = this
994 .update(&mut cx, |this, cx| {
995 this.create_worktree_for_abs_path(&abs_path, true, cx)
996 })
997 .await?;
998 this.update(&mut cx, |this, cx| {
999 this.language_servers.insert(
1000 (worktree.read(cx).id(), lang_name.clone()),
1001 lang_server.clone(),
1002 );
1003 });
1004 (worktree, relative_path)
1005 };
1006
1007 let project_path = ProjectPath {
1008 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1009 path: relative_path.into(),
1010 };
1011 let target_buffer_handle = this
1012 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1013 .await?;
1014 cx.read(|cx| {
1015 let target_buffer = target_buffer_handle.read(cx);
1016 let target_start = target_buffer
1017 .clip_point_utf16(target_range.start.to_point_utf16(), Bias::Left);
1018 let target_end = target_buffer
1019 .clip_point_utf16(target_range.end.to_point_utf16(), Bias::Left);
1020 definitions.push(Definition {
1021 target_buffer: target_buffer_handle,
1022 target_range: target_buffer.anchor_after(target_start)
1023 ..target_buffer.anchor_before(target_end),
1024 });
1025 });
1026 }
1027 }
1028
1029 Ok(definitions)
1030 })
1031 } else {
1032 log::info!("go to definition is not yet implemented for guests");
1033 Task::ready(Ok(Default::default()))
1034 }
1035 }
1036
1037 pub fn find_or_create_worktree_for_abs_path(
1038 &self,
1039 abs_path: impl AsRef<Path>,
1040 weak: bool,
1041 cx: &mut ModelContext<Self>,
1042 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
1043 let abs_path = abs_path.as_ref();
1044 if let Some((tree, relative_path)) = self.find_worktree_for_abs_path(abs_path, cx) {
1045 Task::ready(Ok((tree.clone(), relative_path.into())))
1046 } else {
1047 self.create_worktree_for_abs_path(abs_path, weak, cx)
1048 }
1049 }
1050
1051 fn create_worktree_for_abs_path(
1052 &self,
1053 abs_path: &Path,
1054 weak: bool,
1055 cx: &mut ModelContext<Self>,
1056 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
1057 let worktree = self.add_local_worktree(abs_path, weak, cx);
1058 cx.background().spawn(async move {
1059 let worktree = worktree.await?;
1060 Ok((worktree, PathBuf::new()))
1061 })
1062 }
1063
1064 fn find_worktree_for_abs_path(
1065 &self,
1066 abs_path: &Path,
1067 cx: &AppContext,
1068 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
1069 for tree in self.worktrees(cx) {
1070 if let Some(relative_path) = tree
1071 .read(cx)
1072 .as_local()
1073 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
1074 {
1075 return Some((tree.clone(), relative_path.into()));
1076 }
1077 }
1078 None
1079 }
1080
1081 pub fn is_shared(&self) -> bool {
1082 match &self.client_state {
1083 ProjectClientState::Local { is_shared, .. } => *is_shared,
1084 ProjectClientState::Remote { .. } => false,
1085 }
1086 }
1087
1088 pub fn add_local_worktree(
1089 &self,
1090 abs_path: impl AsRef<Path>,
1091 weak: bool,
1092 cx: &mut ModelContext<Self>,
1093 ) -> Task<Result<ModelHandle<Worktree>>> {
1094 let fs = self.fs.clone();
1095 let client = self.client.clone();
1096 let path = Arc::from(abs_path.as_ref());
1097 cx.spawn(|project, mut cx| async move {
1098 let worktree = Worktree::local(client.clone(), path, weak, fs, &mut cx).await?;
1099
1100 let (remote_project_id, is_shared) = project.update(&mut cx, |project, cx| {
1101 project.add_worktree(&worktree, cx);
1102 (project.remote_id(), project.is_shared())
1103 });
1104
1105 if let Some(project_id) = remote_project_id {
1106 worktree
1107 .update(&mut cx, |worktree, cx| {
1108 worktree.as_local_mut().unwrap().register(project_id, cx)
1109 })
1110 .await?;
1111 if is_shared {
1112 worktree
1113 .update(&mut cx, |worktree, cx| {
1114 worktree.as_local_mut().unwrap().share(project_id, cx)
1115 })
1116 .await?;
1117 }
1118 }
1119
1120 Ok(worktree)
1121 })
1122 }
1123
1124 pub fn remove_worktree(&mut self, id: WorktreeId, cx: &mut ModelContext<Self>) {
1125 self.worktrees.retain(|worktree| {
1126 worktree
1127 .upgrade(cx)
1128 .map_or(false, |w| w.read(cx).id() != id)
1129 });
1130 cx.notify();
1131 }
1132
1133 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
1134 cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
1135 cx.subscribe(&worktree, |this, worktree, _, cx| {
1136 this.update_open_buffers(worktree, cx)
1137 })
1138 .detach();
1139
1140 let push_weak_handle = {
1141 let worktree = worktree.read(cx);
1142 worktree.is_local() && worktree.is_weak()
1143 };
1144 if push_weak_handle {
1145 cx.observe_release(&worktree, |this, cx| {
1146 this.worktrees
1147 .retain(|worktree| worktree.upgrade(cx).is_some());
1148 cx.notify();
1149 })
1150 .detach();
1151 self.worktrees
1152 .push(WorktreeHandle::Weak(worktree.downgrade()));
1153 } else {
1154 self.worktrees
1155 .push(WorktreeHandle::Strong(worktree.clone()));
1156 }
1157 cx.notify();
1158 }
1159
1160 fn update_open_buffers(
1161 &mut self,
1162 worktree_handle: ModelHandle<Worktree>,
1163 cx: &mut ModelContext<Self>,
1164 ) {
1165 let local = worktree_handle.read(cx).is_local();
1166 let snapshot = worktree_handle.read(cx).snapshot();
1167 let worktree_path = snapshot.abs_path();
1168 let mut buffers_to_delete = Vec::new();
1169 for (buffer_id, buffer) in &self.open_buffers {
1170 if let OpenBuffer::Loaded(buffer) = buffer {
1171 if let Some(buffer) = buffer.upgrade(cx) {
1172 buffer.update(cx, |buffer, cx| {
1173 if let Some(old_file) = File::from_dyn(buffer.file()) {
1174 if old_file.worktree != worktree_handle {
1175 return;
1176 }
1177
1178 let new_file = if let Some(entry) = old_file
1179 .entry_id
1180 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
1181 {
1182 File {
1183 is_local: local,
1184 worktree_path: worktree_path.clone(),
1185 entry_id: Some(entry.id),
1186 mtime: entry.mtime,
1187 path: entry.path.clone(),
1188 worktree: worktree_handle.clone(),
1189 }
1190 } else if let Some(entry) =
1191 snapshot.entry_for_path(old_file.path().as_ref())
1192 {
1193 File {
1194 is_local: local,
1195 worktree_path: worktree_path.clone(),
1196 entry_id: Some(entry.id),
1197 mtime: entry.mtime,
1198 path: entry.path.clone(),
1199 worktree: worktree_handle.clone(),
1200 }
1201 } else {
1202 File {
1203 is_local: local,
1204 worktree_path: worktree_path.clone(),
1205 entry_id: None,
1206 path: old_file.path().clone(),
1207 mtime: old_file.mtime(),
1208 worktree: worktree_handle.clone(),
1209 }
1210 };
1211
1212 if let Some(task) = buffer.file_updated(Box::new(new_file), cx) {
1213 task.detach();
1214 }
1215 }
1216 });
1217 } else {
1218 buffers_to_delete.push(*buffer_id);
1219 }
1220 }
1221 }
1222
1223 for buffer_id in buffers_to_delete {
1224 self.open_buffers.remove(&buffer_id);
1225 }
1226 }
1227
1228 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
1229 let new_active_entry = entry.and_then(|project_path| {
1230 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1231 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
1232 Some(ProjectEntry {
1233 worktree_id: project_path.worktree_id,
1234 entry_id: entry.id,
1235 })
1236 });
1237 if new_active_entry != self.active_entry {
1238 self.active_entry = new_active_entry;
1239 cx.emit(Event::ActiveEntryChanged(new_active_entry));
1240 }
1241 }
1242
1243 pub fn is_running_disk_based_diagnostics(&self) -> bool {
1244 self.language_servers_with_diagnostics_running > 0
1245 }
1246
1247 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
1248 let mut summary = DiagnosticSummary::default();
1249 for (_, path_summary) in self.diagnostic_summaries(cx) {
1250 summary.error_count += path_summary.error_count;
1251 summary.warning_count += path_summary.warning_count;
1252 summary.info_count += path_summary.info_count;
1253 summary.hint_count += path_summary.hint_count;
1254 }
1255 summary
1256 }
1257
1258 pub fn diagnostic_summaries<'a>(
1259 &'a self,
1260 cx: &'a AppContext,
1261 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
1262 self.worktrees(cx).flat_map(move |worktree| {
1263 let worktree = worktree.read(cx);
1264 let worktree_id = worktree.id();
1265 worktree
1266 .diagnostic_summaries()
1267 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
1268 })
1269 }
1270
1271 fn disk_based_diagnostics_started(&mut self, cx: &mut ModelContext<Self>) {
1272 self.language_servers_with_diagnostics_running += 1;
1273 if self.language_servers_with_diagnostics_running == 1 {
1274 cx.emit(Event::DiskBasedDiagnosticsStarted);
1275 }
1276 }
1277
1278 fn disk_based_diagnostics_finished(&mut self, cx: &mut ModelContext<Self>) {
1279 cx.emit(Event::DiskBasedDiagnosticsUpdated);
1280 self.language_servers_with_diagnostics_running -= 1;
1281 if self.language_servers_with_diagnostics_running == 0 {
1282 cx.emit(Event::DiskBasedDiagnosticsFinished);
1283 }
1284 }
1285
1286 pub fn active_entry(&self) -> Option<ProjectEntry> {
1287 self.active_entry
1288 }
1289
1290 // RPC message handlers
1291
1292 fn handle_unshare_project(
1293 &mut self,
1294 _: TypedEnvelope<proto::UnshareProject>,
1295 _: Arc<Client>,
1296 cx: &mut ModelContext<Self>,
1297 ) -> Result<()> {
1298 if let ProjectClientState::Remote {
1299 sharing_has_stopped,
1300 ..
1301 } = &mut self.client_state
1302 {
1303 *sharing_has_stopped = true;
1304 self.collaborators.clear();
1305 cx.notify();
1306 Ok(())
1307 } else {
1308 unreachable!()
1309 }
1310 }
1311
1312 fn handle_add_collaborator(
1313 &mut self,
1314 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
1315 _: Arc<Client>,
1316 cx: &mut ModelContext<Self>,
1317 ) -> Result<()> {
1318 let user_store = self.user_store.clone();
1319 let collaborator = envelope
1320 .payload
1321 .collaborator
1322 .take()
1323 .ok_or_else(|| anyhow!("empty collaborator"))?;
1324
1325 cx.spawn(|this, mut cx| {
1326 async move {
1327 let collaborator =
1328 Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
1329 this.update(&mut cx, |this, cx| {
1330 this.collaborators
1331 .insert(collaborator.peer_id, collaborator);
1332 cx.notify();
1333 });
1334 Ok(())
1335 }
1336 .log_err()
1337 })
1338 .detach();
1339
1340 Ok(())
1341 }
1342
1343 fn handle_remove_collaborator(
1344 &mut self,
1345 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
1346 _: Arc<Client>,
1347 cx: &mut ModelContext<Self>,
1348 ) -> Result<()> {
1349 let peer_id = PeerId(envelope.payload.peer_id);
1350 let replica_id = self
1351 .collaborators
1352 .remove(&peer_id)
1353 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
1354 .replica_id;
1355 self.shared_buffers.remove(&peer_id);
1356 for (_, buffer) in &self.open_buffers {
1357 if let OpenBuffer::Loaded(buffer) = buffer {
1358 if let Some(buffer) = buffer.upgrade(cx) {
1359 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
1360 }
1361 }
1362 }
1363 cx.notify();
1364 Ok(())
1365 }
1366
1367 fn handle_share_worktree(
1368 &mut self,
1369 envelope: TypedEnvelope<proto::ShareWorktree>,
1370 client: Arc<Client>,
1371 cx: &mut ModelContext<Self>,
1372 ) -> Result<()> {
1373 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
1374 let replica_id = self.replica_id();
1375 let worktree = envelope
1376 .payload
1377 .worktree
1378 .ok_or_else(|| anyhow!("invalid worktree"))?;
1379 cx.spawn(|this, mut cx| {
1380 async move {
1381 let worktree =
1382 Worktree::remote(remote_id, replica_id, worktree, client, &mut cx).await?;
1383 this.update(&mut cx, |this, cx| this.add_worktree(&worktree, cx));
1384 Ok(())
1385 }
1386 .log_err()
1387 })
1388 .detach();
1389 Ok(())
1390 }
1391
1392 fn handle_unregister_worktree(
1393 &mut self,
1394 envelope: TypedEnvelope<proto::UnregisterWorktree>,
1395 _: Arc<Client>,
1396 cx: &mut ModelContext<Self>,
1397 ) -> Result<()> {
1398 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1399 self.remove_worktree(worktree_id, cx);
1400 Ok(())
1401 }
1402
1403 fn handle_update_worktree(
1404 &mut self,
1405 envelope: TypedEnvelope<proto::UpdateWorktree>,
1406 _: Arc<Client>,
1407 cx: &mut ModelContext<Self>,
1408 ) -> Result<()> {
1409 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1410 if let Some(worktree) = self.worktree_for_id(worktree_id, cx) {
1411 worktree.update(cx, |worktree, cx| {
1412 let worktree = worktree.as_remote_mut().unwrap();
1413 worktree.update_from_remote(envelope, cx)
1414 })?;
1415 }
1416 Ok(())
1417 }
1418
1419 fn handle_update_diagnostic_summary(
1420 &mut self,
1421 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
1422 _: Arc<Client>,
1423 cx: &mut ModelContext<Self>,
1424 ) -> Result<()> {
1425 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1426 if let Some(worktree) = self.worktree_for_id(worktree_id, cx) {
1427 if let Some(summary) = envelope.payload.summary {
1428 let project_path = ProjectPath {
1429 worktree_id,
1430 path: Path::new(&summary.path).into(),
1431 };
1432 worktree.update(cx, |worktree, _| {
1433 worktree
1434 .as_remote_mut()
1435 .unwrap()
1436 .update_diagnostic_summary(project_path.path.clone(), &summary);
1437 });
1438 cx.emit(Event::DiagnosticsUpdated(project_path));
1439 }
1440 }
1441 Ok(())
1442 }
1443
1444 fn handle_disk_based_diagnostics_updating(
1445 &mut self,
1446 _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
1447 _: Arc<Client>,
1448 cx: &mut ModelContext<Self>,
1449 ) -> Result<()> {
1450 self.disk_based_diagnostics_started(cx);
1451 Ok(())
1452 }
1453
1454 fn handle_disk_based_diagnostics_updated(
1455 &mut self,
1456 _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
1457 _: Arc<Client>,
1458 cx: &mut ModelContext<Self>,
1459 ) -> Result<()> {
1460 self.disk_based_diagnostics_finished(cx);
1461 Ok(())
1462 }
1463
1464 pub fn handle_update_buffer(
1465 &mut self,
1466 envelope: TypedEnvelope<proto::UpdateBuffer>,
1467 _: Arc<Client>,
1468 cx: &mut ModelContext<Self>,
1469 ) -> Result<()> {
1470 let payload = envelope.payload.clone();
1471 let buffer_id = payload.buffer_id as usize;
1472 let ops = payload
1473 .operations
1474 .into_iter()
1475 .map(|op| language::proto::deserialize_operation(op))
1476 .collect::<Result<Vec<_>, _>>()?;
1477 match self.open_buffers.get_mut(&buffer_id) {
1478 Some(OpenBuffer::Operations(pending_ops)) => pending_ops.extend(ops),
1479 Some(OpenBuffer::Loaded(buffer)) => {
1480 if let Some(buffer) = buffer.upgrade(cx) {
1481 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
1482 } else {
1483 self.open_buffers
1484 .insert(buffer_id, OpenBuffer::Operations(ops));
1485 }
1486 }
1487 None => {
1488 self.open_buffers
1489 .insert(buffer_id, OpenBuffer::Operations(ops));
1490 }
1491 }
1492 Ok(())
1493 }
1494
1495 pub fn handle_save_buffer(
1496 &mut self,
1497 envelope: TypedEnvelope<proto::SaveBuffer>,
1498 rpc: Arc<Client>,
1499 cx: &mut ModelContext<Self>,
1500 ) -> Result<()> {
1501 let sender_id = envelope.original_sender_id()?;
1502 let project_id = self.remote_id().ok_or_else(|| anyhow!("not connected"))?;
1503 let buffer = self
1504 .shared_buffers
1505 .get(&sender_id)
1506 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
1507 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
1508 let receipt = envelope.receipt();
1509 let buffer_id = envelope.payload.buffer_id;
1510 let save = cx.spawn(|_, mut cx| async move {
1511 buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await
1512 });
1513
1514 cx.background()
1515 .spawn(
1516 async move {
1517 let (version, mtime) = save.await?;
1518
1519 rpc.respond(
1520 receipt,
1521 proto::BufferSaved {
1522 project_id,
1523 buffer_id,
1524 version: (&version).into(),
1525 mtime: Some(mtime.into()),
1526 },
1527 )
1528 .await?;
1529
1530 Ok(())
1531 }
1532 .log_err(),
1533 )
1534 .detach();
1535 Ok(())
1536 }
1537
1538 pub fn handle_format_buffer(
1539 &mut self,
1540 envelope: TypedEnvelope<proto::FormatBuffer>,
1541 rpc: Arc<Client>,
1542 cx: &mut ModelContext<Self>,
1543 ) -> Result<()> {
1544 let receipt = envelope.receipt();
1545 let sender_id = envelope.original_sender_id()?;
1546 let buffer = self
1547 .shared_buffers
1548 .get(&sender_id)
1549 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
1550 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
1551 cx.spawn(|_, mut cx| async move {
1552 let format = buffer.update(&mut cx, |buffer, cx| buffer.format(cx)).await;
1553 // We spawn here in order to enqueue the sending of `Ack` *after* transmission of edits
1554 // associated with formatting.
1555 cx.spawn(|_| async move {
1556 match format {
1557 Ok(()) => rpc.respond(receipt, proto::Ack {}).await?,
1558 Err(error) => {
1559 rpc.respond_with_error(
1560 receipt,
1561 proto::Error {
1562 message: error.to_string(),
1563 },
1564 )
1565 .await?
1566 }
1567 }
1568 Ok::<_, anyhow::Error>(())
1569 })
1570 .await
1571 .log_err();
1572 })
1573 .detach();
1574 Ok(())
1575 }
1576
1577 pub fn handle_open_buffer(
1578 &mut self,
1579 envelope: TypedEnvelope<proto::OpenBuffer>,
1580 rpc: Arc<Client>,
1581 cx: &mut ModelContext<Self>,
1582 ) -> anyhow::Result<()> {
1583 let receipt = envelope.receipt();
1584 let peer_id = envelope.original_sender_id()?;
1585 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1586 let open_buffer = self.open_buffer(
1587 ProjectPath {
1588 worktree_id,
1589 path: PathBuf::from(envelope.payload.path).into(),
1590 },
1591 cx,
1592 );
1593 cx.spawn(|this, mut cx| {
1594 async move {
1595 let buffer = open_buffer.await?;
1596 this.update(&mut cx, |this, _| {
1597 this.shared_buffers
1598 .entry(peer_id)
1599 .or_default()
1600 .insert(buffer.id() as u64, buffer.clone());
1601 });
1602 let message = buffer.read_with(&cx, |buffer, _| buffer.to_proto());
1603 rpc.respond(
1604 receipt,
1605 proto::OpenBufferResponse {
1606 buffer: Some(message),
1607 },
1608 )
1609 .await
1610 }
1611 .log_err()
1612 })
1613 .detach();
1614 Ok(())
1615 }
1616
1617 pub fn handle_close_buffer(
1618 &mut self,
1619 envelope: TypedEnvelope<proto::CloseBuffer>,
1620 _: Arc<Client>,
1621 cx: &mut ModelContext<Self>,
1622 ) -> anyhow::Result<()> {
1623 if let Some(shared_buffers) = self.shared_buffers.get_mut(&envelope.original_sender_id()?) {
1624 shared_buffers.remove(&envelope.payload.buffer_id);
1625 cx.notify();
1626 }
1627 Ok(())
1628 }
1629
1630 pub fn handle_buffer_saved(
1631 &mut self,
1632 envelope: TypedEnvelope<proto::BufferSaved>,
1633 _: Arc<Client>,
1634 cx: &mut ModelContext<Self>,
1635 ) -> Result<()> {
1636 let payload = envelope.payload.clone();
1637 let buffer = self
1638 .open_buffers
1639 .get(&(payload.buffer_id as usize))
1640 .and_then(|buf| {
1641 if let OpenBuffer::Loaded(buffer) = buf {
1642 buffer.upgrade(cx)
1643 } else {
1644 None
1645 }
1646 });
1647 if let Some(buffer) = buffer {
1648 buffer.update(cx, |buffer, cx| {
1649 let version = payload.version.try_into()?;
1650 let mtime = payload
1651 .mtime
1652 .ok_or_else(|| anyhow!("missing mtime"))?
1653 .into();
1654 buffer.did_save(version, mtime, None, cx);
1655 Result::<_, anyhow::Error>::Ok(())
1656 })?;
1657 }
1658 Ok(())
1659 }
1660
1661 pub fn match_paths<'a>(
1662 &self,
1663 query: &'a str,
1664 include_ignored: bool,
1665 smart_case: bool,
1666 max_results: usize,
1667 cancel_flag: &'a AtomicBool,
1668 cx: &AppContext,
1669 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
1670 let worktrees = self
1671 .worktrees(cx)
1672 .filter(|worktree| !worktree.read(cx).is_weak())
1673 .collect::<Vec<_>>();
1674 let include_root_name = worktrees.len() > 1;
1675 let candidate_sets = worktrees
1676 .into_iter()
1677 .map(|worktree| CandidateSet {
1678 snapshot: worktree.read(cx).snapshot(),
1679 include_ignored,
1680 include_root_name,
1681 })
1682 .collect::<Vec<_>>();
1683
1684 let background = cx.background().clone();
1685 async move {
1686 fuzzy::match_paths(
1687 candidate_sets.as_slice(),
1688 query,
1689 smart_case,
1690 max_results,
1691 cancel_flag,
1692 background,
1693 )
1694 .await
1695 }
1696 }
1697}
1698
1699impl WorktreeHandle {
1700 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
1701 match self {
1702 WorktreeHandle::Strong(handle) => Some(handle.clone()),
1703 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
1704 }
1705 }
1706}
1707
1708struct CandidateSet {
1709 snapshot: Snapshot,
1710 include_ignored: bool,
1711 include_root_name: bool,
1712}
1713
1714impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
1715 type Candidates = CandidateSetIter<'a>;
1716
1717 fn id(&self) -> usize {
1718 self.snapshot.id().to_usize()
1719 }
1720
1721 fn len(&self) -> usize {
1722 if self.include_ignored {
1723 self.snapshot.file_count()
1724 } else {
1725 self.snapshot.visible_file_count()
1726 }
1727 }
1728
1729 fn prefix(&self) -> Arc<str> {
1730 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
1731 self.snapshot.root_name().into()
1732 } else if self.include_root_name {
1733 format!("{}/", self.snapshot.root_name()).into()
1734 } else {
1735 "".into()
1736 }
1737 }
1738
1739 fn candidates(&'a self, start: usize) -> Self::Candidates {
1740 CandidateSetIter {
1741 traversal: self.snapshot.files(self.include_ignored, start),
1742 }
1743 }
1744}
1745
1746struct CandidateSetIter<'a> {
1747 traversal: Traversal<'a>,
1748}
1749
1750impl<'a> Iterator for CandidateSetIter<'a> {
1751 type Item = PathMatchCandidate<'a>;
1752
1753 fn next(&mut self) -> Option<Self::Item> {
1754 self.traversal.next().map(|entry| {
1755 if let EntryKind::File(char_bag) = entry.kind {
1756 PathMatchCandidate {
1757 path: &entry.path,
1758 char_bag,
1759 }
1760 } else {
1761 unreachable!()
1762 }
1763 })
1764 }
1765}
1766
1767impl Entity for Project {
1768 type Event = Event;
1769
1770 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
1771 match &self.client_state {
1772 ProjectClientState::Local { remote_id_rx, .. } => {
1773 if let Some(project_id) = *remote_id_rx.borrow() {
1774 let rpc = self.client.clone();
1775 cx.spawn(|_| async move {
1776 if let Err(err) = rpc.send(proto::UnregisterProject { project_id }).await {
1777 log::error!("error unregistering project: {}", err);
1778 }
1779 })
1780 .detach();
1781 }
1782 }
1783 ProjectClientState::Remote { remote_id, .. } => {
1784 let rpc = self.client.clone();
1785 let project_id = *remote_id;
1786 cx.spawn(|_| async move {
1787 if let Err(err) = rpc.send(proto::LeaveProject { project_id }).await {
1788 log::error!("error leaving project: {}", err);
1789 }
1790 })
1791 .detach();
1792 }
1793 }
1794 }
1795
1796 fn app_will_quit(
1797 &mut self,
1798 _: &mut MutableAppContext,
1799 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
1800 use futures::FutureExt;
1801
1802 let shutdown_futures = self
1803 .language_servers
1804 .drain()
1805 .filter_map(|(_, server)| server.shutdown())
1806 .collect::<Vec<_>>();
1807 Some(
1808 async move {
1809 futures::future::join_all(shutdown_futures).await;
1810 }
1811 .boxed(),
1812 )
1813 }
1814}
1815
1816impl Collaborator {
1817 fn from_proto(
1818 message: proto::Collaborator,
1819 user_store: &ModelHandle<UserStore>,
1820 cx: &mut AsyncAppContext,
1821 ) -> impl Future<Output = Result<Self>> {
1822 let user = user_store.update(cx, |user_store, cx| {
1823 user_store.fetch_user(message.user_id, cx)
1824 });
1825
1826 async move {
1827 Ok(Self {
1828 peer_id: PeerId(message.peer_id),
1829 user: user.await?,
1830 replica_id: message.replica_id as ReplicaId,
1831 })
1832 }
1833 }
1834}
1835
1836impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
1837 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
1838 Self {
1839 worktree_id,
1840 path: path.as_ref().into(),
1841 }
1842 }
1843}
1844
1845impl OpenBuffer {
1846 fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
1847 match self {
1848 OpenBuffer::Loaded(buffer) => buffer.upgrade(cx),
1849 OpenBuffer::Operations(_) => None,
1850 }
1851 }
1852}
1853
1854#[cfg(test)]
1855mod tests {
1856 use super::{Event, *};
1857 use client::test::FakeHttpClient;
1858 use fs::RealFs;
1859 use futures::StreamExt;
1860 use gpui::{test::subscribe, TestAppContext};
1861 use language::{
1862 tree_sitter_rust, AnchorRangeExt, Diagnostic, LanguageConfig, LanguageRegistry,
1863 LanguageServerConfig, Point,
1864 };
1865 use lsp::Url;
1866 use serde_json::json;
1867 use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
1868 use unindent::Unindent as _;
1869 use util::test::temp_tree;
1870 use worktree::WorktreeHandle as _;
1871
1872 #[gpui::test]
1873 async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
1874 let dir = temp_tree(json!({
1875 "root": {
1876 "apple": "",
1877 "banana": {
1878 "carrot": {
1879 "date": "",
1880 "endive": "",
1881 }
1882 },
1883 "fennel": {
1884 "grape": "",
1885 }
1886 }
1887 }));
1888
1889 let root_link_path = dir.path().join("root_link");
1890 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
1891 unix::fs::symlink(
1892 &dir.path().join("root/fennel"),
1893 &dir.path().join("root/finnochio"),
1894 )
1895 .unwrap();
1896
1897 let project = build_project(Arc::new(RealFs), &mut cx);
1898
1899 let (tree, _) = project
1900 .update(&mut cx, |project, cx| {
1901 project.find_or_create_worktree_for_abs_path(&root_link_path, false, cx)
1902 })
1903 .await
1904 .unwrap();
1905
1906 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1907 .await;
1908 cx.read(|cx| {
1909 let tree = tree.read(cx);
1910 assert_eq!(tree.file_count(), 5);
1911 assert_eq!(
1912 tree.inode_for_path("fennel/grape"),
1913 tree.inode_for_path("finnochio/grape")
1914 );
1915 });
1916
1917 let cancel_flag = Default::default();
1918 let results = project
1919 .read_with(&cx, |project, cx| {
1920 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
1921 })
1922 .await;
1923 assert_eq!(
1924 results
1925 .into_iter()
1926 .map(|result| result.path)
1927 .collect::<Vec<Arc<Path>>>(),
1928 vec![
1929 PathBuf::from("banana/carrot/date").into(),
1930 PathBuf::from("banana/carrot/endive").into(),
1931 ]
1932 );
1933 }
1934
1935 #[gpui::test]
1936 async fn test_language_server_diagnostics(mut cx: gpui::TestAppContext) {
1937 let (language_server_config, mut fake_server) =
1938 LanguageServerConfig::fake(cx.background()).await;
1939 let progress_token = language_server_config
1940 .disk_based_diagnostics_progress_token
1941 .clone()
1942 .unwrap();
1943
1944 let mut languages = LanguageRegistry::new();
1945 languages.add(Arc::new(Language::new(
1946 LanguageConfig {
1947 name: "Rust".to_string(),
1948 path_suffixes: vec!["rs".to_string()],
1949 language_server: Some(language_server_config),
1950 ..Default::default()
1951 },
1952 Some(tree_sitter_rust::language()),
1953 )));
1954
1955 let dir = temp_tree(json!({
1956 "a.rs": "fn a() { A }",
1957 "b.rs": "const y: i32 = 1",
1958 }));
1959
1960 let http_client = FakeHttpClient::with_404_response();
1961 let client = Client::new(http_client.clone());
1962 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
1963
1964 let project = cx.update(|cx| {
1965 Project::local(
1966 client,
1967 user_store,
1968 Arc::new(languages),
1969 Arc::new(RealFs),
1970 cx,
1971 )
1972 });
1973
1974 let (tree, _) = project
1975 .update(&mut cx, |project, cx| {
1976 project.find_or_create_worktree_for_abs_path(dir.path(), false, cx)
1977 })
1978 .await
1979 .unwrap();
1980 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
1981
1982 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
1983 .await;
1984
1985 // Cause worktree to start the fake language server
1986 let _buffer = project
1987 .update(&mut cx, |project, cx| {
1988 project.open_buffer(
1989 ProjectPath {
1990 worktree_id,
1991 path: Path::new("b.rs").into(),
1992 },
1993 cx,
1994 )
1995 })
1996 .await
1997 .unwrap();
1998
1999 let mut events = subscribe(&project, &mut cx);
2000
2001 fake_server.start_progress(&progress_token).await;
2002 assert_eq!(
2003 events.next().await.unwrap(),
2004 Event::DiskBasedDiagnosticsStarted
2005 );
2006
2007 fake_server.start_progress(&progress_token).await;
2008 fake_server.end_progress(&progress_token).await;
2009 fake_server.start_progress(&progress_token).await;
2010
2011 fake_server
2012 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
2013 uri: Url::from_file_path(dir.path().join("a.rs")).unwrap(),
2014 version: None,
2015 diagnostics: vec![lsp::Diagnostic {
2016 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
2017 severity: Some(lsp::DiagnosticSeverity::ERROR),
2018 message: "undefined variable 'A'".to_string(),
2019 ..Default::default()
2020 }],
2021 })
2022 .await;
2023 assert_eq!(
2024 events.next().await.unwrap(),
2025 Event::DiagnosticsUpdated(ProjectPath {
2026 worktree_id,
2027 path: Arc::from(Path::new("a.rs"))
2028 })
2029 );
2030
2031 fake_server.end_progress(&progress_token).await;
2032 fake_server.end_progress(&progress_token).await;
2033 assert_eq!(
2034 events.next().await.unwrap(),
2035 Event::DiskBasedDiagnosticsUpdated
2036 );
2037 assert_eq!(
2038 events.next().await.unwrap(),
2039 Event::DiskBasedDiagnosticsFinished
2040 );
2041
2042 let buffer = project
2043 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
2044 .await
2045 .unwrap();
2046
2047 buffer.read_with(&cx, |buffer, _| {
2048 let snapshot = buffer.snapshot();
2049 let diagnostics = snapshot
2050 .diagnostics_in_range::<_, Point>(0..buffer.len())
2051 .collect::<Vec<_>>();
2052 assert_eq!(
2053 diagnostics,
2054 &[DiagnosticEntry {
2055 range: Point::new(0, 9)..Point::new(0, 10),
2056 diagnostic: Diagnostic {
2057 severity: lsp::DiagnosticSeverity::ERROR,
2058 message: "undefined variable 'A'".to_string(),
2059 group_id: 0,
2060 is_primary: true,
2061 ..Default::default()
2062 }
2063 }]
2064 )
2065 });
2066 }
2067
2068 #[gpui::test]
2069 async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
2070 let dir = temp_tree(json!({
2071 "root": {
2072 "dir1": {},
2073 "dir2": {
2074 "dir3": {}
2075 }
2076 }
2077 }));
2078
2079 let project = build_project(Arc::new(RealFs), &mut cx);
2080 let (tree, _) = project
2081 .update(&mut cx, |project, cx| {
2082 project.find_or_create_worktree_for_abs_path(&dir.path(), false, cx)
2083 })
2084 .await
2085 .unwrap();
2086
2087 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2088 .await;
2089
2090 let cancel_flag = Default::default();
2091 let results = project
2092 .read_with(&cx, |project, cx| {
2093 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
2094 })
2095 .await;
2096
2097 assert!(results.is_empty());
2098 }
2099
2100 #[gpui::test]
2101 async fn test_definition(mut cx: gpui::TestAppContext) {
2102 let (language_server_config, mut fake_server) =
2103 LanguageServerConfig::fake(cx.background()).await;
2104
2105 let mut languages = LanguageRegistry::new();
2106 languages.add(Arc::new(Language::new(
2107 LanguageConfig {
2108 name: "Rust".to_string(),
2109 path_suffixes: vec!["rs".to_string()],
2110 language_server: Some(language_server_config),
2111 ..Default::default()
2112 },
2113 Some(tree_sitter_rust::language()),
2114 )));
2115
2116 let dir = temp_tree(json!({
2117 "a.rs": "const fn a() { A }",
2118 "b.rs": "const y: i32 = crate::a()",
2119 }));
2120
2121 let http_client = FakeHttpClient::with_404_response();
2122 let client = Client::new(http_client.clone());
2123 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
2124 let project = cx.update(|cx| {
2125 Project::local(
2126 client,
2127 user_store,
2128 Arc::new(languages),
2129 Arc::new(RealFs),
2130 cx,
2131 )
2132 });
2133
2134 let (tree, _) = project
2135 .update(&mut cx, |project, cx| {
2136 project.find_or_create_worktree_for_abs_path(dir.path().join("b.rs"), false, cx)
2137 })
2138 .await
2139 .unwrap();
2140 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
2141 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2142 .await;
2143
2144 // Cause worktree to start the fake language server
2145 let buffer = project
2146 .update(&mut cx, |project, cx| {
2147 project.open_buffer(
2148 ProjectPath {
2149 worktree_id,
2150 path: Path::new("").into(),
2151 },
2152 cx,
2153 )
2154 })
2155 .await
2156 .unwrap();
2157 let definitions =
2158 project.update(&mut cx, |project, cx| project.definition(&buffer, 22, cx));
2159 let (request_id, request) = fake_server
2160 .receive_request::<lsp::request::GotoDefinition>()
2161 .await;
2162 let request_params = request.text_document_position_params;
2163 assert_eq!(
2164 request_params.text_document.uri.to_file_path().unwrap(),
2165 dir.path().join("b.rs")
2166 );
2167 assert_eq!(request_params.position, lsp::Position::new(0, 22));
2168
2169 fake_server
2170 .respond(
2171 request_id,
2172 Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
2173 lsp::Url::from_file_path(dir.path().join("a.rs")).unwrap(),
2174 lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
2175 ))),
2176 )
2177 .await;
2178 let mut definitions = definitions.await.unwrap();
2179 assert_eq!(definitions.len(), 1);
2180 let definition = definitions.pop().unwrap();
2181 cx.update(|cx| {
2182 let target_buffer = definition.target_buffer.read(cx);
2183 assert_eq!(
2184 target_buffer.file().unwrap().abs_path(),
2185 Some(dir.path().join("a.rs"))
2186 );
2187 assert_eq!(definition.target_range.to_offset(target_buffer), 9..10);
2188 assert_eq!(
2189 list_worktrees(&project, cx),
2190 [
2191 (dir.path().join("b.rs"), false),
2192 (dir.path().join("a.rs"), true)
2193 ]
2194 );
2195
2196 drop(definition);
2197 });
2198 cx.read(|cx| {
2199 assert_eq!(
2200 list_worktrees(&project, cx),
2201 [(dir.path().join("b.rs"), false)]
2202 );
2203 });
2204
2205 fn list_worktrees(project: &ModelHandle<Project>, cx: &AppContext) -> Vec<(PathBuf, bool)> {
2206 project
2207 .read(cx)
2208 .worktrees(cx)
2209 .map(|worktree| {
2210 let worktree = worktree.read(cx);
2211 (
2212 worktree.as_local().unwrap().abs_path().to_path_buf(),
2213 worktree.is_weak(),
2214 )
2215 })
2216 .collect::<Vec<_>>()
2217 }
2218 }
2219
2220 #[gpui::test]
2221 async fn test_save_file(mut cx: gpui::TestAppContext) {
2222 let fs = Arc::new(FakeFs::new());
2223 fs.insert_tree(
2224 "/dir",
2225 json!({
2226 "file1": "the old contents",
2227 }),
2228 )
2229 .await;
2230
2231 let project = build_project(fs.clone(), &mut cx);
2232 let worktree_id = project
2233 .update(&mut cx, |p, cx| p.add_local_worktree("/dir", false, cx))
2234 .await
2235 .unwrap()
2236 .read_with(&cx, |tree, _| tree.id());
2237
2238 let buffer = project
2239 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
2240 .await
2241 .unwrap();
2242 buffer
2243 .update(&mut cx, |buffer, cx| {
2244 assert_eq!(buffer.text(), "the old contents");
2245 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
2246 buffer.save(cx)
2247 })
2248 .await
2249 .unwrap();
2250
2251 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
2252 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
2253 }
2254
2255 #[gpui::test]
2256 async fn test_save_in_single_file_worktree(mut cx: gpui::TestAppContext) {
2257 let fs = Arc::new(FakeFs::new());
2258 fs.insert_tree(
2259 "/dir",
2260 json!({
2261 "file1": "the old contents",
2262 }),
2263 )
2264 .await;
2265
2266 let project = build_project(fs.clone(), &mut cx);
2267 let worktree_id = project
2268 .update(&mut cx, |p, cx| {
2269 p.add_local_worktree("/dir/file1", false, cx)
2270 })
2271 .await
2272 .unwrap()
2273 .read_with(&cx, |tree, _| tree.id());
2274
2275 let buffer = project
2276 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
2277 .await
2278 .unwrap();
2279 buffer
2280 .update(&mut cx, |buffer, cx| {
2281 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
2282 buffer.save(cx)
2283 })
2284 .await
2285 .unwrap();
2286
2287 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
2288 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
2289 }
2290
2291 #[gpui::test]
2292 async fn test_rescan_and_remote_updates(mut cx: gpui::TestAppContext) {
2293 let dir = temp_tree(json!({
2294 "a": {
2295 "file1": "",
2296 "file2": "",
2297 "file3": "",
2298 },
2299 "b": {
2300 "c": {
2301 "file4": "",
2302 "file5": "",
2303 }
2304 }
2305 }));
2306
2307 let project = build_project(Arc::new(RealFs), &mut cx);
2308 let rpc = project.read_with(&cx, |p, _| p.client.clone());
2309
2310 let tree = project
2311 .update(&mut cx, |p, cx| p.add_local_worktree(dir.path(), false, cx))
2312 .await
2313 .unwrap();
2314 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
2315
2316 let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
2317 let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
2318 async move { buffer.await.unwrap() }
2319 };
2320 let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
2321 tree.read_with(cx, |tree, _| {
2322 tree.entry_for_path(path)
2323 .expect(&format!("no entry for path {}", path))
2324 .id
2325 })
2326 };
2327
2328 let buffer2 = buffer_for_path("a/file2", &mut cx).await;
2329 let buffer3 = buffer_for_path("a/file3", &mut cx).await;
2330 let buffer4 = buffer_for_path("b/c/file4", &mut cx).await;
2331 let buffer5 = buffer_for_path("b/c/file5", &mut cx).await;
2332
2333 let file2_id = id_for_path("a/file2", &cx);
2334 let file3_id = id_for_path("a/file3", &cx);
2335 let file4_id = id_for_path("b/c/file4", &cx);
2336
2337 // Wait for the initial scan.
2338 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2339 .await;
2340
2341 // Create a remote copy of this worktree.
2342 let initial_snapshot = tree.read_with(&cx, |tree, _| tree.snapshot());
2343 let remote = Worktree::remote(
2344 1,
2345 1,
2346 initial_snapshot.to_proto(&Default::default(), Default::default()),
2347 rpc.clone(),
2348 &mut cx.to_async(),
2349 )
2350 .await
2351 .unwrap();
2352
2353 cx.read(|cx| {
2354 assert!(!buffer2.read(cx).is_dirty());
2355 assert!(!buffer3.read(cx).is_dirty());
2356 assert!(!buffer4.read(cx).is_dirty());
2357 assert!(!buffer5.read(cx).is_dirty());
2358 });
2359
2360 // Rename and delete files and directories.
2361 tree.flush_fs_events(&cx).await;
2362 std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
2363 std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
2364 std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
2365 std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
2366 tree.flush_fs_events(&cx).await;
2367
2368 let expected_paths = vec![
2369 "a",
2370 "a/file1",
2371 "a/file2.new",
2372 "b",
2373 "d",
2374 "d/file3",
2375 "d/file4",
2376 ];
2377
2378 cx.read(|app| {
2379 assert_eq!(
2380 tree.read(app)
2381 .paths()
2382 .map(|p| p.to_str().unwrap())
2383 .collect::<Vec<_>>(),
2384 expected_paths
2385 );
2386
2387 assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
2388 assert_eq!(id_for_path("d/file3", &cx), file3_id);
2389 assert_eq!(id_for_path("d/file4", &cx), file4_id);
2390
2391 assert_eq!(
2392 buffer2.read(app).file().unwrap().path().as_ref(),
2393 Path::new("a/file2.new")
2394 );
2395 assert_eq!(
2396 buffer3.read(app).file().unwrap().path().as_ref(),
2397 Path::new("d/file3")
2398 );
2399 assert_eq!(
2400 buffer4.read(app).file().unwrap().path().as_ref(),
2401 Path::new("d/file4")
2402 );
2403 assert_eq!(
2404 buffer5.read(app).file().unwrap().path().as_ref(),
2405 Path::new("b/c/file5")
2406 );
2407
2408 assert!(!buffer2.read(app).file().unwrap().is_deleted());
2409 assert!(!buffer3.read(app).file().unwrap().is_deleted());
2410 assert!(!buffer4.read(app).file().unwrap().is_deleted());
2411 assert!(buffer5.read(app).file().unwrap().is_deleted());
2412 });
2413
2414 // Update the remote worktree. Check that it becomes consistent with the
2415 // local worktree.
2416 remote.update(&mut cx, |remote, cx| {
2417 let update_message =
2418 tree.read(cx)
2419 .snapshot()
2420 .build_update(&initial_snapshot, 1, 1, true);
2421 remote
2422 .as_remote_mut()
2423 .unwrap()
2424 .snapshot
2425 .apply_update(update_message)
2426 .unwrap();
2427
2428 assert_eq!(
2429 remote
2430 .paths()
2431 .map(|p| p.to_str().unwrap())
2432 .collect::<Vec<_>>(),
2433 expected_paths
2434 );
2435 });
2436 }
2437
2438 #[gpui::test]
2439 async fn test_buffer_deduping(mut cx: gpui::TestAppContext) {
2440 let fs = Arc::new(FakeFs::new());
2441 fs.insert_tree(
2442 "/the-dir",
2443 json!({
2444 "a.txt": "a-contents",
2445 "b.txt": "b-contents",
2446 }),
2447 )
2448 .await;
2449
2450 let project = build_project(fs.clone(), &mut cx);
2451 let worktree_id = project
2452 .update(&mut cx, |p, cx| p.add_local_worktree("/the-dir", false, cx))
2453 .await
2454 .unwrap()
2455 .read_with(&cx, |tree, _| tree.id());
2456
2457 // Spawn multiple tasks to open paths, repeating some paths.
2458 let (buffer_a_1, buffer_b, buffer_a_2) = project.update(&mut cx, |p, cx| {
2459 (
2460 p.open_buffer((worktree_id, "a.txt"), cx),
2461 p.open_buffer((worktree_id, "b.txt"), cx),
2462 p.open_buffer((worktree_id, "a.txt"), cx),
2463 )
2464 });
2465
2466 let buffer_a_1 = buffer_a_1.await.unwrap();
2467 let buffer_a_2 = buffer_a_2.await.unwrap();
2468 let buffer_b = buffer_b.await.unwrap();
2469 assert_eq!(buffer_a_1.read_with(&cx, |b, _| b.text()), "a-contents");
2470 assert_eq!(buffer_b.read_with(&cx, |b, _| b.text()), "b-contents");
2471
2472 // There is only one buffer per path.
2473 let buffer_a_id = buffer_a_1.id();
2474 assert_eq!(buffer_a_2.id(), buffer_a_id);
2475
2476 // Open the same path again while it is still open.
2477 drop(buffer_a_1);
2478 let buffer_a_3 = project
2479 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
2480 .await
2481 .unwrap();
2482
2483 // There's still only one buffer per path.
2484 assert_eq!(buffer_a_3.id(), buffer_a_id);
2485 }
2486
2487 #[gpui::test]
2488 async fn test_buffer_is_dirty(mut cx: gpui::TestAppContext) {
2489 use std::fs;
2490
2491 let dir = temp_tree(json!({
2492 "file1": "abc",
2493 "file2": "def",
2494 "file3": "ghi",
2495 }));
2496
2497 let project = build_project(Arc::new(RealFs), &mut cx);
2498 let worktree = project
2499 .update(&mut cx, |p, cx| p.add_local_worktree(dir.path(), false, cx))
2500 .await
2501 .unwrap();
2502 let worktree_id = worktree.read_with(&cx, |worktree, _| worktree.id());
2503
2504 worktree.flush_fs_events(&cx).await;
2505 worktree
2506 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
2507 .await;
2508
2509 let buffer1 = project
2510 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
2511 .await
2512 .unwrap();
2513 let events = Rc::new(RefCell::new(Vec::new()));
2514
2515 // initially, the buffer isn't dirty.
2516 buffer1.update(&mut cx, |buffer, cx| {
2517 cx.subscribe(&buffer1, {
2518 let events = events.clone();
2519 move |_, _, event, _| events.borrow_mut().push(event.clone())
2520 })
2521 .detach();
2522
2523 assert!(!buffer.is_dirty());
2524 assert!(events.borrow().is_empty());
2525
2526 buffer.edit(vec![1..2], "", cx);
2527 });
2528
2529 // after the first edit, the buffer is dirty, and emits a dirtied event.
2530 buffer1.update(&mut cx, |buffer, cx| {
2531 assert!(buffer.text() == "ac");
2532 assert!(buffer.is_dirty());
2533 assert_eq!(
2534 *events.borrow(),
2535 &[language::Event::Edited, language::Event::Dirtied]
2536 );
2537 events.borrow_mut().clear();
2538 buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
2539 });
2540
2541 // after saving, the buffer is not dirty, and emits a saved event.
2542 buffer1.update(&mut cx, |buffer, cx| {
2543 assert!(!buffer.is_dirty());
2544 assert_eq!(*events.borrow(), &[language::Event::Saved]);
2545 events.borrow_mut().clear();
2546
2547 buffer.edit(vec![1..1], "B", cx);
2548 buffer.edit(vec![2..2], "D", cx);
2549 });
2550
2551 // after editing again, the buffer is dirty, and emits another dirty event.
2552 buffer1.update(&mut cx, |buffer, cx| {
2553 assert!(buffer.text() == "aBDc");
2554 assert!(buffer.is_dirty());
2555 assert_eq!(
2556 *events.borrow(),
2557 &[
2558 language::Event::Edited,
2559 language::Event::Dirtied,
2560 language::Event::Edited,
2561 ],
2562 );
2563 events.borrow_mut().clear();
2564
2565 // TODO - currently, after restoring the buffer to its
2566 // previously-saved state, the is still considered dirty.
2567 buffer.edit([1..3], "", cx);
2568 assert!(buffer.text() == "ac");
2569 assert!(buffer.is_dirty());
2570 });
2571
2572 assert_eq!(*events.borrow(), &[language::Event::Edited]);
2573
2574 // When a file is deleted, the buffer is considered dirty.
2575 let events = Rc::new(RefCell::new(Vec::new()));
2576 let buffer2 = project
2577 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
2578 .await
2579 .unwrap();
2580 buffer2.update(&mut cx, |_, cx| {
2581 cx.subscribe(&buffer2, {
2582 let events = events.clone();
2583 move |_, _, event, _| events.borrow_mut().push(event.clone())
2584 })
2585 .detach();
2586 });
2587
2588 fs::remove_file(dir.path().join("file2")).unwrap();
2589 buffer2.condition(&cx, |b, _| b.is_dirty()).await;
2590 assert_eq!(
2591 *events.borrow(),
2592 &[language::Event::Dirtied, language::Event::FileHandleChanged]
2593 );
2594
2595 // When a file is already dirty when deleted, we don't emit a Dirtied event.
2596 let events = Rc::new(RefCell::new(Vec::new()));
2597 let buffer3 = project
2598 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
2599 .await
2600 .unwrap();
2601 buffer3.update(&mut cx, |_, cx| {
2602 cx.subscribe(&buffer3, {
2603 let events = events.clone();
2604 move |_, _, event, _| events.borrow_mut().push(event.clone())
2605 })
2606 .detach();
2607 });
2608
2609 worktree.flush_fs_events(&cx).await;
2610 buffer3.update(&mut cx, |buffer, cx| {
2611 buffer.edit(Some(0..0), "x", cx);
2612 });
2613 events.borrow_mut().clear();
2614 fs::remove_file(dir.path().join("file3")).unwrap();
2615 buffer3
2616 .condition(&cx, |_, _| !events.borrow().is_empty())
2617 .await;
2618 assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
2619 cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
2620 }
2621
2622 #[gpui::test]
2623 async fn test_buffer_file_changes_on_disk(mut cx: gpui::TestAppContext) {
2624 use std::fs;
2625
2626 let initial_contents = "aaa\nbbbbb\nc\n";
2627 let dir = temp_tree(json!({ "the-file": initial_contents }));
2628
2629 let project = build_project(Arc::new(RealFs), &mut cx);
2630 let worktree = project
2631 .update(&mut cx, |p, cx| p.add_local_worktree(dir.path(), false, cx))
2632 .await
2633 .unwrap();
2634 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
2635
2636 worktree
2637 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
2638 .await;
2639
2640 let abs_path = dir.path().join("the-file");
2641 let buffer = project
2642 .update(&mut cx, |p, cx| {
2643 p.open_buffer((worktree_id, "the-file"), cx)
2644 })
2645 .await
2646 .unwrap();
2647
2648 // TODO
2649 // Add a cursor on each row.
2650 // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
2651 // assert!(!buffer.is_dirty());
2652 // buffer.add_selection_set(
2653 // &(0..3)
2654 // .map(|row| Selection {
2655 // id: row as usize,
2656 // start: Point::new(row, 1),
2657 // end: Point::new(row, 1),
2658 // reversed: false,
2659 // goal: SelectionGoal::None,
2660 // })
2661 // .collect::<Vec<_>>(),
2662 // cx,
2663 // )
2664 // });
2665
2666 // Change the file on disk, adding two new lines of text, and removing
2667 // one line.
2668 buffer.read_with(&cx, |buffer, _| {
2669 assert!(!buffer.is_dirty());
2670 assert!(!buffer.has_conflict());
2671 });
2672 let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
2673 fs::write(&abs_path, new_contents).unwrap();
2674
2675 // Because the buffer was not modified, it is reloaded from disk. Its
2676 // contents are edited according to the diff between the old and new
2677 // file contents.
2678 buffer
2679 .condition(&cx, |buffer, _| buffer.text() == new_contents)
2680 .await;
2681
2682 buffer.update(&mut cx, |buffer, _| {
2683 assert_eq!(buffer.text(), new_contents);
2684 assert!(!buffer.is_dirty());
2685 assert!(!buffer.has_conflict());
2686
2687 // TODO
2688 // let cursor_positions = buffer
2689 // .selection_set(selection_set_id)
2690 // .unwrap()
2691 // .selections::<Point>(&*buffer)
2692 // .map(|selection| {
2693 // assert_eq!(selection.start, selection.end);
2694 // selection.start
2695 // })
2696 // .collect::<Vec<_>>();
2697 // assert_eq!(
2698 // cursor_positions,
2699 // [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
2700 // );
2701 });
2702
2703 // Modify the buffer
2704 buffer.update(&mut cx, |buffer, cx| {
2705 buffer.edit(vec![0..0], " ", cx);
2706 assert!(buffer.is_dirty());
2707 assert!(!buffer.has_conflict());
2708 });
2709
2710 // Change the file on disk again, adding blank lines to the beginning.
2711 fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
2712
2713 // Because the buffer is modified, it doesn't reload from disk, but is
2714 // marked as having a conflict.
2715 buffer
2716 .condition(&cx, |buffer, _| buffer.has_conflict())
2717 .await;
2718 }
2719
2720 #[gpui::test]
2721 async fn test_grouped_diagnostics(mut cx: gpui::TestAppContext) {
2722 let fs = Arc::new(FakeFs::new());
2723 fs.insert_tree(
2724 "/the-dir",
2725 json!({
2726 "a.rs": "
2727 fn foo(mut v: Vec<usize>) {
2728 for x in &v {
2729 v.push(1);
2730 }
2731 }
2732 "
2733 .unindent(),
2734 }),
2735 )
2736 .await;
2737
2738 let project = build_project(fs.clone(), &mut cx);
2739 let worktree = project
2740 .update(&mut cx, |p, cx| p.add_local_worktree("/the-dir", false, cx))
2741 .await
2742 .unwrap();
2743 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
2744
2745 let buffer = project
2746 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
2747 .await
2748 .unwrap();
2749
2750 let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
2751 let message = lsp::PublishDiagnosticsParams {
2752 uri: buffer_uri.clone(),
2753 diagnostics: vec![
2754 lsp::Diagnostic {
2755 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
2756 severity: Some(DiagnosticSeverity::WARNING),
2757 message: "error 1".to_string(),
2758 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
2759 location: lsp::Location {
2760 uri: buffer_uri.clone(),
2761 range: lsp::Range::new(
2762 lsp::Position::new(1, 8),
2763 lsp::Position::new(1, 9),
2764 ),
2765 },
2766 message: "error 1 hint 1".to_string(),
2767 }]),
2768 ..Default::default()
2769 },
2770 lsp::Diagnostic {
2771 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
2772 severity: Some(DiagnosticSeverity::HINT),
2773 message: "error 1 hint 1".to_string(),
2774 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
2775 location: lsp::Location {
2776 uri: buffer_uri.clone(),
2777 range: lsp::Range::new(
2778 lsp::Position::new(1, 8),
2779 lsp::Position::new(1, 9),
2780 ),
2781 },
2782 message: "original diagnostic".to_string(),
2783 }]),
2784 ..Default::default()
2785 },
2786 lsp::Diagnostic {
2787 range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
2788 severity: Some(DiagnosticSeverity::ERROR),
2789 message: "error 2".to_string(),
2790 related_information: Some(vec![
2791 lsp::DiagnosticRelatedInformation {
2792 location: lsp::Location {
2793 uri: buffer_uri.clone(),
2794 range: lsp::Range::new(
2795 lsp::Position::new(1, 13),
2796 lsp::Position::new(1, 15),
2797 ),
2798 },
2799 message: "error 2 hint 1".to_string(),
2800 },
2801 lsp::DiagnosticRelatedInformation {
2802 location: lsp::Location {
2803 uri: buffer_uri.clone(),
2804 range: lsp::Range::new(
2805 lsp::Position::new(1, 13),
2806 lsp::Position::new(1, 15),
2807 ),
2808 },
2809 message: "error 2 hint 2".to_string(),
2810 },
2811 ]),
2812 ..Default::default()
2813 },
2814 lsp::Diagnostic {
2815 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
2816 severity: Some(DiagnosticSeverity::HINT),
2817 message: "error 2 hint 1".to_string(),
2818 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
2819 location: lsp::Location {
2820 uri: buffer_uri.clone(),
2821 range: lsp::Range::new(
2822 lsp::Position::new(2, 8),
2823 lsp::Position::new(2, 17),
2824 ),
2825 },
2826 message: "original diagnostic".to_string(),
2827 }]),
2828 ..Default::default()
2829 },
2830 lsp::Diagnostic {
2831 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
2832 severity: Some(DiagnosticSeverity::HINT),
2833 message: "error 2 hint 2".to_string(),
2834 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
2835 location: lsp::Location {
2836 uri: buffer_uri.clone(),
2837 range: lsp::Range::new(
2838 lsp::Position::new(2, 8),
2839 lsp::Position::new(2, 17),
2840 ),
2841 },
2842 message: "original diagnostic".to_string(),
2843 }]),
2844 ..Default::default()
2845 },
2846 ],
2847 version: None,
2848 };
2849
2850 project
2851 .update(&mut cx, |p, cx| {
2852 p.update_diagnostics(message, &Default::default(), cx)
2853 })
2854 .unwrap();
2855 let buffer = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
2856
2857 assert_eq!(
2858 buffer
2859 .diagnostics_in_range::<_, Point>(0..buffer.len())
2860 .collect::<Vec<_>>(),
2861 &[
2862 DiagnosticEntry {
2863 range: Point::new(1, 8)..Point::new(1, 9),
2864 diagnostic: Diagnostic {
2865 severity: DiagnosticSeverity::WARNING,
2866 message: "error 1".to_string(),
2867 group_id: 0,
2868 is_primary: true,
2869 ..Default::default()
2870 }
2871 },
2872 DiagnosticEntry {
2873 range: Point::new(1, 8)..Point::new(1, 9),
2874 diagnostic: Diagnostic {
2875 severity: DiagnosticSeverity::HINT,
2876 message: "error 1 hint 1".to_string(),
2877 group_id: 0,
2878 is_primary: false,
2879 ..Default::default()
2880 }
2881 },
2882 DiagnosticEntry {
2883 range: Point::new(1, 13)..Point::new(1, 15),
2884 diagnostic: Diagnostic {
2885 severity: DiagnosticSeverity::HINT,
2886 message: "error 2 hint 1".to_string(),
2887 group_id: 1,
2888 is_primary: false,
2889 ..Default::default()
2890 }
2891 },
2892 DiagnosticEntry {
2893 range: Point::new(1, 13)..Point::new(1, 15),
2894 diagnostic: Diagnostic {
2895 severity: DiagnosticSeverity::HINT,
2896 message: "error 2 hint 2".to_string(),
2897 group_id: 1,
2898 is_primary: false,
2899 ..Default::default()
2900 }
2901 },
2902 DiagnosticEntry {
2903 range: Point::new(2, 8)..Point::new(2, 17),
2904 diagnostic: Diagnostic {
2905 severity: DiagnosticSeverity::ERROR,
2906 message: "error 2".to_string(),
2907 group_id: 1,
2908 is_primary: true,
2909 ..Default::default()
2910 }
2911 }
2912 ]
2913 );
2914
2915 assert_eq!(
2916 buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
2917 &[
2918 DiagnosticEntry {
2919 range: Point::new(1, 8)..Point::new(1, 9),
2920 diagnostic: Diagnostic {
2921 severity: DiagnosticSeverity::WARNING,
2922 message: "error 1".to_string(),
2923 group_id: 0,
2924 is_primary: true,
2925 ..Default::default()
2926 }
2927 },
2928 DiagnosticEntry {
2929 range: Point::new(1, 8)..Point::new(1, 9),
2930 diagnostic: Diagnostic {
2931 severity: DiagnosticSeverity::HINT,
2932 message: "error 1 hint 1".to_string(),
2933 group_id: 0,
2934 is_primary: false,
2935 ..Default::default()
2936 }
2937 },
2938 ]
2939 );
2940 assert_eq!(
2941 buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
2942 &[
2943 DiagnosticEntry {
2944 range: Point::new(1, 13)..Point::new(1, 15),
2945 diagnostic: Diagnostic {
2946 severity: DiagnosticSeverity::HINT,
2947 message: "error 2 hint 1".to_string(),
2948 group_id: 1,
2949 is_primary: false,
2950 ..Default::default()
2951 }
2952 },
2953 DiagnosticEntry {
2954 range: Point::new(1, 13)..Point::new(1, 15),
2955 diagnostic: Diagnostic {
2956 severity: DiagnosticSeverity::HINT,
2957 message: "error 2 hint 2".to_string(),
2958 group_id: 1,
2959 is_primary: false,
2960 ..Default::default()
2961 }
2962 },
2963 DiagnosticEntry {
2964 range: Point::new(2, 8)..Point::new(2, 17),
2965 diagnostic: Diagnostic {
2966 severity: DiagnosticSeverity::ERROR,
2967 message: "error 2".to_string(),
2968 group_id: 1,
2969 is_primary: true,
2970 ..Default::default()
2971 }
2972 }
2973 ]
2974 );
2975 }
2976
2977 fn build_project(fs: Arc<dyn Fs>, cx: &mut TestAppContext) -> ModelHandle<Project> {
2978 let languages = Arc::new(LanguageRegistry::new());
2979 let http_client = FakeHttpClient::with_404_response();
2980 let client = client::Client::new(http_client.clone());
2981 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
2982 cx.update(|cx| Project::local(client, user_store, languages, fs, cx))
2983 }
2984}