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(edits) = resolved_completion.additional_text_edits {
1408 let edits = buffer_handle
1409 .update(&mut cx, |buffer, cx| buffer.edits_from_lsp(edits, None, cx))
1410 .await?;
1411 buffer_handle.update(&mut cx, |buffer, cx| {
1412 buffer.finalize_last_transaction();
1413 buffer.start_transaction();
1414 for (range, text) in edits {
1415 buffer.edit([range], text, cx);
1416 }
1417 let transaction = if buffer.end_transaction(cx).is_some() {
1418 let transaction = buffer.finalize_last_transaction().unwrap().clone();
1419 if !push_to_history {
1420 buffer.forget_transaction(transaction.id);
1421 }
1422 Some(transaction)
1423 } else {
1424 None
1425 };
1426 Ok(transaction)
1427 })
1428 } else {
1429 Ok(None)
1430 }
1431 })
1432 } else if let Some(project_id) = self.remote_id() {
1433 let client = self.client.clone();
1434 cx.spawn(|_, mut cx| async move {
1435 let response = client
1436 .request(proto::ApplyCompletionAdditionalEdits {
1437 project_id,
1438 buffer_id,
1439 completion: Some(language::proto::serialize_completion(&completion)),
1440 })
1441 .await?;
1442
1443 if let Some(transaction) = response.transaction {
1444 let transaction = language::proto::deserialize_transaction(transaction)?;
1445 buffer_handle
1446 .update(&mut cx, |buffer, _| {
1447 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
1448 })
1449 .await;
1450 if push_to_history {
1451 buffer_handle.update(&mut cx, |buffer, _| {
1452 buffer.push_transaction(transaction.clone(), Instant::now());
1453 });
1454 }
1455 Ok(Some(transaction))
1456 } else {
1457 Ok(None)
1458 }
1459 })
1460 } else {
1461 Task::ready(Err(anyhow!("project does not have a remote id")))
1462 }
1463 }
1464
1465 pub fn code_actions<T: ToPointUtf16>(
1466 &self,
1467 source_buffer_handle: &ModelHandle<Buffer>,
1468 position: T,
1469 cx: &mut ModelContext<Self>,
1470 ) -> Task<Result<Vec<CodeAction>>> {
1471 let source_buffer_handle = source_buffer_handle.clone();
1472 let source_buffer = source_buffer_handle.read(cx);
1473 let buffer_id = source_buffer.remote_id();
1474 let worktree;
1475 let buffer_abs_path;
1476 if let Some(file) = File::from_dyn(source_buffer.file()) {
1477 worktree = file.worktree.clone();
1478 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
1479 } else {
1480 return Task::ready(Ok(Default::default()));
1481 };
1482
1483 let position = position.to_point_utf16(source_buffer);
1484 let anchor = source_buffer.anchor_after(position);
1485
1486 if worktree.read(cx).as_local().is_some() {
1487 let buffer_abs_path = buffer_abs_path.unwrap();
1488 let lang_name;
1489 let lang_server;
1490 if let Some(lang) = source_buffer.language() {
1491 lang_name = lang.name().to_string();
1492 if let Some(server) = self
1493 .language_servers
1494 .get(&(worktree.read(cx).id(), lang_name.clone()))
1495 {
1496 lang_server = server.clone();
1497 } else {
1498 return Task::ready(Ok(Default::default()));
1499 };
1500 } else {
1501 return Task::ready(Ok(Default::default()));
1502 }
1503
1504 cx.foreground().spawn(async move {
1505 let actions = lang_server
1506 .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
1507 text_document: lsp::TextDocumentIdentifier::new(
1508 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
1509 ),
1510 range: lsp::Range::new(
1511 position.to_lsp_position(),
1512 position.to_lsp_position(),
1513 ),
1514 work_done_progress_params: Default::default(),
1515 partial_result_params: Default::default(),
1516 context: lsp::CodeActionContext {
1517 diagnostics: Default::default(),
1518 only: Some(vec![
1519 lsp::CodeActionKind::QUICKFIX,
1520 lsp::CodeActionKind::REFACTOR,
1521 lsp::CodeActionKind::REFACTOR_EXTRACT,
1522 ]),
1523 },
1524 })
1525 .await?
1526 .unwrap_or_default()
1527 .into_iter()
1528 .filter_map(|entry| {
1529 if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
1530 Some(CodeAction {
1531 position: anchor.clone(),
1532 lsp_action,
1533 })
1534 } else {
1535 None
1536 }
1537 })
1538 .collect();
1539 Ok(actions)
1540 })
1541 } else if let Some(project_id) = self.remote_id() {
1542 let rpc = self.client.clone();
1543 cx.foreground().spawn(async move {
1544 let response = rpc
1545 .request(proto::GetCodeActions {
1546 project_id,
1547 buffer_id,
1548 position: Some(language::proto::serialize_anchor(&anchor)),
1549 })
1550 .await?;
1551 response
1552 .actions
1553 .into_iter()
1554 .map(language::proto::deserialize_code_action)
1555 .collect()
1556 })
1557 } else {
1558 Task::ready(Ok(Default::default()))
1559 }
1560 }
1561
1562 pub fn apply_code_action(
1563 &self,
1564 buffer_handle: ModelHandle<Buffer>,
1565 mut action: CodeAction,
1566 push_to_history: bool,
1567 cx: &mut ModelContext<Self>,
1568 ) -> Task<Result<ProjectTransaction>> {
1569 if self.is_local() {
1570 let buffer = buffer_handle.read(cx);
1571 let lang_name = if let Some(lang) = buffer.language() {
1572 lang.name().to_string()
1573 } else {
1574 return Task::ready(Ok(Default::default()));
1575 };
1576 let lang_server = if let Some(language_server) = buffer.language_server() {
1577 language_server.clone()
1578 } else {
1579 return Task::ready(Err(anyhow!("buffer does not have a language server")));
1580 };
1581 let position = action.position.to_point_utf16(buffer).to_lsp_position();
1582 let fs = self.fs.clone();
1583
1584 cx.spawn(|this, mut cx| async move {
1585 if let Some(range) = action
1586 .lsp_action
1587 .data
1588 .as_mut()
1589 .and_then(|d| d.get_mut("codeActionParams"))
1590 .and_then(|d| d.get_mut("range"))
1591 {
1592 *range = serde_json::to_value(&lsp::Range::new(position, position)).unwrap();
1593 action.lsp_action = lang_server
1594 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
1595 .await?;
1596 } else {
1597 let actions = this
1598 .update(&mut cx, |this, cx| {
1599 this.code_actions(&buffer_handle, action.position.clone(), cx)
1600 })
1601 .await?;
1602 action.lsp_action = actions
1603 .into_iter()
1604 .find(|a| a.lsp_action.title == action.lsp_action.title)
1605 .ok_or_else(|| anyhow!("code action is outdated"))?
1606 .lsp_action;
1607 }
1608
1609 let mut operations = Vec::new();
1610 if let Some(edit) = action.lsp_action.edit {
1611 if let Some(document_changes) = edit.document_changes {
1612 match document_changes {
1613 lsp::DocumentChanges::Edits(edits) => operations
1614 .extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit)),
1615 lsp::DocumentChanges::Operations(ops) => operations = ops,
1616 }
1617 } else if let Some(changes) = edit.changes {
1618 operations.extend(changes.into_iter().map(|(uri, edits)| {
1619 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
1620 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
1621 uri,
1622 version: None,
1623 },
1624 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
1625 })
1626 }));
1627 }
1628 }
1629
1630 let mut project_transaction = ProjectTransaction::default();
1631 for operation in operations {
1632 match operation {
1633 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
1634 let abs_path = op
1635 .uri
1636 .to_file_path()
1637 .map_err(|_| anyhow!("can't convert URI to path"))?;
1638
1639 if let Some(parent_path) = abs_path.parent() {
1640 fs.create_dir(parent_path).await?;
1641 }
1642 if abs_path.ends_with("/") {
1643 fs.create_dir(&abs_path).await?;
1644 } else {
1645 fs.create_file(
1646 &abs_path,
1647 op.options.map(Into::into).unwrap_or_default(),
1648 )
1649 .await?;
1650 }
1651 }
1652 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
1653 let source_abs_path = op
1654 .old_uri
1655 .to_file_path()
1656 .map_err(|_| anyhow!("can't convert URI to path"))?;
1657 let target_abs_path = op
1658 .new_uri
1659 .to_file_path()
1660 .map_err(|_| anyhow!("can't convert URI to path"))?;
1661 fs.rename(
1662 &source_abs_path,
1663 &target_abs_path,
1664 op.options.map(Into::into).unwrap_or_default(),
1665 )
1666 .await?;
1667 }
1668 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
1669 let abs_path = op
1670 .uri
1671 .to_file_path()
1672 .map_err(|_| anyhow!("can't convert URI to path"))?;
1673 let options = op.options.map(Into::into).unwrap_or_default();
1674 if abs_path.ends_with("/") {
1675 fs.remove_dir(&abs_path, options).await?;
1676 } else {
1677 fs.remove_file(&abs_path, options).await?;
1678 }
1679 }
1680 lsp::DocumentChangeOperation::Edit(op) => {
1681 let buffer_to_edit = this
1682 .update(&mut cx, |this, cx| {
1683 this.open_local_buffer_from_lsp_path(
1684 op.text_document.uri,
1685 lang_name.clone(),
1686 lang_server.clone(),
1687 cx,
1688 )
1689 })
1690 .await?;
1691
1692 let edits = buffer_to_edit
1693 .update(&mut cx, |buffer, cx| {
1694 let edits = op.edits.into_iter().map(|edit| match edit {
1695 lsp::OneOf::Left(edit) => edit,
1696 lsp::OneOf::Right(edit) => edit.text_edit,
1697 });
1698 buffer.edits_from_lsp(edits, op.text_document.version, cx)
1699 })
1700 .await?;
1701
1702 let transaction = buffer_to_edit.update(&mut cx, |buffer, cx| {
1703 buffer.finalize_last_transaction();
1704 buffer.start_transaction();
1705 for (range, text) in edits {
1706 buffer.edit([range], text, cx);
1707 }
1708 let transaction = if buffer.end_transaction(cx).is_some() {
1709 let transaction =
1710 buffer.finalize_last_transaction().unwrap().clone();
1711 if !push_to_history {
1712 buffer.forget_transaction(transaction.id);
1713 }
1714 Some(transaction)
1715 } else {
1716 None
1717 };
1718
1719 transaction
1720 });
1721 if let Some(transaction) = transaction {
1722 project_transaction.0.insert(buffer_to_edit, transaction);
1723 }
1724 }
1725 }
1726 }
1727
1728 Ok(project_transaction)
1729 })
1730 } else if let Some(project_id) = self.remote_id() {
1731 let client = self.client.clone();
1732 let request = proto::ApplyCodeAction {
1733 project_id,
1734 buffer_id: buffer_handle.read(cx).remote_id(),
1735 action: Some(language::proto::serialize_code_action(&action)),
1736 };
1737 cx.spawn(|this, mut cx| async move {
1738 let response = client
1739 .request(request)
1740 .await?
1741 .transaction
1742 .ok_or_else(|| anyhow!("missing transaction"))?;
1743 this.update(&mut cx, |this, cx| {
1744 this.deserialize_project_transaction(response, push_to_history, cx)
1745 })
1746 .await
1747 })
1748 } else {
1749 Task::ready(Err(anyhow!("project does not have a remote id")))
1750 }
1751 }
1752
1753 pub fn find_or_create_local_worktree(
1754 &self,
1755 abs_path: impl AsRef<Path>,
1756 weak: bool,
1757 cx: &mut ModelContext<Self>,
1758 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
1759 let abs_path = abs_path.as_ref();
1760 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
1761 Task::ready(Ok((tree.clone(), relative_path.into())))
1762 } else {
1763 let worktree = self.create_local_worktree(abs_path, weak, cx);
1764 cx.foreground()
1765 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
1766 }
1767 }
1768
1769 fn find_local_worktree(
1770 &self,
1771 abs_path: &Path,
1772 cx: &AppContext,
1773 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
1774 for tree in self.worktrees(cx) {
1775 if let Some(relative_path) = tree
1776 .read(cx)
1777 .as_local()
1778 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
1779 {
1780 return Some((tree.clone(), relative_path.into()));
1781 }
1782 }
1783 None
1784 }
1785
1786 pub fn is_shared(&self) -> bool {
1787 match &self.client_state {
1788 ProjectClientState::Local { is_shared, .. } => *is_shared,
1789 ProjectClientState::Remote { .. } => false,
1790 }
1791 }
1792
1793 fn create_local_worktree(
1794 &self,
1795 abs_path: impl AsRef<Path>,
1796 weak: bool,
1797 cx: &mut ModelContext<Self>,
1798 ) -> Task<Result<ModelHandle<Worktree>>> {
1799 let fs = self.fs.clone();
1800 let client = self.client.clone();
1801 let path = Arc::from(abs_path.as_ref());
1802 cx.spawn(|project, mut cx| async move {
1803 let worktree = Worktree::local(client.clone(), path, weak, fs, &mut cx).await?;
1804
1805 let (remote_project_id, is_shared) = project.update(&mut cx, |project, cx| {
1806 project.add_worktree(&worktree, cx);
1807 (project.remote_id(), project.is_shared())
1808 });
1809
1810 if let Some(project_id) = remote_project_id {
1811 worktree
1812 .update(&mut cx, |worktree, cx| {
1813 worktree.as_local_mut().unwrap().register(project_id, cx)
1814 })
1815 .await?;
1816 if is_shared {
1817 worktree
1818 .update(&mut cx, |worktree, cx| {
1819 worktree.as_local_mut().unwrap().share(project_id, cx)
1820 })
1821 .await?;
1822 }
1823 }
1824
1825 Ok(worktree)
1826 })
1827 }
1828
1829 pub fn remove_worktree(&mut self, id: WorktreeId, cx: &mut ModelContext<Self>) {
1830 self.worktrees.retain(|worktree| {
1831 worktree
1832 .upgrade(cx)
1833 .map_or(false, |w| w.read(cx).id() != id)
1834 });
1835 cx.notify();
1836 }
1837
1838 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
1839 cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
1840 if worktree.read(cx).is_local() {
1841 cx.subscribe(&worktree, |this, worktree, _, cx| {
1842 this.update_local_worktree_buffers(worktree, cx);
1843 })
1844 .detach();
1845 }
1846
1847 let push_weak_handle = {
1848 let worktree = worktree.read(cx);
1849 worktree.is_local() && worktree.is_weak()
1850 };
1851 if push_weak_handle {
1852 cx.observe_release(&worktree, |this, cx| {
1853 this.worktrees
1854 .retain(|worktree| worktree.upgrade(cx).is_some());
1855 cx.notify();
1856 })
1857 .detach();
1858 self.worktrees
1859 .push(WorktreeHandle::Weak(worktree.downgrade()));
1860 } else {
1861 self.worktrees
1862 .push(WorktreeHandle::Strong(worktree.clone()));
1863 }
1864 cx.notify();
1865 }
1866
1867 fn update_local_worktree_buffers(
1868 &mut self,
1869 worktree_handle: ModelHandle<Worktree>,
1870 cx: &mut ModelContext<Self>,
1871 ) {
1872 let snapshot = worktree_handle.read(cx).snapshot();
1873 let mut buffers_to_delete = Vec::new();
1874 for (buffer_id, buffer) in &self.open_buffers {
1875 if let Some(buffer) = buffer.upgrade(cx) {
1876 buffer.update(cx, |buffer, cx| {
1877 if let Some(old_file) = File::from_dyn(buffer.file()) {
1878 if old_file.worktree != worktree_handle {
1879 return;
1880 }
1881
1882 let new_file = if let Some(entry) = old_file
1883 .entry_id
1884 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
1885 {
1886 File {
1887 is_local: true,
1888 entry_id: Some(entry.id),
1889 mtime: entry.mtime,
1890 path: entry.path.clone(),
1891 worktree: worktree_handle.clone(),
1892 }
1893 } else if let Some(entry) =
1894 snapshot.entry_for_path(old_file.path().as_ref())
1895 {
1896 File {
1897 is_local: true,
1898 entry_id: Some(entry.id),
1899 mtime: entry.mtime,
1900 path: entry.path.clone(),
1901 worktree: worktree_handle.clone(),
1902 }
1903 } else {
1904 File {
1905 is_local: true,
1906 entry_id: None,
1907 path: old_file.path().clone(),
1908 mtime: old_file.mtime(),
1909 worktree: worktree_handle.clone(),
1910 }
1911 };
1912
1913 if let Some(project_id) = self.remote_id() {
1914 self.client
1915 .send(proto::UpdateBufferFile {
1916 project_id,
1917 buffer_id: *buffer_id as u64,
1918 file: Some(new_file.to_proto()),
1919 })
1920 .log_err();
1921 }
1922 buffer.file_updated(Box::new(new_file), cx).detach();
1923 }
1924 });
1925 } else {
1926 buffers_to_delete.push(*buffer_id);
1927 }
1928 }
1929
1930 for buffer_id in buffers_to_delete {
1931 self.open_buffers.remove(&buffer_id);
1932 }
1933 }
1934
1935 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
1936 let new_active_entry = entry.and_then(|project_path| {
1937 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1938 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
1939 Some(ProjectEntry {
1940 worktree_id: project_path.worktree_id,
1941 entry_id: entry.id,
1942 })
1943 });
1944 if new_active_entry != self.active_entry {
1945 self.active_entry = new_active_entry;
1946 cx.emit(Event::ActiveEntryChanged(new_active_entry));
1947 }
1948 }
1949
1950 pub fn is_running_disk_based_diagnostics(&self) -> bool {
1951 self.language_servers_with_diagnostics_running > 0
1952 }
1953
1954 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
1955 let mut summary = DiagnosticSummary::default();
1956 for (_, path_summary) in self.diagnostic_summaries(cx) {
1957 summary.error_count += path_summary.error_count;
1958 summary.warning_count += path_summary.warning_count;
1959 summary.info_count += path_summary.info_count;
1960 summary.hint_count += path_summary.hint_count;
1961 }
1962 summary
1963 }
1964
1965 pub fn diagnostic_summaries<'a>(
1966 &'a self,
1967 cx: &'a AppContext,
1968 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
1969 self.worktrees(cx).flat_map(move |worktree| {
1970 let worktree = worktree.read(cx);
1971 let worktree_id = worktree.id();
1972 worktree
1973 .diagnostic_summaries()
1974 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
1975 })
1976 }
1977
1978 pub fn disk_based_diagnostics_started(&mut self, cx: &mut ModelContext<Self>) {
1979 self.language_servers_with_diagnostics_running += 1;
1980 if self.language_servers_with_diagnostics_running == 1 {
1981 cx.emit(Event::DiskBasedDiagnosticsStarted);
1982 }
1983 }
1984
1985 pub fn disk_based_diagnostics_finished(&mut self, cx: &mut ModelContext<Self>) {
1986 cx.emit(Event::DiskBasedDiagnosticsUpdated);
1987 self.language_servers_with_diagnostics_running -= 1;
1988 if self.language_servers_with_diagnostics_running == 0 {
1989 cx.emit(Event::DiskBasedDiagnosticsFinished);
1990 }
1991 }
1992
1993 pub fn active_entry(&self) -> Option<ProjectEntry> {
1994 self.active_entry
1995 }
1996
1997 // RPC message handlers
1998
1999 fn handle_unshare_project(
2000 &mut self,
2001 _: TypedEnvelope<proto::UnshareProject>,
2002 _: Arc<Client>,
2003 cx: &mut ModelContext<Self>,
2004 ) -> Result<()> {
2005 if let ProjectClientState::Remote {
2006 sharing_has_stopped,
2007 ..
2008 } = &mut self.client_state
2009 {
2010 *sharing_has_stopped = true;
2011 self.collaborators.clear();
2012 cx.notify();
2013 Ok(())
2014 } else {
2015 unreachable!()
2016 }
2017 }
2018
2019 fn handle_add_collaborator(
2020 &mut self,
2021 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
2022 _: Arc<Client>,
2023 cx: &mut ModelContext<Self>,
2024 ) -> Result<()> {
2025 let user_store = self.user_store.clone();
2026 let collaborator = envelope
2027 .payload
2028 .collaborator
2029 .take()
2030 .ok_or_else(|| anyhow!("empty collaborator"))?;
2031
2032 cx.spawn(|this, mut cx| {
2033 async move {
2034 let collaborator =
2035 Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
2036 this.update(&mut cx, |this, cx| {
2037 this.collaborators
2038 .insert(collaborator.peer_id, collaborator);
2039 cx.notify();
2040 });
2041 Ok(())
2042 }
2043 .log_err()
2044 })
2045 .detach();
2046
2047 Ok(())
2048 }
2049
2050 fn handle_remove_collaborator(
2051 &mut self,
2052 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
2053 _: Arc<Client>,
2054 cx: &mut ModelContext<Self>,
2055 ) -> Result<()> {
2056 let peer_id = PeerId(envelope.payload.peer_id);
2057 let replica_id = self
2058 .collaborators
2059 .remove(&peer_id)
2060 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
2061 .replica_id;
2062 self.shared_buffers.remove(&peer_id);
2063 for (_, buffer) in &self.open_buffers {
2064 if let Some(buffer) = buffer.upgrade(cx) {
2065 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
2066 }
2067 }
2068 cx.notify();
2069 Ok(())
2070 }
2071
2072 fn handle_share_worktree(
2073 &mut self,
2074 envelope: TypedEnvelope<proto::ShareWorktree>,
2075 client: Arc<Client>,
2076 cx: &mut ModelContext<Self>,
2077 ) -> Result<()> {
2078 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
2079 let replica_id = self.replica_id();
2080 let worktree = envelope
2081 .payload
2082 .worktree
2083 .ok_or_else(|| anyhow!("invalid worktree"))?;
2084 let (worktree, load_task) = Worktree::remote(remote_id, replica_id, worktree, client, cx);
2085 self.add_worktree(&worktree, cx);
2086 load_task.detach();
2087 Ok(())
2088 }
2089
2090 fn handle_unregister_worktree(
2091 &mut self,
2092 envelope: TypedEnvelope<proto::UnregisterWorktree>,
2093 _: Arc<Client>,
2094 cx: &mut ModelContext<Self>,
2095 ) -> Result<()> {
2096 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2097 self.remove_worktree(worktree_id, cx);
2098 Ok(())
2099 }
2100
2101 fn handle_update_worktree(
2102 &mut self,
2103 envelope: TypedEnvelope<proto::UpdateWorktree>,
2104 _: Arc<Client>,
2105 cx: &mut ModelContext<Self>,
2106 ) -> Result<()> {
2107 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2108 if let Some(worktree) = self.worktree_for_id(worktree_id, cx) {
2109 worktree.update(cx, |worktree, cx| {
2110 let worktree = worktree.as_remote_mut().unwrap();
2111 worktree.update_from_remote(envelope, cx)
2112 })?;
2113 }
2114 Ok(())
2115 }
2116
2117 fn handle_update_diagnostic_summary(
2118 &mut self,
2119 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
2120 _: Arc<Client>,
2121 cx: &mut ModelContext<Self>,
2122 ) -> Result<()> {
2123 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2124 if let Some(worktree) = self.worktree_for_id(worktree_id, cx) {
2125 if let Some(summary) = envelope.payload.summary {
2126 let project_path = ProjectPath {
2127 worktree_id,
2128 path: Path::new(&summary.path).into(),
2129 };
2130 worktree.update(cx, |worktree, _| {
2131 worktree
2132 .as_remote_mut()
2133 .unwrap()
2134 .update_diagnostic_summary(project_path.path.clone(), &summary);
2135 });
2136 cx.emit(Event::DiagnosticsUpdated(project_path));
2137 }
2138 }
2139 Ok(())
2140 }
2141
2142 fn handle_disk_based_diagnostics_updating(
2143 &mut self,
2144 _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
2145 _: Arc<Client>,
2146 cx: &mut ModelContext<Self>,
2147 ) -> Result<()> {
2148 self.disk_based_diagnostics_started(cx);
2149 Ok(())
2150 }
2151
2152 fn handle_disk_based_diagnostics_updated(
2153 &mut self,
2154 _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
2155 _: Arc<Client>,
2156 cx: &mut ModelContext<Self>,
2157 ) -> Result<()> {
2158 self.disk_based_diagnostics_finished(cx);
2159 Ok(())
2160 }
2161
2162 pub fn handle_update_buffer(
2163 &mut self,
2164 envelope: TypedEnvelope<proto::UpdateBuffer>,
2165 _: Arc<Client>,
2166 cx: &mut ModelContext<Self>,
2167 ) -> Result<()> {
2168 let payload = envelope.payload.clone();
2169 let buffer_id = payload.buffer_id as usize;
2170 let ops = payload
2171 .operations
2172 .into_iter()
2173 .map(|op| language::proto::deserialize_operation(op))
2174 .collect::<Result<Vec<_>, _>>()?;
2175 if let Some(buffer) = self.open_buffers.get_mut(&buffer_id) {
2176 if let Some(buffer) = buffer.upgrade(cx) {
2177 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
2178 }
2179 }
2180 Ok(())
2181 }
2182
2183 pub fn handle_update_buffer_file(
2184 &mut self,
2185 envelope: TypedEnvelope<proto::UpdateBufferFile>,
2186 _: Arc<Client>,
2187 cx: &mut ModelContext<Self>,
2188 ) -> Result<()> {
2189 let payload = envelope.payload.clone();
2190 let buffer_id = payload.buffer_id as usize;
2191 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
2192 let worktree = self
2193 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
2194 .ok_or_else(|| anyhow!("no such worktree"))?;
2195 let file = File::from_proto(file, worktree.clone(), cx)?;
2196 let buffer = self
2197 .open_buffers
2198 .get_mut(&buffer_id)
2199 .and_then(|b| b.upgrade(cx))
2200 .ok_or_else(|| anyhow!("no such buffer"))?;
2201 buffer.update(cx, |buffer, cx| {
2202 buffer.file_updated(Box::new(file), cx).detach();
2203 });
2204
2205 Ok(())
2206 }
2207
2208 pub fn handle_save_buffer(
2209 &mut self,
2210 envelope: TypedEnvelope<proto::SaveBuffer>,
2211 rpc: Arc<Client>,
2212 cx: &mut ModelContext<Self>,
2213 ) -> Result<()> {
2214 let sender_id = envelope.original_sender_id()?;
2215 let project_id = self.remote_id().ok_or_else(|| anyhow!("not connected"))?;
2216 let buffer = self
2217 .shared_buffers
2218 .get(&sender_id)
2219 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2220 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2221 let receipt = envelope.receipt();
2222 let buffer_id = envelope.payload.buffer_id;
2223 let save = cx.spawn(|_, mut cx| async move {
2224 buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await
2225 });
2226
2227 cx.background()
2228 .spawn(
2229 async move {
2230 let (version, mtime) = save.await?;
2231
2232 rpc.respond(
2233 receipt,
2234 proto::BufferSaved {
2235 project_id,
2236 buffer_id,
2237 version: (&version).into(),
2238 mtime: Some(mtime.into()),
2239 },
2240 )?;
2241
2242 Ok(())
2243 }
2244 .log_err(),
2245 )
2246 .detach();
2247 Ok(())
2248 }
2249
2250 pub fn handle_format_buffers(
2251 &mut self,
2252 envelope: TypedEnvelope<proto::FormatBuffers>,
2253 rpc: Arc<Client>,
2254 cx: &mut ModelContext<Self>,
2255 ) -> Result<()> {
2256 let receipt = envelope.receipt();
2257 let sender_id = envelope.original_sender_id()?;
2258 let shared_buffers = self
2259 .shared_buffers
2260 .get(&sender_id)
2261 .ok_or_else(|| anyhow!("peer has no buffers"))?;
2262 let mut buffers = HashSet::default();
2263 for buffer_id in envelope.payload.buffer_ids {
2264 buffers.insert(
2265 shared_buffers
2266 .get(&buffer_id)
2267 .cloned()
2268 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
2269 );
2270 }
2271 cx.spawn(|this, mut cx| async move {
2272 let project_transaction = this
2273 .update(&mut cx, |this, cx| this.format(buffers, false, cx))
2274 .await
2275 .map(|project_transaction| {
2276 this.update(&mut cx, |this, cx| {
2277 this.serialize_project_transaction_for_peer(
2278 project_transaction,
2279 sender_id,
2280 cx,
2281 )
2282 })
2283 });
2284 // We spawn here in order to enqueue the sending of the response *after* transmission of
2285 // edits associated with formatting.
2286 cx.spawn(|_| async move {
2287 match project_transaction {
2288 Ok(transaction) => rpc.respond(
2289 receipt,
2290 proto::FormatBuffersResponse {
2291 transaction: Some(transaction),
2292 },
2293 )?,
2294 Err(error) => rpc.respond_with_error(
2295 receipt,
2296 proto::Error {
2297 message: error.to_string(),
2298 },
2299 )?,
2300 }
2301 Ok::<_, anyhow::Error>(())
2302 })
2303 .await
2304 .log_err();
2305 })
2306 .detach();
2307 Ok(())
2308 }
2309
2310 fn handle_get_completions(
2311 &mut self,
2312 envelope: TypedEnvelope<proto::GetCompletions>,
2313 rpc: Arc<Client>,
2314 cx: &mut ModelContext<Self>,
2315 ) -> Result<()> {
2316 let receipt = envelope.receipt();
2317 let sender_id = envelope.original_sender_id()?;
2318 let buffer = self
2319 .shared_buffers
2320 .get(&sender_id)
2321 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2322 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2323 let position = envelope
2324 .payload
2325 .position
2326 .and_then(language::proto::deserialize_anchor)
2327 .ok_or_else(|| anyhow!("invalid position"))?;
2328 cx.spawn(|this, mut cx| async move {
2329 match this
2330 .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
2331 .await
2332 {
2333 Ok(completions) => rpc.respond(
2334 receipt,
2335 proto::GetCompletionsResponse {
2336 completions: completions
2337 .iter()
2338 .map(language::proto::serialize_completion)
2339 .collect(),
2340 },
2341 ),
2342 Err(error) => rpc.respond_with_error(
2343 receipt,
2344 proto::Error {
2345 message: error.to_string(),
2346 },
2347 ),
2348 }
2349 })
2350 .detach_and_log_err(cx);
2351 Ok(())
2352 }
2353
2354 fn handle_apply_additional_edits_for_completion(
2355 &mut self,
2356 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
2357 rpc: Arc<Client>,
2358 cx: &mut ModelContext<Self>,
2359 ) -> Result<()> {
2360 let receipt = envelope.receipt();
2361 let sender_id = envelope.original_sender_id()?;
2362 let buffer = self
2363 .shared_buffers
2364 .get(&sender_id)
2365 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2366 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2367 let language = buffer.read(cx).language();
2368 let completion = language::proto::deserialize_completion(
2369 envelope
2370 .payload
2371 .completion
2372 .ok_or_else(|| anyhow!("invalid completion"))?,
2373 language,
2374 )?;
2375 cx.spawn(|this, mut cx| async move {
2376 match this
2377 .update(&mut cx, |this, cx| {
2378 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
2379 })
2380 .await
2381 {
2382 Ok(transaction) => rpc.respond(
2383 receipt,
2384 proto::ApplyCompletionAdditionalEditsResponse {
2385 transaction: transaction
2386 .as_ref()
2387 .map(language::proto::serialize_transaction),
2388 },
2389 ),
2390 Err(error) => rpc.respond_with_error(
2391 receipt,
2392 proto::Error {
2393 message: error.to_string(),
2394 },
2395 ),
2396 }
2397 })
2398 .detach_and_log_err(cx);
2399 Ok(())
2400 }
2401
2402 fn handle_get_code_actions(
2403 &mut self,
2404 envelope: TypedEnvelope<proto::GetCodeActions>,
2405 rpc: Arc<Client>,
2406 cx: &mut ModelContext<Self>,
2407 ) -> Result<()> {
2408 let receipt = envelope.receipt();
2409 let sender_id = envelope.original_sender_id()?;
2410 let buffer = self
2411 .shared_buffers
2412 .get(&sender_id)
2413 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2414 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2415 let position = envelope
2416 .payload
2417 .position
2418 .and_then(language::proto::deserialize_anchor)
2419 .ok_or_else(|| anyhow!("invalid position"))?;
2420 cx.spawn(|this, mut cx| async move {
2421 match this
2422 .update(&mut cx, |this, cx| this.code_actions(&buffer, position, cx))
2423 .await
2424 {
2425 Ok(actions) => rpc.respond(
2426 receipt,
2427 proto::GetCodeActionsResponse {
2428 actions: actions
2429 .iter()
2430 .map(language::proto::serialize_code_action)
2431 .collect(),
2432 },
2433 ),
2434 Err(error) => rpc.respond_with_error(
2435 receipt,
2436 proto::Error {
2437 message: error.to_string(),
2438 },
2439 ),
2440 }
2441 })
2442 .detach_and_log_err(cx);
2443 Ok(())
2444 }
2445
2446 fn handle_apply_code_action(
2447 &mut self,
2448 envelope: TypedEnvelope<proto::ApplyCodeAction>,
2449 rpc: Arc<Client>,
2450 cx: &mut ModelContext<Self>,
2451 ) -> Result<()> {
2452 let receipt = envelope.receipt();
2453 let sender_id = envelope.original_sender_id()?;
2454 let buffer = self
2455 .shared_buffers
2456 .get(&sender_id)
2457 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2458 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2459 let action = language::proto::deserialize_code_action(
2460 envelope
2461 .payload
2462 .action
2463 .ok_or_else(|| anyhow!("invalid action"))?,
2464 )?;
2465 let apply_code_action = self.apply_code_action(buffer, action, false, cx);
2466 cx.spawn(|this, mut cx| async move {
2467 match apply_code_action.await {
2468 Ok(project_transaction) => this.update(&mut cx, |this, cx| {
2469 let serialized_transaction = this.serialize_project_transaction_for_peer(
2470 project_transaction,
2471 sender_id,
2472 cx,
2473 );
2474 rpc.respond(
2475 receipt,
2476 proto::ApplyCodeActionResponse {
2477 transaction: Some(serialized_transaction),
2478 },
2479 )
2480 }),
2481 Err(error) => rpc.respond_with_error(
2482 receipt,
2483 proto::Error {
2484 message: error.to_string(),
2485 },
2486 ),
2487 }
2488 })
2489 .detach_and_log_err(cx);
2490 Ok(())
2491 }
2492
2493 pub fn handle_get_definition(
2494 &mut self,
2495 envelope: TypedEnvelope<proto::GetDefinition>,
2496 rpc: Arc<Client>,
2497 cx: &mut ModelContext<Self>,
2498 ) -> Result<()> {
2499 let receipt = envelope.receipt();
2500 let sender_id = envelope.original_sender_id()?;
2501 let source_buffer = self
2502 .shared_buffers
2503 .get(&sender_id)
2504 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2505 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2506 let position = envelope
2507 .payload
2508 .position
2509 .and_then(deserialize_anchor)
2510 .ok_or_else(|| anyhow!("invalid position"))?;
2511 if !source_buffer.read(cx).can_resolve(&position) {
2512 return Err(anyhow!("cannot resolve position"));
2513 }
2514
2515 let definitions = self.definition(&source_buffer, position, cx);
2516 cx.spawn(|this, mut cx| async move {
2517 let definitions = definitions.await?;
2518 let mut response = proto::GetDefinitionResponse {
2519 definitions: Default::default(),
2520 };
2521 this.update(&mut cx, |this, cx| {
2522 for definition in definitions {
2523 let buffer =
2524 this.serialize_buffer_for_peer(&definition.target_buffer, sender_id, cx);
2525 response.definitions.push(proto::Definition {
2526 target_start: Some(serialize_anchor(&definition.target_range.start)),
2527 target_end: Some(serialize_anchor(&definition.target_range.end)),
2528 buffer: Some(buffer),
2529 });
2530 }
2531 });
2532 rpc.respond(receipt, response)?;
2533 Ok::<_, anyhow::Error>(())
2534 })
2535 .detach_and_log_err(cx);
2536
2537 Ok(())
2538 }
2539
2540 pub fn handle_open_buffer(
2541 &mut self,
2542 envelope: TypedEnvelope<proto::OpenBuffer>,
2543 rpc: Arc<Client>,
2544 cx: &mut ModelContext<Self>,
2545 ) -> anyhow::Result<()> {
2546 let receipt = envelope.receipt();
2547 let peer_id = envelope.original_sender_id()?;
2548 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2549 let open_buffer = self.open_buffer(
2550 ProjectPath {
2551 worktree_id,
2552 path: PathBuf::from(envelope.payload.path).into(),
2553 },
2554 cx,
2555 );
2556 cx.spawn(|this, mut cx| {
2557 async move {
2558 let buffer = open_buffer.await?;
2559 let buffer = this.update(&mut cx, |this, cx| {
2560 this.serialize_buffer_for_peer(&buffer, peer_id, cx)
2561 });
2562 rpc.respond(
2563 receipt,
2564 proto::OpenBufferResponse {
2565 buffer: Some(buffer),
2566 },
2567 )
2568 }
2569 .log_err()
2570 })
2571 .detach();
2572 Ok(())
2573 }
2574
2575 fn serialize_project_transaction_for_peer(
2576 &mut self,
2577 project_transaction: ProjectTransaction,
2578 peer_id: PeerId,
2579 cx: &AppContext,
2580 ) -> proto::ProjectTransaction {
2581 let mut serialized_transaction = proto::ProjectTransaction {
2582 buffers: Default::default(),
2583 transactions: Default::default(),
2584 };
2585 for (buffer, transaction) in project_transaction.0 {
2586 serialized_transaction
2587 .buffers
2588 .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
2589 serialized_transaction
2590 .transactions
2591 .push(language::proto::serialize_transaction(&transaction));
2592 }
2593 serialized_transaction
2594 }
2595
2596 fn deserialize_project_transaction(
2597 &self,
2598 message: proto::ProjectTransaction,
2599 push_to_history: bool,
2600 cx: &mut ModelContext<Self>,
2601 ) -> Task<Result<ProjectTransaction>> {
2602 cx.spawn(|this, mut cx| async move {
2603 let mut project_transaction = ProjectTransaction::default();
2604 for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
2605 let buffer =
2606 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))?;
2607 let transaction = language::proto::deserialize_transaction(transaction)?;
2608
2609 buffer
2610 .update(&mut cx, |buffer, _| {
2611 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
2612 })
2613 .await;
2614
2615 if push_to_history {
2616 buffer.update(&mut cx, |buffer, _| {
2617 buffer.push_transaction(transaction.clone(), Instant::now());
2618 });
2619 }
2620
2621 project_transaction.0.insert(buffer, transaction);
2622 }
2623 Ok(project_transaction)
2624 })
2625 }
2626
2627 fn serialize_buffer_for_peer(
2628 &mut self,
2629 buffer: &ModelHandle<Buffer>,
2630 peer_id: PeerId,
2631 cx: &AppContext,
2632 ) -> proto::Buffer {
2633 let buffer_id = buffer.read(cx).remote_id();
2634 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
2635 match shared_buffers.entry(buffer_id) {
2636 hash_map::Entry::Occupied(_) => proto::Buffer {
2637 variant: Some(proto::buffer::Variant::Id(buffer_id)),
2638 },
2639 hash_map::Entry::Vacant(entry) => {
2640 entry.insert(buffer.clone());
2641 proto::Buffer {
2642 variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
2643 }
2644 }
2645 }
2646 }
2647
2648 fn deserialize_buffer(
2649 &mut self,
2650 buffer: proto::Buffer,
2651 cx: &mut ModelContext<Self>,
2652 ) -> Result<ModelHandle<Buffer>> {
2653 match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
2654 proto::buffer::Variant::Id(id) => self
2655 .open_buffers
2656 .get(&(id as usize))
2657 .and_then(|buffer| buffer.upgrade(cx))
2658 .ok_or_else(|| anyhow!("no buffer exists for id {}", id)),
2659 proto::buffer::Variant::State(mut buffer) => {
2660 let mut buffer_worktree = None;
2661 let mut buffer_file = None;
2662 if let Some(file) = buffer.file.take() {
2663 let worktree_id = WorktreeId::from_proto(file.worktree_id);
2664 let worktree = self
2665 .worktree_for_id(worktree_id, cx)
2666 .ok_or_else(|| anyhow!("no worktree found for id {}", file.worktree_id))?;
2667 buffer_file = Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
2668 as Box<dyn language::File>);
2669 buffer_worktree = Some(worktree);
2670 }
2671
2672 let buffer = cx.add_model(|cx| {
2673 Buffer::from_proto(self.replica_id(), buffer, buffer_file, cx).unwrap()
2674 });
2675 self.register_buffer(&buffer, buffer_worktree.as_ref(), cx)?;
2676 Ok(buffer)
2677 }
2678 }
2679 }
2680
2681 pub fn handle_close_buffer(
2682 &mut self,
2683 envelope: TypedEnvelope<proto::CloseBuffer>,
2684 _: Arc<Client>,
2685 cx: &mut ModelContext<Self>,
2686 ) -> anyhow::Result<()> {
2687 if let Some(shared_buffers) = self.shared_buffers.get_mut(&envelope.original_sender_id()?) {
2688 shared_buffers.remove(&envelope.payload.buffer_id);
2689 cx.notify();
2690 }
2691 Ok(())
2692 }
2693
2694 pub fn handle_buffer_saved(
2695 &mut self,
2696 envelope: TypedEnvelope<proto::BufferSaved>,
2697 _: Arc<Client>,
2698 cx: &mut ModelContext<Self>,
2699 ) -> Result<()> {
2700 let payload = envelope.payload.clone();
2701 let buffer = self
2702 .open_buffers
2703 .get(&(payload.buffer_id as usize))
2704 .and_then(|buffer| buffer.upgrade(cx));
2705 if let Some(buffer) = buffer {
2706 buffer.update(cx, |buffer, cx| {
2707 let version = payload.version.try_into()?;
2708 let mtime = payload
2709 .mtime
2710 .ok_or_else(|| anyhow!("missing mtime"))?
2711 .into();
2712 buffer.did_save(version, mtime, None, cx);
2713 Result::<_, anyhow::Error>::Ok(())
2714 })?;
2715 }
2716 Ok(())
2717 }
2718
2719 pub fn handle_buffer_reloaded(
2720 &mut self,
2721 envelope: TypedEnvelope<proto::BufferReloaded>,
2722 _: Arc<Client>,
2723 cx: &mut ModelContext<Self>,
2724 ) -> Result<()> {
2725 let payload = envelope.payload.clone();
2726 let buffer = self
2727 .open_buffers
2728 .get(&(payload.buffer_id as usize))
2729 .and_then(|buffer| buffer.upgrade(cx));
2730 if let Some(buffer) = buffer {
2731 buffer.update(cx, |buffer, cx| {
2732 let version = payload.version.try_into()?;
2733 let mtime = payload
2734 .mtime
2735 .ok_or_else(|| anyhow!("missing mtime"))?
2736 .into();
2737 buffer.did_reload(version, mtime, cx);
2738 Result::<_, anyhow::Error>::Ok(())
2739 })?;
2740 }
2741 Ok(())
2742 }
2743
2744 pub fn match_paths<'a>(
2745 &self,
2746 query: &'a str,
2747 include_ignored: bool,
2748 smart_case: bool,
2749 max_results: usize,
2750 cancel_flag: &'a AtomicBool,
2751 cx: &AppContext,
2752 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
2753 let worktrees = self
2754 .worktrees(cx)
2755 .filter(|worktree| !worktree.read(cx).is_weak())
2756 .collect::<Vec<_>>();
2757 let include_root_name = worktrees.len() > 1;
2758 let candidate_sets = worktrees
2759 .into_iter()
2760 .map(|worktree| CandidateSet {
2761 snapshot: worktree.read(cx).snapshot(),
2762 include_ignored,
2763 include_root_name,
2764 })
2765 .collect::<Vec<_>>();
2766
2767 let background = cx.background().clone();
2768 async move {
2769 fuzzy::match_paths(
2770 candidate_sets.as_slice(),
2771 query,
2772 smart_case,
2773 max_results,
2774 cancel_flag,
2775 background,
2776 )
2777 .await
2778 }
2779 }
2780}
2781
2782impl WorktreeHandle {
2783 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
2784 match self {
2785 WorktreeHandle::Strong(handle) => Some(handle.clone()),
2786 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
2787 }
2788 }
2789}
2790
2791struct CandidateSet {
2792 snapshot: Snapshot,
2793 include_ignored: bool,
2794 include_root_name: bool,
2795}
2796
2797impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
2798 type Candidates = CandidateSetIter<'a>;
2799
2800 fn id(&self) -> usize {
2801 self.snapshot.id().to_usize()
2802 }
2803
2804 fn len(&self) -> usize {
2805 if self.include_ignored {
2806 self.snapshot.file_count()
2807 } else {
2808 self.snapshot.visible_file_count()
2809 }
2810 }
2811
2812 fn prefix(&self) -> Arc<str> {
2813 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
2814 self.snapshot.root_name().into()
2815 } else if self.include_root_name {
2816 format!("{}/", self.snapshot.root_name()).into()
2817 } else {
2818 "".into()
2819 }
2820 }
2821
2822 fn candidates(&'a self, start: usize) -> Self::Candidates {
2823 CandidateSetIter {
2824 traversal: self.snapshot.files(self.include_ignored, start),
2825 }
2826 }
2827}
2828
2829struct CandidateSetIter<'a> {
2830 traversal: Traversal<'a>,
2831}
2832
2833impl<'a> Iterator for CandidateSetIter<'a> {
2834 type Item = PathMatchCandidate<'a>;
2835
2836 fn next(&mut self) -> Option<Self::Item> {
2837 self.traversal.next().map(|entry| {
2838 if let EntryKind::File(char_bag) = entry.kind {
2839 PathMatchCandidate {
2840 path: &entry.path,
2841 char_bag,
2842 }
2843 } else {
2844 unreachable!()
2845 }
2846 })
2847 }
2848}
2849
2850impl Entity for Project {
2851 type Event = Event;
2852
2853 fn release(&mut self, _: &mut gpui::MutableAppContext) {
2854 match &self.client_state {
2855 ProjectClientState::Local { remote_id_rx, .. } => {
2856 if let Some(project_id) = *remote_id_rx.borrow() {
2857 self.client
2858 .send(proto::UnregisterProject { project_id })
2859 .log_err();
2860 }
2861 }
2862 ProjectClientState::Remote { remote_id, .. } => {
2863 self.client
2864 .send(proto::LeaveProject {
2865 project_id: *remote_id,
2866 })
2867 .log_err();
2868 }
2869 }
2870 }
2871
2872 fn app_will_quit(
2873 &mut self,
2874 _: &mut MutableAppContext,
2875 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
2876 use futures::FutureExt;
2877
2878 let shutdown_futures = self
2879 .language_servers
2880 .drain()
2881 .filter_map(|(_, server)| server.shutdown())
2882 .collect::<Vec<_>>();
2883 Some(
2884 async move {
2885 futures::future::join_all(shutdown_futures).await;
2886 }
2887 .boxed(),
2888 )
2889 }
2890}
2891
2892impl Collaborator {
2893 fn from_proto(
2894 message: proto::Collaborator,
2895 user_store: &ModelHandle<UserStore>,
2896 cx: &mut AsyncAppContext,
2897 ) -> impl Future<Output = Result<Self>> {
2898 let user = user_store.update(cx, |user_store, cx| {
2899 user_store.fetch_user(message.user_id, cx)
2900 });
2901
2902 async move {
2903 Ok(Self {
2904 peer_id: PeerId(message.peer_id),
2905 user: user.await?,
2906 replica_id: message.replica_id as ReplicaId,
2907 })
2908 }
2909 }
2910}
2911
2912impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
2913 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
2914 Self {
2915 worktree_id,
2916 path: path.as_ref().into(),
2917 }
2918 }
2919}
2920
2921impl From<lsp::CreateFileOptions> for fs::CreateOptions {
2922 fn from(options: lsp::CreateFileOptions) -> Self {
2923 Self {
2924 overwrite: options.overwrite.unwrap_or(false),
2925 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2926 }
2927 }
2928}
2929
2930impl From<lsp::RenameFileOptions> for fs::RenameOptions {
2931 fn from(options: lsp::RenameFileOptions) -> Self {
2932 Self {
2933 overwrite: options.overwrite.unwrap_or(false),
2934 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2935 }
2936 }
2937}
2938
2939impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
2940 fn from(options: lsp::DeleteFileOptions) -> Self {
2941 Self {
2942 recursive: options.recursive.unwrap_or(false),
2943 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
2944 }
2945 }
2946}
2947
2948#[cfg(test)]
2949mod tests {
2950 use super::{Event, *};
2951 use client::test::FakeHttpClient;
2952 use fs::RealFs;
2953 use futures::StreamExt;
2954 use gpui::test::subscribe;
2955 use language::{
2956 tree_sitter_rust, AnchorRangeExt, Diagnostic, LanguageConfig, LanguageRegistry,
2957 LanguageServerConfig, Point,
2958 };
2959 use lsp::Url;
2960 use serde_json::json;
2961 use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
2962 use unindent::Unindent as _;
2963 use util::test::temp_tree;
2964 use worktree::WorktreeHandle as _;
2965
2966 #[gpui::test]
2967 async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
2968 let dir = temp_tree(json!({
2969 "root": {
2970 "apple": "",
2971 "banana": {
2972 "carrot": {
2973 "date": "",
2974 "endive": "",
2975 }
2976 },
2977 "fennel": {
2978 "grape": "",
2979 }
2980 }
2981 }));
2982
2983 let root_link_path = dir.path().join("root_link");
2984 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
2985 unix::fs::symlink(
2986 &dir.path().join("root/fennel"),
2987 &dir.path().join("root/finnochio"),
2988 )
2989 .unwrap();
2990
2991 let project = Project::test(Arc::new(RealFs), &mut cx);
2992
2993 let (tree, _) = project
2994 .update(&mut cx, |project, cx| {
2995 project.find_or_create_local_worktree(&root_link_path, false, cx)
2996 })
2997 .await
2998 .unwrap();
2999
3000 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3001 .await;
3002 cx.read(|cx| {
3003 let tree = tree.read(cx);
3004 assert_eq!(tree.file_count(), 5);
3005 assert_eq!(
3006 tree.inode_for_path("fennel/grape"),
3007 tree.inode_for_path("finnochio/grape")
3008 );
3009 });
3010
3011 let cancel_flag = Default::default();
3012 let results = project
3013 .read_with(&cx, |project, cx| {
3014 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
3015 })
3016 .await;
3017 assert_eq!(
3018 results
3019 .into_iter()
3020 .map(|result| result.path)
3021 .collect::<Vec<Arc<Path>>>(),
3022 vec![
3023 PathBuf::from("banana/carrot/date").into(),
3024 PathBuf::from("banana/carrot/endive").into(),
3025 ]
3026 );
3027 }
3028
3029 #[gpui::test]
3030 async fn test_language_server_diagnostics(mut cx: gpui::TestAppContext) {
3031 let (language_server_config, mut fake_server) = LanguageServerConfig::fake(&cx).await;
3032 let progress_token = language_server_config
3033 .disk_based_diagnostics_progress_token
3034 .clone()
3035 .unwrap();
3036
3037 let mut languages = LanguageRegistry::new();
3038 languages.add(Arc::new(Language::new(
3039 LanguageConfig {
3040 name: "Rust".to_string(),
3041 path_suffixes: vec!["rs".to_string()],
3042 language_server: Some(language_server_config),
3043 ..Default::default()
3044 },
3045 Some(tree_sitter_rust::language()),
3046 )));
3047
3048 let dir = temp_tree(json!({
3049 "a.rs": "fn a() { A }",
3050 "b.rs": "const y: i32 = 1",
3051 }));
3052
3053 let http_client = FakeHttpClient::with_404_response();
3054 let client = Client::new(http_client.clone());
3055 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3056
3057 let project = cx.update(|cx| {
3058 Project::local(
3059 client,
3060 user_store,
3061 Arc::new(languages),
3062 Arc::new(RealFs),
3063 cx,
3064 )
3065 });
3066
3067 let (tree, _) = project
3068 .update(&mut cx, |project, cx| {
3069 project.find_or_create_local_worktree(dir.path(), false, cx)
3070 })
3071 .await
3072 .unwrap();
3073 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3074
3075 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3076 .await;
3077
3078 // Cause worktree to start the fake language server
3079 let _buffer = project
3080 .update(&mut cx, |project, cx| {
3081 project.open_buffer(
3082 ProjectPath {
3083 worktree_id,
3084 path: Path::new("b.rs").into(),
3085 },
3086 cx,
3087 )
3088 })
3089 .await
3090 .unwrap();
3091
3092 let mut events = subscribe(&project, &mut cx);
3093
3094 fake_server.start_progress(&progress_token).await;
3095 assert_eq!(
3096 events.next().await.unwrap(),
3097 Event::DiskBasedDiagnosticsStarted
3098 );
3099
3100 fake_server.start_progress(&progress_token).await;
3101 fake_server.end_progress(&progress_token).await;
3102 fake_server.start_progress(&progress_token).await;
3103
3104 fake_server
3105 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
3106 uri: Url::from_file_path(dir.path().join("a.rs")).unwrap(),
3107 version: None,
3108 diagnostics: vec![lsp::Diagnostic {
3109 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3110 severity: Some(lsp::DiagnosticSeverity::ERROR),
3111 message: "undefined variable 'A'".to_string(),
3112 ..Default::default()
3113 }],
3114 })
3115 .await;
3116 assert_eq!(
3117 events.next().await.unwrap(),
3118 Event::DiagnosticsUpdated(ProjectPath {
3119 worktree_id,
3120 path: Arc::from(Path::new("a.rs"))
3121 })
3122 );
3123
3124 fake_server.end_progress(&progress_token).await;
3125 fake_server.end_progress(&progress_token).await;
3126 assert_eq!(
3127 events.next().await.unwrap(),
3128 Event::DiskBasedDiagnosticsUpdated
3129 );
3130 assert_eq!(
3131 events.next().await.unwrap(),
3132 Event::DiskBasedDiagnosticsFinished
3133 );
3134
3135 let buffer = project
3136 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3137 .await
3138 .unwrap();
3139
3140 buffer.read_with(&cx, |buffer, _| {
3141 let snapshot = buffer.snapshot();
3142 let diagnostics = snapshot
3143 .diagnostics_in_range::<_, Point>(0..buffer.len())
3144 .collect::<Vec<_>>();
3145 assert_eq!(
3146 diagnostics,
3147 &[DiagnosticEntry {
3148 range: Point::new(0, 9)..Point::new(0, 10),
3149 diagnostic: Diagnostic {
3150 severity: lsp::DiagnosticSeverity::ERROR,
3151 message: "undefined variable 'A'".to_string(),
3152 group_id: 0,
3153 is_primary: true,
3154 ..Default::default()
3155 }
3156 }]
3157 )
3158 });
3159 }
3160
3161 #[gpui::test]
3162 async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
3163 let dir = temp_tree(json!({
3164 "root": {
3165 "dir1": {},
3166 "dir2": {
3167 "dir3": {}
3168 }
3169 }
3170 }));
3171
3172 let project = Project::test(Arc::new(RealFs), &mut cx);
3173 let (tree, _) = project
3174 .update(&mut cx, |project, cx| {
3175 project.find_or_create_local_worktree(&dir.path(), false, cx)
3176 })
3177 .await
3178 .unwrap();
3179
3180 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3181 .await;
3182
3183 let cancel_flag = Default::default();
3184 let results = project
3185 .read_with(&cx, |project, cx| {
3186 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
3187 })
3188 .await;
3189
3190 assert!(results.is_empty());
3191 }
3192
3193 #[gpui::test]
3194 async fn test_definition(mut cx: gpui::TestAppContext) {
3195 let (language_server_config, mut fake_server) = LanguageServerConfig::fake(&cx).await;
3196
3197 let mut languages = LanguageRegistry::new();
3198 languages.add(Arc::new(Language::new(
3199 LanguageConfig {
3200 name: "Rust".to_string(),
3201 path_suffixes: vec!["rs".to_string()],
3202 language_server: Some(language_server_config),
3203 ..Default::default()
3204 },
3205 Some(tree_sitter_rust::language()),
3206 )));
3207
3208 let dir = temp_tree(json!({
3209 "a.rs": "const fn a() { A }",
3210 "b.rs": "const y: i32 = crate::a()",
3211 }));
3212 let dir_path = dir.path().to_path_buf();
3213
3214 let http_client = FakeHttpClient::with_404_response();
3215 let client = Client::new(http_client.clone());
3216 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3217 let project = cx.update(|cx| {
3218 Project::local(
3219 client,
3220 user_store,
3221 Arc::new(languages),
3222 Arc::new(RealFs),
3223 cx,
3224 )
3225 });
3226
3227 let (tree, _) = project
3228 .update(&mut cx, |project, cx| {
3229 project.find_or_create_local_worktree(dir.path().join("b.rs"), false, cx)
3230 })
3231 .await
3232 .unwrap();
3233 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3234 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3235 .await;
3236
3237 let buffer = project
3238 .update(&mut cx, |project, cx| {
3239 project.open_buffer(
3240 ProjectPath {
3241 worktree_id,
3242 path: Path::new("").into(),
3243 },
3244 cx,
3245 )
3246 })
3247 .await
3248 .unwrap();
3249
3250 fake_server.handle_request::<lsp::request::GotoDefinition, _>(move |params| {
3251 let params = params.text_document_position_params;
3252 assert_eq!(
3253 params.text_document.uri.to_file_path().unwrap(),
3254 dir_path.join("b.rs")
3255 );
3256 assert_eq!(params.position, lsp::Position::new(0, 22));
3257
3258 Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
3259 lsp::Url::from_file_path(dir_path.join("a.rs")).unwrap(),
3260 lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3261 )))
3262 });
3263
3264 let mut definitions = project
3265 .update(&mut cx, |project, cx| project.definition(&buffer, 22, cx))
3266 .await
3267 .unwrap();
3268
3269 assert_eq!(definitions.len(), 1);
3270 let definition = definitions.pop().unwrap();
3271 cx.update(|cx| {
3272 let target_buffer = definition.target_buffer.read(cx);
3273 assert_eq!(
3274 target_buffer
3275 .file()
3276 .unwrap()
3277 .as_local()
3278 .unwrap()
3279 .abs_path(cx),
3280 dir.path().join("a.rs")
3281 );
3282 assert_eq!(definition.target_range.to_offset(target_buffer), 9..10);
3283 assert_eq!(
3284 list_worktrees(&project, cx),
3285 [
3286 (dir.path().join("b.rs"), false),
3287 (dir.path().join("a.rs"), true)
3288 ]
3289 );
3290
3291 drop(definition);
3292 });
3293 cx.read(|cx| {
3294 assert_eq!(
3295 list_worktrees(&project, cx),
3296 [(dir.path().join("b.rs"), false)]
3297 );
3298 });
3299
3300 fn list_worktrees(project: &ModelHandle<Project>, cx: &AppContext) -> Vec<(PathBuf, bool)> {
3301 project
3302 .read(cx)
3303 .worktrees(cx)
3304 .map(|worktree| {
3305 let worktree = worktree.read(cx);
3306 (
3307 worktree.as_local().unwrap().abs_path().to_path_buf(),
3308 worktree.is_weak(),
3309 )
3310 })
3311 .collect::<Vec<_>>()
3312 }
3313 }
3314
3315 #[gpui::test]
3316 async fn test_save_file(mut cx: gpui::TestAppContext) {
3317 let fs = Arc::new(FakeFs::new(cx.background()));
3318 fs.insert_tree(
3319 "/dir",
3320 json!({
3321 "file1": "the old contents",
3322 }),
3323 )
3324 .await;
3325
3326 let project = Project::test(fs.clone(), &mut cx);
3327 let worktree_id = project
3328 .update(&mut cx, |p, cx| {
3329 p.find_or_create_local_worktree("/dir", false, cx)
3330 })
3331 .await
3332 .unwrap()
3333 .0
3334 .read_with(&cx, |tree, _| tree.id());
3335
3336 let buffer = project
3337 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3338 .await
3339 .unwrap();
3340 buffer
3341 .update(&mut cx, |buffer, cx| {
3342 assert_eq!(buffer.text(), "the old contents");
3343 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3344 buffer.save(cx)
3345 })
3346 .await
3347 .unwrap();
3348
3349 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3350 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3351 }
3352
3353 #[gpui::test]
3354 async fn test_save_in_single_file_worktree(mut cx: gpui::TestAppContext) {
3355 let fs = Arc::new(FakeFs::new(cx.background()));
3356 fs.insert_tree(
3357 "/dir",
3358 json!({
3359 "file1": "the old contents",
3360 }),
3361 )
3362 .await;
3363
3364 let project = Project::test(fs.clone(), &mut cx);
3365 let worktree_id = project
3366 .update(&mut cx, |p, cx| {
3367 p.find_or_create_local_worktree("/dir/file1", false, cx)
3368 })
3369 .await
3370 .unwrap()
3371 .0
3372 .read_with(&cx, |tree, _| tree.id());
3373
3374 let buffer = project
3375 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
3376 .await
3377 .unwrap();
3378 buffer
3379 .update(&mut cx, |buffer, cx| {
3380 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3381 buffer.save(cx)
3382 })
3383 .await
3384 .unwrap();
3385
3386 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3387 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3388 }
3389
3390 #[gpui::test(retries = 5)]
3391 async fn test_rescan_and_remote_updates(mut cx: gpui::TestAppContext) {
3392 let dir = temp_tree(json!({
3393 "a": {
3394 "file1": "",
3395 "file2": "",
3396 "file3": "",
3397 },
3398 "b": {
3399 "c": {
3400 "file4": "",
3401 "file5": "",
3402 }
3403 }
3404 }));
3405
3406 let project = Project::test(Arc::new(RealFs), &mut cx);
3407 let rpc = project.read_with(&cx, |p, _| p.client.clone());
3408
3409 let (tree, _) = project
3410 .update(&mut cx, |p, cx| {
3411 p.find_or_create_local_worktree(dir.path(), false, cx)
3412 })
3413 .await
3414 .unwrap();
3415 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3416
3417 let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
3418 let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
3419 async move { buffer.await.unwrap() }
3420 };
3421 let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
3422 tree.read_with(cx, |tree, _| {
3423 tree.entry_for_path(path)
3424 .expect(&format!("no entry for path {}", path))
3425 .id
3426 })
3427 };
3428
3429 let buffer2 = buffer_for_path("a/file2", &mut cx).await;
3430 let buffer3 = buffer_for_path("a/file3", &mut cx).await;
3431 let buffer4 = buffer_for_path("b/c/file4", &mut cx).await;
3432 let buffer5 = buffer_for_path("b/c/file5", &mut cx).await;
3433
3434 let file2_id = id_for_path("a/file2", &cx);
3435 let file3_id = id_for_path("a/file3", &cx);
3436 let file4_id = id_for_path("b/c/file4", &cx);
3437
3438 // Wait for the initial scan.
3439 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3440 .await;
3441
3442 // Create a remote copy of this worktree.
3443 let initial_snapshot = tree.read_with(&cx, |tree, _| tree.snapshot());
3444 let (remote, load_task) = cx.update(|cx| {
3445 Worktree::remote(
3446 1,
3447 1,
3448 initial_snapshot.to_proto(&Default::default(), Default::default()),
3449 rpc.clone(),
3450 cx,
3451 )
3452 });
3453 load_task.await;
3454
3455 cx.read(|cx| {
3456 assert!(!buffer2.read(cx).is_dirty());
3457 assert!(!buffer3.read(cx).is_dirty());
3458 assert!(!buffer4.read(cx).is_dirty());
3459 assert!(!buffer5.read(cx).is_dirty());
3460 });
3461
3462 // Rename and delete files and directories.
3463 tree.flush_fs_events(&cx).await;
3464 std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
3465 std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
3466 std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
3467 std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
3468 tree.flush_fs_events(&cx).await;
3469
3470 let expected_paths = vec![
3471 "a",
3472 "a/file1",
3473 "a/file2.new",
3474 "b",
3475 "d",
3476 "d/file3",
3477 "d/file4",
3478 ];
3479
3480 cx.read(|app| {
3481 assert_eq!(
3482 tree.read(app)
3483 .paths()
3484 .map(|p| p.to_str().unwrap())
3485 .collect::<Vec<_>>(),
3486 expected_paths
3487 );
3488
3489 assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
3490 assert_eq!(id_for_path("d/file3", &cx), file3_id);
3491 assert_eq!(id_for_path("d/file4", &cx), file4_id);
3492
3493 assert_eq!(
3494 buffer2.read(app).file().unwrap().path().as_ref(),
3495 Path::new("a/file2.new")
3496 );
3497 assert_eq!(
3498 buffer3.read(app).file().unwrap().path().as_ref(),
3499 Path::new("d/file3")
3500 );
3501 assert_eq!(
3502 buffer4.read(app).file().unwrap().path().as_ref(),
3503 Path::new("d/file4")
3504 );
3505 assert_eq!(
3506 buffer5.read(app).file().unwrap().path().as_ref(),
3507 Path::new("b/c/file5")
3508 );
3509
3510 assert!(!buffer2.read(app).file().unwrap().is_deleted());
3511 assert!(!buffer3.read(app).file().unwrap().is_deleted());
3512 assert!(!buffer4.read(app).file().unwrap().is_deleted());
3513 assert!(buffer5.read(app).file().unwrap().is_deleted());
3514 });
3515
3516 // Update the remote worktree. Check that it becomes consistent with the
3517 // local worktree.
3518 remote.update(&mut cx, |remote, cx| {
3519 let update_message =
3520 tree.read(cx)
3521 .snapshot()
3522 .build_update(&initial_snapshot, 1, 1, true);
3523 remote
3524 .as_remote_mut()
3525 .unwrap()
3526 .snapshot
3527 .apply_remote_update(update_message)
3528 .unwrap();
3529
3530 assert_eq!(
3531 remote
3532 .paths()
3533 .map(|p| p.to_str().unwrap())
3534 .collect::<Vec<_>>(),
3535 expected_paths
3536 );
3537 });
3538 }
3539
3540 #[gpui::test]
3541 async fn test_buffer_deduping(mut cx: gpui::TestAppContext) {
3542 let fs = Arc::new(FakeFs::new(cx.background()));
3543 fs.insert_tree(
3544 "/the-dir",
3545 json!({
3546 "a.txt": "a-contents",
3547 "b.txt": "b-contents",
3548 }),
3549 )
3550 .await;
3551
3552 let project = Project::test(fs.clone(), &mut cx);
3553 let worktree_id = project
3554 .update(&mut cx, |p, cx| {
3555 p.find_or_create_local_worktree("/the-dir", false, cx)
3556 })
3557 .await
3558 .unwrap()
3559 .0
3560 .read_with(&cx, |tree, _| tree.id());
3561
3562 // Spawn multiple tasks to open paths, repeating some paths.
3563 let (buffer_a_1, buffer_b, buffer_a_2) = project.update(&mut cx, |p, cx| {
3564 (
3565 p.open_buffer((worktree_id, "a.txt"), cx),
3566 p.open_buffer((worktree_id, "b.txt"), cx),
3567 p.open_buffer((worktree_id, "a.txt"), cx),
3568 )
3569 });
3570
3571 let buffer_a_1 = buffer_a_1.await.unwrap();
3572 let buffer_a_2 = buffer_a_2.await.unwrap();
3573 let buffer_b = buffer_b.await.unwrap();
3574 assert_eq!(buffer_a_1.read_with(&cx, |b, _| b.text()), "a-contents");
3575 assert_eq!(buffer_b.read_with(&cx, |b, _| b.text()), "b-contents");
3576
3577 // There is only one buffer per path.
3578 let buffer_a_id = buffer_a_1.id();
3579 assert_eq!(buffer_a_2.id(), buffer_a_id);
3580
3581 // Open the same path again while it is still open.
3582 drop(buffer_a_1);
3583 let buffer_a_3 = project
3584 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3585 .await
3586 .unwrap();
3587
3588 // There's still only one buffer per path.
3589 assert_eq!(buffer_a_3.id(), buffer_a_id);
3590 }
3591
3592 #[gpui::test]
3593 async fn test_buffer_is_dirty(mut cx: gpui::TestAppContext) {
3594 use std::fs;
3595
3596 let dir = temp_tree(json!({
3597 "file1": "abc",
3598 "file2": "def",
3599 "file3": "ghi",
3600 }));
3601
3602 let project = Project::test(Arc::new(RealFs), &mut cx);
3603 let (worktree, _) = project
3604 .update(&mut cx, |p, cx| {
3605 p.find_or_create_local_worktree(dir.path(), false, cx)
3606 })
3607 .await
3608 .unwrap();
3609 let worktree_id = worktree.read_with(&cx, |worktree, _| worktree.id());
3610
3611 worktree.flush_fs_events(&cx).await;
3612 worktree
3613 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
3614 .await;
3615
3616 let buffer1 = project
3617 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3618 .await
3619 .unwrap();
3620 let events = Rc::new(RefCell::new(Vec::new()));
3621
3622 // initially, the buffer isn't dirty.
3623 buffer1.update(&mut cx, |buffer, cx| {
3624 cx.subscribe(&buffer1, {
3625 let events = events.clone();
3626 move |_, _, event, _| events.borrow_mut().push(event.clone())
3627 })
3628 .detach();
3629
3630 assert!(!buffer.is_dirty());
3631 assert!(events.borrow().is_empty());
3632
3633 buffer.edit(vec![1..2], "", cx);
3634 });
3635
3636 // after the first edit, the buffer is dirty, and emits a dirtied event.
3637 buffer1.update(&mut cx, |buffer, cx| {
3638 assert!(buffer.text() == "ac");
3639 assert!(buffer.is_dirty());
3640 assert_eq!(
3641 *events.borrow(),
3642 &[language::Event::Edited, language::Event::Dirtied]
3643 );
3644 events.borrow_mut().clear();
3645 buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
3646 });
3647
3648 // after saving, the buffer is not dirty, and emits a saved event.
3649 buffer1.update(&mut cx, |buffer, cx| {
3650 assert!(!buffer.is_dirty());
3651 assert_eq!(*events.borrow(), &[language::Event::Saved]);
3652 events.borrow_mut().clear();
3653
3654 buffer.edit(vec![1..1], "B", cx);
3655 buffer.edit(vec![2..2], "D", cx);
3656 });
3657
3658 // after editing again, the buffer is dirty, and emits another dirty event.
3659 buffer1.update(&mut cx, |buffer, cx| {
3660 assert!(buffer.text() == "aBDc");
3661 assert!(buffer.is_dirty());
3662 assert_eq!(
3663 *events.borrow(),
3664 &[
3665 language::Event::Edited,
3666 language::Event::Dirtied,
3667 language::Event::Edited,
3668 ],
3669 );
3670 events.borrow_mut().clear();
3671
3672 // TODO - currently, after restoring the buffer to its
3673 // previously-saved state, the is still considered dirty.
3674 buffer.edit([1..3], "", cx);
3675 assert!(buffer.text() == "ac");
3676 assert!(buffer.is_dirty());
3677 });
3678
3679 assert_eq!(*events.borrow(), &[language::Event::Edited]);
3680
3681 // When a file is deleted, the buffer is considered dirty.
3682 let events = Rc::new(RefCell::new(Vec::new()));
3683 let buffer2 = project
3684 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
3685 .await
3686 .unwrap();
3687 buffer2.update(&mut cx, |_, cx| {
3688 cx.subscribe(&buffer2, {
3689 let events = events.clone();
3690 move |_, _, event, _| events.borrow_mut().push(event.clone())
3691 })
3692 .detach();
3693 });
3694
3695 fs::remove_file(dir.path().join("file2")).unwrap();
3696 buffer2.condition(&cx, |b, _| b.is_dirty()).await;
3697 assert_eq!(
3698 *events.borrow(),
3699 &[language::Event::Dirtied, language::Event::FileHandleChanged]
3700 );
3701
3702 // When a file is already dirty when deleted, we don't emit a Dirtied event.
3703 let events = Rc::new(RefCell::new(Vec::new()));
3704 let buffer3 = project
3705 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
3706 .await
3707 .unwrap();
3708 buffer3.update(&mut cx, |_, cx| {
3709 cx.subscribe(&buffer3, {
3710 let events = events.clone();
3711 move |_, _, event, _| events.borrow_mut().push(event.clone())
3712 })
3713 .detach();
3714 });
3715
3716 worktree.flush_fs_events(&cx).await;
3717 buffer3.update(&mut cx, |buffer, cx| {
3718 buffer.edit(Some(0..0), "x", cx);
3719 });
3720 events.borrow_mut().clear();
3721 fs::remove_file(dir.path().join("file3")).unwrap();
3722 buffer3
3723 .condition(&cx, |_, _| !events.borrow().is_empty())
3724 .await;
3725 assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
3726 cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
3727 }
3728
3729 #[gpui::test]
3730 async fn test_buffer_file_changes_on_disk(mut cx: gpui::TestAppContext) {
3731 use std::fs;
3732
3733 let initial_contents = "aaa\nbbbbb\nc\n";
3734 let dir = temp_tree(json!({ "the-file": initial_contents }));
3735
3736 let project = Project::test(Arc::new(RealFs), &mut cx);
3737 let (worktree, _) = project
3738 .update(&mut cx, |p, cx| {
3739 p.find_or_create_local_worktree(dir.path(), false, cx)
3740 })
3741 .await
3742 .unwrap();
3743 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
3744
3745 worktree
3746 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
3747 .await;
3748
3749 let abs_path = dir.path().join("the-file");
3750 let buffer = project
3751 .update(&mut cx, |p, cx| {
3752 p.open_buffer((worktree_id, "the-file"), cx)
3753 })
3754 .await
3755 .unwrap();
3756
3757 // TODO
3758 // Add a cursor on each row.
3759 // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
3760 // assert!(!buffer.is_dirty());
3761 // buffer.add_selection_set(
3762 // &(0..3)
3763 // .map(|row| Selection {
3764 // id: row as usize,
3765 // start: Point::new(row, 1),
3766 // end: Point::new(row, 1),
3767 // reversed: false,
3768 // goal: SelectionGoal::None,
3769 // })
3770 // .collect::<Vec<_>>(),
3771 // cx,
3772 // )
3773 // });
3774
3775 // Change the file on disk, adding two new lines of text, and removing
3776 // one line.
3777 buffer.read_with(&cx, |buffer, _| {
3778 assert!(!buffer.is_dirty());
3779 assert!(!buffer.has_conflict());
3780 });
3781 let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
3782 fs::write(&abs_path, new_contents).unwrap();
3783
3784 // Because the buffer was not modified, it is reloaded from disk. Its
3785 // contents are edited according to the diff between the old and new
3786 // file contents.
3787 buffer
3788 .condition(&cx, |buffer, _| buffer.text() == new_contents)
3789 .await;
3790
3791 buffer.update(&mut cx, |buffer, _| {
3792 assert_eq!(buffer.text(), new_contents);
3793 assert!(!buffer.is_dirty());
3794 assert!(!buffer.has_conflict());
3795
3796 // TODO
3797 // let cursor_positions = buffer
3798 // .selection_set(selection_set_id)
3799 // .unwrap()
3800 // .selections::<Point>(&*buffer)
3801 // .map(|selection| {
3802 // assert_eq!(selection.start, selection.end);
3803 // selection.start
3804 // })
3805 // .collect::<Vec<_>>();
3806 // assert_eq!(
3807 // cursor_positions,
3808 // [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
3809 // );
3810 });
3811
3812 // Modify the buffer
3813 buffer.update(&mut cx, |buffer, cx| {
3814 buffer.edit(vec![0..0], " ", cx);
3815 assert!(buffer.is_dirty());
3816 assert!(!buffer.has_conflict());
3817 });
3818
3819 // Change the file on disk again, adding blank lines to the beginning.
3820 fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
3821
3822 // Because the buffer is modified, it doesn't reload from disk, but is
3823 // marked as having a conflict.
3824 buffer
3825 .condition(&cx, |buffer, _| buffer.has_conflict())
3826 .await;
3827 }
3828
3829 #[gpui::test]
3830 async fn test_grouped_diagnostics(mut cx: gpui::TestAppContext) {
3831 let fs = Arc::new(FakeFs::new(cx.background()));
3832 fs.insert_tree(
3833 "/the-dir",
3834 json!({
3835 "a.rs": "
3836 fn foo(mut v: Vec<usize>) {
3837 for x in &v {
3838 v.push(1);
3839 }
3840 }
3841 "
3842 .unindent(),
3843 }),
3844 )
3845 .await;
3846
3847 let project = Project::test(fs.clone(), &mut cx);
3848 let (worktree, _) = project
3849 .update(&mut cx, |p, cx| {
3850 p.find_or_create_local_worktree("/the-dir", false, cx)
3851 })
3852 .await
3853 .unwrap();
3854 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
3855
3856 let buffer = project
3857 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3858 .await
3859 .unwrap();
3860
3861 let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
3862 let message = lsp::PublishDiagnosticsParams {
3863 uri: buffer_uri.clone(),
3864 diagnostics: vec![
3865 lsp::Diagnostic {
3866 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3867 severity: Some(DiagnosticSeverity::WARNING),
3868 message: "error 1".to_string(),
3869 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3870 location: lsp::Location {
3871 uri: buffer_uri.clone(),
3872 range: lsp::Range::new(
3873 lsp::Position::new(1, 8),
3874 lsp::Position::new(1, 9),
3875 ),
3876 },
3877 message: "error 1 hint 1".to_string(),
3878 }]),
3879 ..Default::default()
3880 },
3881 lsp::Diagnostic {
3882 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3883 severity: Some(DiagnosticSeverity::HINT),
3884 message: "error 1 hint 1".to_string(),
3885 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3886 location: lsp::Location {
3887 uri: buffer_uri.clone(),
3888 range: lsp::Range::new(
3889 lsp::Position::new(1, 8),
3890 lsp::Position::new(1, 9),
3891 ),
3892 },
3893 message: "original diagnostic".to_string(),
3894 }]),
3895 ..Default::default()
3896 },
3897 lsp::Diagnostic {
3898 range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
3899 severity: Some(DiagnosticSeverity::ERROR),
3900 message: "error 2".to_string(),
3901 related_information: Some(vec![
3902 lsp::DiagnosticRelatedInformation {
3903 location: lsp::Location {
3904 uri: buffer_uri.clone(),
3905 range: lsp::Range::new(
3906 lsp::Position::new(1, 13),
3907 lsp::Position::new(1, 15),
3908 ),
3909 },
3910 message: "error 2 hint 1".to_string(),
3911 },
3912 lsp::DiagnosticRelatedInformation {
3913 location: lsp::Location {
3914 uri: buffer_uri.clone(),
3915 range: lsp::Range::new(
3916 lsp::Position::new(1, 13),
3917 lsp::Position::new(1, 15),
3918 ),
3919 },
3920 message: "error 2 hint 2".to_string(),
3921 },
3922 ]),
3923 ..Default::default()
3924 },
3925 lsp::Diagnostic {
3926 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3927 severity: Some(DiagnosticSeverity::HINT),
3928 message: "error 2 hint 1".to_string(),
3929 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3930 location: lsp::Location {
3931 uri: buffer_uri.clone(),
3932 range: lsp::Range::new(
3933 lsp::Position::new(2, 8),
3934 lsp::Position::new(2, 17),
3935 ),
3936 },
3937 message: "original diagnostic".to_string(),
3938 }]),
3939 ..Default::default()
3940 },
3941 lsp::Diagnostic {
3942 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3943 severity: Some(DiagnosticSeverity::HINT),
3944 message: "error 2 hint 2".to_string(),
3945 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3946 location: lsp::Location {
3947 uri: buffer_uri.clone(),
3948 range: lsp::Range::new(
3949 lsp::Position::new(2, 8),
3950 lsp::Position::new(2, 17),
3951 ),
3952 },
3953 message: "original diagnostic".to_string(),
3954 }]),
3955 ..Default::default()
3956 },
3957 ],
3958 version: None,
3959 };
3960
3961 project
3962 .update(&mut cx, |p, cx| {
3963 p.update_diagnostics(message, &Default::default(), cx)
3964 })
3965 .unwrap();
3966 let buffer = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3967
3968 assert_eq!(
3969 buffer
3970 .diagnostics_in_range::<_, Point>(0..buffer.len())
3971 .collect::<Vec<_>>(),
3972 &[
3973 DiagnosticEntry {
3974 range: Point::new(1, 8)..Point::new(1, 9),
3975 diagnostic: Diagnostic {
3976 severity: DiagnosticSeverity::WARNING,
3977 message: "error 1".to_string(),
3978 group_id: 0,
3979 is_primary: true,
3980 ..Default::default()
3981 }
3982 },
3983 DiagnosticEntry {
3984 range: Point::new(1, 8)..Point::new(1, 9),
3985 diagnostic: Diagnostic {
3986 severity: DiagnosticSeverity::HINT,
3987 message: "error 1 hint 1".to_string(),
3988 group_id: 0,
3989 is_primary: false,
3990 ..Default::default()
3991 }
3992 },
3993 DiagnosticEntry {
3994 range: Point::new(1, 13)..Point::new(1, 15),
3995 diagnostic: Diagnostic {
3996 severity: DiagnosticSeverity::HINT,
3997 message: "error 2 hint 1".to_string(),
3998 group_id: 1,
3999 is_primary: false,
4000 ..Default::default()
4001 }
4002 },
4003 DiagnosticEntry {
4004 range: Point::new(1, 13)..Point::new(1, 15),
4005 diagnostic: Diagnostic {
4006 severity: DiagnosticSeverity::HINT,
4007 message: "error 2 hint 2".to_string(),
4008 group_id: 1,
4009 is_primary: false,
4010 ..Default::default()
4011 }
4012 },
4013 DiagnosticEntry {
4014 range: Point::new(2, 8)..Point::new(2, 17),
4015 diagnostic: Diagnostic {
4016 severity: DiagnosticSeverity::ERROR,
4017 message: "error 2".to_string(),
4018 group_id: 1,
4019 is_primary: true,
4020 ..Default::default()
4021 }
4022 }
4023 ]
4024 );
4025
4026 assert_eq!(
4027 buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
4028 &[
4029 DiagnosticEntry {
4030 range: Point::new(1, 8)..Point::new(1, 9),
4031 diagnostic: Diagnostic {
4032 severity: DiagnosticSeverity::WARNING,
4033 message: "error 1".to_string(),
4034 group_id: 0,
4035 is_primary: true,
4036 ..Default::default()
4037 }
4038 },
4039 DiagnosticEntry {
4040 range: Point::new(1, 8)..Point::new(1, 9),
4041 diagnostic: Diagnostic {
4042 severity: DiagnosticSeverity::HINT,
4043 message: "error 1 hint 1".to_string(),
4044 group_id: 0,
4045 is_primary: false,
4046 ..Default::default()
4047 }
4048 },
4049 ]
4050 );
4051 assert_eq!(
4052 buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
4053 &[
4054 DiagnosticEntry {
4055 range: Point::new(1, 13)..Point::new(1, 15),
4056 diagnostic: Diagnostic {
4057 severity: DiagnosticSeverity::HINT,
4058 message: "error 2 hint 1".to_string(),
4059 group_id: 1,
4060 is_primary: false,
4061 ..Default::default()
4062 }
4063 },
4064 DiagnosticEntry {
4065 range: Point::new(1, 13)..Point::new(1, 15),
4066 diagnostic: Diagnostic {
4067 severity: DiagnosticSeverity::HINT,
4068 message: "error 2 hint 2".to_string(),
4069 group_id: 1,
4070 is_primary: false,
4071 ..Default::default()
4072 }
4073 },
4074 DiagnosticEntry {
4075 range: Point::new(2, 8)..Point::new(2, 17),
4076 diagnostic: Diagnostic {
4077 severity: DiagnosticSeverity::ERROR,
4078 message: "error 2".to_string(),
4079 group_id: 1,
4080 is_primary: true,
4081 ..Default::default()
4082 }
4083 }
4084 ]
4085 );
4086 }
4087}