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