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