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