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