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 &mut self,
2598 message: proto::ProjectTransaction,
2599 push_to_history: bool,
2600 cx: &mut ModelContext<Self>,
2601 ) -> Task<Result<ProjectTransaction>> {
2602 let mut project_transaction = ProjectTransaction::default();
2603 for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
2604 let buffer = match self.deserialize_buffer(buffer, cx) {
2605 Ok(buffer) => buffer,
2606 Err(error) => return Task::ready(Err(error)),
2607 };
2608 let transaction = match language::proto::deserialize_transaction(transaction) {
2609 Ok(transaction) => transaction,
2610 Err(error) => return Task::ready(Err(error)),
2611 };
2612 project_transaction.0.insert(buffer, transaction);
2613 }
2614
2615 cx.spawn_weak(|_, mut cx| async move {
2616 for (buffer, transaction) in &project_transaction.0 {
2617 buffer
2618 .update(&mut cx, |buffer, _| {
2619 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
2620 })
2621 .await;
2622
2623 if push_to_history {
2624 buffer.update(&mut cx, |buffer, _| {
2625 buffer.push_transaction(transaction.clone(), Instant::now());
2626 });
2627 }
2628 }
2629
2630 Ok(project_transaction)
2631 })
2632 }
2633
2634 fn serialize_buffer_for_peer(
2635 &mut self,
2636 buffer: &ModelHandle<Buffer>,
2637 peer_id: PeerId,
2638 cx: &AppContext,
2639 ) -> proto::Buffer {
2640 let buffer_id = buffer.read(cx).remote_id();
2641 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
2642 match shared_buffers.entry(buffer_id) {
2643 hash_map::Entry::Occupied(_) => proto::Buffer {
2644 variant: Some(proto::buffer::Variant::Id(buffer_id)),
2645 },
2646 hash_map::Entry::Vacant(entry) => {
2647 entry.insert(buffer.clone());
2648 proto::Buffer {
2649 variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
2650 }
2651 }
2652 }
2653 }
2654
2655 fn deserialize_buffer(
2656 &mut self,
2657 buffer: proto::Buffer,
2658 cx: &mut ModelContext<Self>,
2659 ) -> Result<ModelHandle<Buffer>> {
2660 match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
2661 proto::buffer::Variant::Id(id) => self
2662 .open_buffers
2663 .get(&(id as usize))
2664 .and_then(|buffer| buffer.upgrade(cx))
2665 .ok_or_else(|| anyhow!("no buffer exists for id {}", id)),
2666 proto::buffer::Variant::State(mut buffer) => {
2667 let mut buffer_worktree = None;
2668 let mut buffer_file = None;
2669 if let Some(file) = buffer.file.take() {
2670 let worktree_id = WorktreeId::from_proto(file.worktree_id);
2671 let worktree = self
2672 .worktree_for_id(worktree_id, cx)
2673 .ok_or_else(|| anyhow!("no worktree found for id {}", file.worktree_id))?;
2674 buffer_file = Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
2675 as Box<dyn language::File>);
2676 buffer_worktree = Some(worktree);
2677 }
2678
2679 let buffer = cx.add_model(|cx| {
2680 Buffer::from_proto(self.replica_id(), buffer, buffer_file, cx).unwrap()
2681 });
2682 self.register_buffer(&buffer, buffer_worktree.as_ref(), cx)?;
2683 Ok(buffer)
2684 }
2685 }
2686 }
2687
2688 pub fn handle_close_buffer(
2689 &mut self,
2690 envelope: TypedEnvelope<proto::CloseBuffer>,
2691 _: Arc<Client>,
2692 cx: &mut ModelContext<Self>,
2693 ) -> anyhow::Result<()> {
2694 if let Some(shared_buffers) = self.shared_buffers.get_mut(&envelope.original_sender_id()?) {
2695 shared_buffers.remove(&envelope.payload.buffer_id);
2696 cx.notify();
2697 }
2698 Ok(())
2699 }
2700
2701 pub fn handle_buffer_saved(
2702 &mut self,
2703 envelope: TypedEnvelope<proto::BufferSaved>,
2704 _: Arc<Client>,
2705 cx: &mut ModelContext<Self>,
2706 ) -> Result<()> {
2707 let payload = envelope.payload.clone();
2708 let buffer = self
2709 .open_buffers
2710 .get(&(payload.buffer_id as usize))
2711 .and_then(|buffer| buffer.upgrade(cx));
2712 if let Some(buffer) = buffer {
2713 buffer.update(cx, |buffer, cx| {
2714 let version = payload.version.try_into()?;
2715 let mtime = payload
2716 .mtime
2717 .ok_or_else(|| anyhow!("missing mtime"))?
2718 .into();
2719 buffer.did_save(version, mtime, None, cx);
2720 Result::<_, anyhow::Error>::Ok(())
2721 })?;
2722 }
2723 Ok(())
2724 }
2725
2726 pub fn handle_buffer_reloaded(
2727 &mut self,
2728 envelope: TypedEnvelope<proto::BufferReloaded>,
2729 _: Arc<Client>,
2730 cx: &mut ModelContext<Self>,
2731 ) -> Result<()> {
2732 let payload = envelope.payload.clone();
2733 let buffer = self
2734 .open_buffers
2735 .get(&(payload.buffer_id as usize))
2736 .and_then(|buffer| buffer.upgrade(cx));
2737 if let Some(buffer) = buffer {
2738 buffer.update(cx, |buffer, cx| {
2739 let version = payload.version.try_into()?;
2740 let mtime = payload
2741 .mtime
2742 .ok_or_else(|| anyhow!("missing mtime"))?
2743 .into();
2744 buffer.did_reload(version, mtime, cx);
2745 Result::<_, anyhow::Error>::Ok(())
2746 })?;
2747 }
2748 Ok(())
2749 }
2750
2751 pub fn match_paths<'a>(
2752 &self,
2753 query: &'a str,
2754 include_ignored: bool,
2755 smart_case: bool,
2756 max_results: usize,
2757 cancel_flag: &'a AtomicBool,
2758 cx: &AppContext,
2759 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
2760 let worktrees = self
2761 .worktrees(cx)
2762 .filter(|worktree| !worktree.read(cx).is_weak())
2763 .collect::<Vec<_>>();
2764 let include_root_name = worktrees.len() > 1;
2765 let candidate_sets = worktrees
2766 .into_iter()
2767 .map(|worktree| CandidateSet {
2768 snapshot: worktree.read(cx).snapshot(),
2769 include_ignored,
2770 include_root_name,
2771 })
2772 .collect::<Vec<_>>();
2773
2774 let background = cx.background().clone();
2775 async move {
2776 fuzzy::match_paths(
2777 candidate_sets.as_slice(),
2778 query,
2779 smart_case,
2780 max_results,
2781 cancel_flag,
2782 background,
2783 )
2784 .await
2785 }
2786 }
2787}
2788
2789impl WorktreeHandle {
2790 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
2791 match self {
2792 WorktreeHandle::Strong(handle) => Some(handle.clone()),
2793 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
2794 }
2795 }
2796}
2797
2798struct CandidateSet {
2799 snapshot: Snapshot,
2800 include_ignored: bool,
2801 include_root_name: bool,
2802}
2803
2804impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
2805 type Candidates = CandidateSetIter<'a>;
2806
2807 fn id(&self) -> usize {
2808 self.snapshot.id().to_usize()
2809 }
2810
2811 fn len(&self) -> usize {
2812 if self.include_ignored {
2813 self.snapshot.file_count()
2814 } else {
2815 self.snapshot.visible_file_count()
2816 }
2817 }
2818
2819 fn prefix(&self) -> Arc<str> {
2820 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
2821 self.snapshot.root_name().into()
2822 } else if self.include_root_name {
2823 format!("{}/", self.snapshot.root_name()).into()
2824 } else {
2825 "".into()
2826 }
2827 }
2828
2829 fn candidates(&'a self, start: usize) -> Self::Candidates {
2830 CandidateSetIter {
2831 traversal: self.snapshot.files(self.include_ignored, start),
2832 }
2833 }
2834}
2835
2836struct CandidateSetIter<'a> {
2837 traversal: Traversal<'a>,
2838}
2839
2840impl<'a> Iterator for CandidateSetIter<'a> {
2841 type Item = PathMatchCandidate<'a>;
2842
2843 fn next(&mut self) -> Option<Self::Item> {
2844 self.traversal.next().map(|entry| {
2845 if let EntryKind::File(char_bag) = entry.kind {
2846 PathMatchCandidate {
2847 path: &entry.path,
2848 char_bag,
2849 }
2850 } else {
2851 unreachable!()
2852 }
2853 })
2854 }
2855}
2856
2857impl Entity for Project {
2858 type Event = Event;
2859
2860 fn release(&mut self, _: &mut gpui::MutableAppContext) {
2861 match &self.client_state {
2862 ProjectClientState::Local { remote_id_rx, .. } => {
2863 if let Some(project_id) = *remote_id_rx.borrow() {
2864 self.client
2865 .send(proto::UnregisterProject { project_id })
2866 .log_err();
2867 }
2868 }
2869 ProjectClientState::Remote { remote_id, .. } => {
2870 self.client
2871 .send(proto::LeaveProject {
2872 project_id: *remote_id,
2873 })
2874 .log_err();
2875 }
2876 }
2877 }
2878
2879 fn app_will_quit(
2880 &mut self,
2881 _: &mut MutableAppContext,
2882 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
2883 use futures::FutureExt;
2884
2885 let shutdown_futures = self
2886 .language_servers
2887 .drain()
2888 .filter_map(|(_, server)| server.shutdown())
2889 .collect::<Vec<_>>();
2890 Some(
2891 async move {
2892 futures::future::join_all(shutdown_futures).await;
2893 }
2894 .boxed(),
2895 )
2896 }
2897}
2898
2899impl Collaborator {
2900 fn from_proto(
2901 message: proto::Collaborator,
2902 user_store: &ModelHandle<UserStore>,
2903 cx: &mut AsyncAppContext,
2904 ) -> impl Future<Output = Result<Self>> {
2905 let user = user_store.update(cx, |user_store, cx| {
2906 user_store.fetch_user(message.user_id, cx)
2907 });
2908
2909 async move {
2910 Ok(Self {
2911 peer_id: PeerId(message.peer_id),
2912 user: user.await?,
2913 replica_id: message.replica_id as ReplicaId,
2914 })
2915 }
2916 }
2917}
2918
2919impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
2920 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
2921 Self {
2922 worktree_id,
2923 path: path.as_ref().into(),
2924 }
2925 }
2926}
2927
2928impl From<lsp::CreateFileOptions> for fs::CreateOptions {
2929 fn from(options: lsp::CreateFileOptions) -> Self {
2930 Self {
2931 overwrite: options.overwrite.unwrap_or(false),
2932 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2933 }
2934 }
2935}
2936
2937impl From<lsp::RenameFileOptions> for fs::RenameOptions {
2938 fn from(options: lsp::RenameFileOptions) -> Self {
2939 Self {
2940 overwrite: options.overwrite.unwrap_or(false),
2941 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2942 }
2943 }
2944}
2945
2946impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
2947 fn from(options: lsp::DeleteFileOptions) -> Self {
2948 Self {
2949 recursive: options.recursive.unwrap_or(false),
2950 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
2951 }
2952 }
2953}
2954
2955#[cfg(test)]
2956mod tests {
2957 use super::{Event, *};
2958 use client::test::FakeHttpClient;
2959 use fs::RealFs;
2960 use futures::StreamExt;
2961 use gpui::test::subscribe;
2962 use language::{
2963 tree_sitter_rust, AnchorRangeExt, Diagnostic, LanguageConfig, LanguageRegistry,
2964 LanguageServerConfig, Point,
2965 };
2966 use lsp::Url;
2967 use serde_json::json;
2968 use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
2969 use unindent::Unindent as _;
2970 use util::test::temp_tree;
2971 use worktree::WorktreeHandle as _;
2972
2973 #[gpui::test]
2974 async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
2975 let dir = temp_tree(json!({
2976 "root": {
2977 "apple": "",
2978 "banana": {
2979 "carrot": {
2980 "date": "",
2981 "endive": "",
2982 }
2983 },
2984 "fennel": {
2985 "grape": "",
2986 }
2987 }
2988 }));
2989
2990 let root_link_path = dir.path().join("root_link");
2991 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
2992 unix::fs::symlink(
2993 &dir.path().join("root/fennel"),
2994 &dir.path().join("root/finnochio"),
2995 )
2996 .unwrap();
2997
2998 let project = Project::test(Arc::new(RealFs), &mut cx);
2999
3000 let (tree, _) = project
3001 .update(&mut cx, |project, cx| {
3002 project.find_or_create_local_worktree(&root_link_path, false, cx)
3003 })
3004 .await
3005 .unwrap();
3006
3007 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3008 .await;
3009 cx.read(|cx| {
3010 let tree = tree.read(cx);
3011 assert_eq!(tree.file_count(), 5);
3012 assert_eq!(
3013 tree.inode_for_path("fennel/grape"),
3014 tree.inode_for_path("finnochio/grape")
3015 );
3016 });
3017
3018 let cancel_flag = Default::default();
3019 let results = project
3020 .read_with(&cx, |project, cx| {
3021 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
3022 })
3023 .await;
3024 assert_eq!(
3025 results
3026 .into_iter()
3027 .map(|result| result.path)
3028 .collect::<Vec<Arc<Path>>>(),
3029 vec![
3030 PathBuf::from("banana/carrot/date").into(),
3031 PathBuf::from("banana/carrot/endive").into(),
3032 ]
3033 );
3034 }
3035
3036 #[gpui::test]
3037 async fn test_language_server_diagnostics(mut cx: gpui::TestAppContext) {
3038 let (language_server_config, mut fake_server) = LanguageServerConfig::fake(&cx).await;
3039 let progress_token = language_server_config
3040 .disk_based_diagnostics_progress_token
3041 .clone()
3042 .unwrap();
3043
3044 let mut languages = LanguageRegistry::new();
3045 languages.add(Arc::new(Language::new(
3046 LanguageConfig {
3047 name: "Rust".to_string(),
3048 path_suffixes: vec!["rs".to_string()],
3049 language_server: Some(language_server_config),
3050 ..Default::default()
3051 },
3052 Some(tree_sitter_rust::language()),
3053 )));
3054
3055 let dir = temp_tree(json!({
3056 "a.rs": "fn a() { A }",
3057 "b.rs": "const y: i32 = 1",
3058 }));
3059
3060 let http_client = FakeHttpClient::with_404_response();
3061 let client = Client::new(http_client.clone());
3062 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3063
3064 let project = cx.update(|cx| {
3065 Project::local(
3066 client,
3067 user_store,
3068 Arc::new(languages),
3069 Arc::new(RealFs),
3070 cx,
3071 )
3072 });
3073
3074 let (tree, _) = project
3075 .update(&mut cx, |project, cx| {
3076 project.find_or_create_local_worktree(dir.path(), false, cx)
3077 })
3078 .await
3079 .unwrap();
3080 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3081
3082 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3083 .await;
3084
3085 // Cause worktree to start the fake language server
3086 let _buffer = project
3087 .update(&mut cx, |project, cx| {
3088 project.open_buffer(
3089 ProjectPath {
3090 worktree_id,
3091 path: Path::new("b.rs").into(),
3092 },
3093 cx,
3094 )
3095 })
3096 .await
3097 .unwrap();
3098
3099 let mut events = subscribe(&project, &mut cx);
3100
3101 fake_server.start_progress(&progress_token).await;
3102 assert_eq!(
3103 events.next().await.unwrap(),
3104 Event::DiskBasedDiagnosticsStarted
3105 );
3106
3107 fake_server.start_progress(&progress_token).await;
3108 fake_server.end_progress(&progress_token).await;
3109 fake_server.start_progress(&progress_token).await;
3110
3111 fake_server
3112 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
3113 uri: Url::from_file_path(dir.path().join("a.rs")).unwrap(),
3114 version: None,
3115 diagnostics: vec![lsp::Diagnostic {
3116 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3117 severity: Some(lsp::DiagnosticSeverity::ERROR),
3118 message: "undefined variable 'A'".to_string(),
3119 ..Default::default()
3120 }],
3121 })
3122 .await;
3123 assert_eq!(
3124 events.next().await.unwrap(),
3125 Event::DiagnosticsUpdated(ProjectPath {
3126 worktree_id,
3127 path: Arc::from(Path::new("a.rs"))
3128 })
3129 );
3130
3131 fake_server.end_progress(&progress_token).await;
3132 fake_server.end_progress(&progress_token).await;
3133 assert_eq!(
3134 events.next().await.unwrap(),
3135 Event::DiskBasedDiagnosticsUpdated
3136 );
3137 assert_eq!(
3138 events.next().await.unwrap(),
3139 Event::DiskBasedDiagnosticsFinished
3140 );
3141
3142 let buffer = project
3143 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3144 .await
3145 .unwrap();
3146
3147 buffer.read_with(&cx, |buffer, _| {
3148 let snapshot = buffer.snapshot();
3149 let diagnostics = snapshot
3150 .diagnostics_in_range::<_, Point>(0..buffer.len())
3151 .collect::<Vec<_>>();
3152 assert_eq!(
3153 diagnostics,
3154 &[DiagnosticEntry {
3155 range: Point::new(0, 9)..Point::new(0, 10),
3156 diagnostic: Diagnostic {
3157 severity: lsp::DiagnosticSeverity::ERROR,
3158 message: "undefined variable 'A'".to_string(),
3159 group_id: 0,
3160 is_primary: true,
3161 ..Default::default()
3162 }
3163 }]
3164 )
3165 });
3166 }
3167
3168 #[gpui::test]
3169 async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
3170 let dir = temp_tree(json!({
3171 "root": {
3172 "dir1": {},
3173 "dir2": {
3174 "dir3": {}
3175 }
3176 }
3177 }));
3178
3179 let project = Project::test(Arc::new(RealFs), &mut cx);
3180 let (tree, _) = project
3181 .update(&mut cx, |project, cx| {
3182 project.find_or_create_local_worktree(&dir.path(), false, cx)
3183 })
3184 .await
3185 .unwrap();
3186
3187 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3188 .await;
3189
3190 let cancel_flag = Default::default();
3191 let results = project
3192 .read_with(&cx, |project, cx| {
3193 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
3194 })
3195 .await;
3196
3197 assert!(results.is_empty());
3198 }
3199
3200 #[gpui::test]
3201 async fn test_definition(mut cx: gpui::TestAppContext) {
3202 let (language_server_config, mut fake_server) = LanguageServerConfig::fake(&cx).await;
3203
3204 let mut languages = LanguageRegistry::new();
3205 languages.add(Arc::new(Language::new(
3206 LanguageConfig {
3207 name: "Rust".to_string(),
3208 path_suffixes: vec!["rs".to_string()],
3209 language_server: Some(language_server_config),
3210 ..Default::default()
3211 },
3212 Some(tree_sitter_rust::language()),
3213 )));
3214
3215 let dir = temp_tree(json!({
3216 "a.rs": "const fn a() { A }",
3217 "b.rs": "const y: i32 = crate::a()",
3218 }));
3219 let dir_path = dir.path().to_path_buf();
3220
3221 let http_client = FakeHttpClient::with_404_response();
3222 let client = Client::new(http_client.clone());
3223 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3224 let project = cx.update(|cx| {
3225 Project::local(
3226 client,
3227 user_store,
3228 Arc::new(languages),
3229 Arc::new(RealFs),
3230 cx,
3231 )
3232 });
3233
3234 let (tree, _) = project
3235 .update(&mut cx, |project, cx| {
3236 project.find_or_create_local_worktree(dir.path().join("b.rs"), false, cx)
3237 })
3238 .await
3239 .unwrap();
3240 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3241 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3242 .await;
3243
3244 let buffer = project
3245 .update(&mut cx, |project, cx| {
3246 project.open_buffer(
3247 ProjectPath {
3248 worktree_id,
3249 path: Path::new("").into(),
3250 },
3251 cx,
3252 )
3253 })
3254 .await
3255 .unwrap();
3256
3257 fake_server.handle_request::<lsp::request::GotoDefinition, _>(move |params| {
3258 let params = params.text_document_position_params;
3259 assert_eq!(
3260 params.text_document.uri.to_file_path().unwrap(),
3261 dir_path.join("b.rs")
3262 );
3263 assert_eq!(params.position, lsp::Position::new(0, 22));
3264
3265 Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
3266 lsp::Url::from_file_path(dir_path.join("a.rs")).unwrap(),
3267 lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3268 )))
3269 });
3270
3271 let mut definitions = project
3272 .update(&mut cx, |project, cx| project.definition(&buffer, 22, cx))
3273 .await
3274 .unwrap();
3275
3276 assert_eq!(definitions.len(), 1);
3277 let definition = definitions.pop().unwrap();
3278 cx.update(|cx| {
3279 let target_buffer = definition.target_buffer.read(cx);
3280 assert_eq!(
3281 target_buffer
3282 .file()
3283 .unwrap()
3284 .as_local()
3285 .unwrap()
3286 .abs_path(cx),
3287 dir.path().join("a.rs")
3288 );
3289 assert_eq!(definition.target_range.to_offset(target_buffer), 9..10);
3290 assert_eq!(
3291 list_worktrees(&project, cx),
3292 [
3293 (dir.path().join("b.rs"), false),
3294 (dir.path().join("a.rs"), true)
3295 ]
3296 );
3297
3298 drop(definition);
3299 });
3300 cx.read(|cx| {
3301 assert_eq!(
3302 list_worktrees(&project, cx),
3303 [(dir.path().join("b.rs"), false)]
3304 );
3305 });
3306
3307 fn list_worktrees(project: &ModelHandle<Project>, cx: &AppContext) -> Vec<(PathBuf, bool)> {
3308 project
3309 .read(cx)
3310 .worktrees(cx)
3311 .map(|worktree| {
3312 let worktree = worktree.read(cx);
3313 (
3314 worktree.as_local().unwrap().abs_path().to_path_buf(),
3315 worktree.is_weak(),
3316 )
3317 })
3318 .collect::<Vec<_>>()
3319 }
3320 }
3321
3322 #[gpui::test]
3323 async fn test_save_file(mut cx: gpui::TestAppContext) {
3324 let fs = Arc::new(FakeFs::new(cx.background()));
3325 fs.insert_tree(
3326 "/dir",
3327 json!({
3328 "file1": "the old contents",
3329 }),
3330 )
3331 .await;
3332
3333 let project = Project::test(fs.clone(), &mut cx);
3334 let worktree_id = project
3335 .update(&mut cx, |p, cx| {
3336 p.find_or_create_local_worktree("/dir", false, cx)
3337 })
3338 .await
3339 .unwrap()
3340 .0
3341 .read_with(&cx, |tree, _| tree.id());
3342
3343 let buffer = project
3344 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3345 .await
3346 .unwrap();
3347 buffer
3348 .update(&mut cx, |buffer, cx| {
3349 assert_eq!(buffer.text(), "the old contents");
3350 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3351 buffer.save(cx)
3352 })
3353 .await
3354 .unwrap();
3355
3356 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3357 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3358 }
3359
3360 #[gpui::test]
3361 async fn test_save_in_single_file_worktree(mut cx: gpui::TestAppContext) {
3362 let fs = Arc::new(FakeFs::new(cx.background()));
3363 fs.insert_tree(
3364 "/dir",
3365 json!({
3366 "file1": "the old contents",
3367 }),
3368 )
3369 .await;
3370
3371 let project = Project::test(fs.clone(), &mut cx);
3372 let worktree_id = project
3373 .update(&mut cx, |p, cx| {
3374 p.find_or_create_local_worktree("/dir/file1", false, cx)
3375 })
3376 .await
3377 .unwrap()
3378 .0
3379 .read_with(&cx, |tree, _| tree.id());
3380
3381 let buffer = project
3382 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
3383 .await
3384 .unwrap();
3385 buffer
3386 .update(&mut cx, |buffer, cx| {
3387 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3388 buffer.save(cx)
3389 })
3390 .await
3391 .unwrap();
3392
3393 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3394 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3395 }
3396
3397 #[gpui::test(retries = 5)]
3398 async fn test_rescan_and_remote_updates(mut cx: gpui::TestAppContext) {
3399 let dir = temp_tree(json!({
3400 "a": {
3401 "file1": "",
3402 "file2": "",
3403 "file3": "",
3404 },
3405 "b": {
3406 "c": {
3407 "file4": "",
3408 "file5": "",
3409 }
3410 }
3411 }));
3412
3413 let project = Project::test(Arc::new(RealFs), &mut cx);
3414 let rpc = project.read_with(&cx, |p, _| p.client.clone());
3415
3416 let (tree, _) = project
3417 .update(&mut cx, |p, cx| {
3418 p.find_or_create_local_worktree(dir.path(), false, cx)
3419 })
3420 .await
3421 .unwrap();
3422 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3423
3424 let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
3425 let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
3426 async move { buffer.await.unwrap() }
3427 };
3428 let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
3429 tree.read_with(cx, |tree, _| {
3430 tree.entry_for_path(path)
3431 .expect(&format!("no entry for path {}", path))
3432 .id
3433 })
3434 };
3435
3436 let buffer2 = buffer_for_path("a/file2", &mut cx).await;
3437 let buffer3 = buffer_for_path("a/file3", &mut cx).await;
3438 let buffer4 = buffer_for_path("b/c/file4", &mut cx).await;
3439 let buffer5 = buffer_for_path("b/c/file5", &mut cx).await;
3440
3441 let file2_id = id_for_path("a/file2", &cx);
3442 let file3_id = id_for_path("a/file3", &cx);
3443 let file4_id = id_for_path("b/c/file4", &cx);
3444
3445 // Wait for the initial scan.
3446 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3447 .await;
3448
3449 // Create a remote copy of this worktree.
3450 let initial_snapshot = tree.read_with(&cx, |tree, _| tree.snapshot());
3451 let (remote, load_task) = cx.update(|cx| {
3452 Worktree::remote(
3453 1,
3454 1,
3455 initial_snapshot.to_proto(&Default::default(), Default::default()),
3456 rpc.clone(),
3457 cx,
3458 )
3459 });
3460 load_task.await;
3461
3462 cx.read(|cx| {
3463 assert!(!buffer2.read(cx).is_dirty());
3464 assert!(!buffer3.read(cx).is_dirty());
3465 assert!(!buffer4.read(cx).is_dirty());
3466 assert!(!buffer5.read(cx).is_dirty());
3467 });
3468
3469 // Rename and delete files and directories.
3470 tree.flush_fs_events(&cx).await;
3471 std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
3472 std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
3473 std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
3474 std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
3475 tree.flush_fs_events(&cx).await;
3476
3477 let expected_paths = vec![
3478 "a",
3479 "a/file1",
3480 "a/file2.new",
3481 "b",
3482 "d",
3483 "d/file3",
3484 "d/file4",
3485 ];
3486
3487 cx.read(|app| {
3488 assert_eq!(
3489 tree.read(app)
3490 .paths()
3491 .map(|p| p.to_str().unwrap())
3492 .collect::<Vec<_>>(),
3493 expected_paths
3494 );
3495
3496 assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
3497 assert_eq!(id_for_path("d/file3", &cx), file3_id);
3498 assert_eq!(id_for_path("d/file4", &cx), file4_id);
3499
3500 assert_eq!(
3501 buffer2.read(app).file().unwrap().path().as_ref(),
3502 Path::new("a/file2.new")
3503 );
3504 assert_eq!(
3505 buffer3.read(app).file().unwrap().path().as_ref(),
3506 Path::new("d/file3")
3507 );
3508 assert_eq!(
3509 buffer4.read(app).file().unwrap().path().as_ref(),
3510 Path::new("d/file4")
3511 );
3512 assert_eq!(
3513 buffer5.read(app).file().unwrap().path().as_ref(),
3514 Path::new("b/c/file5")
3515 );
3516
3517 assert!(!buffer2.read(app).file().unwrap().is_deleted());
3518 assert!(!buffer3.read(app).file().unwrap().is_deleted());
3519 assert!(!buffer4.read(app).file().unwrap().is_deleted());
3520 assert!(buffer5.read(app).file().unwrap().is_deleted());
3521 });
3522
3523 // Update the remote worktree. Check that it becomes consistent with the
3524 // local worktree.
3525 remote.update(&mut cx, |remote, cx| {
3526 let update_message =
3527 tree.read(cx)
3528 .snapshot()
3529 .build_update(&initial_snapshot, 1, 1, true);
3530 remote
3531 .as_remote_mut()
3532 .unwrap()
3533 .snapshot
3534 .apply_remote_update(update_message)
3535 .unwrap();
3536
3537 assert_eq!(
3538 remote
3539 .paths()
3540 .map(|p| p.to_str().unwrap())
3541 .collect::<Vec<_>>(),
3542 expected_paths
3543 );
3544 });
3545 }
3546
3547 #[gpui::test]
3548 async fn test_buffer_deduping(mut cx: gpui::TestAppContext) {
3549 let fs = Arc::new(FakeFs::new(cx.background()));
3550 fs.insert_tree(
3551 "/the-dir",
3552 json!({
3553 "a.txt": "a-contents",
3554 "b.txt": "b-contents",
3555 }),
3556 )
3557 .await;
3558
3559 let project = Project::test(fs.clone(), &mut cx);
3560 let worktree_id = project
3561 .update(&mut cx, |p, cx| {
3562 p.find_or_create_local_worktree("/the-dir", false, cx)
3563 })
3564 .await
3565 .unwrap()
3566 .0
3567 .read_with(&cx, |tree, _| tree.id());
3568
3569 // Spawn multiple tasks to open paths, repeating some paths.
3570 let (buffer_a_1, buffer_b, buffer_a_2) = project.update(&mut cx, |p, cx| {
3571 (
3572 p.open_buffer((worktree_id, "a.txt"), cx),
3573 p.open_buffer((worktree_id, "b.txt"), cx),
3574 p.open_buffer((worktree_id, "a.txt"), cx),
3575 )
3576 });
3577
3578 let buffer_a_1 = buffer_a_1.await.unwrap();
3579 let buffer_a_2 = buffer_a_2.await.unwrap();
3580 let buffer_b = buffer_b.await.unwrap();
3581 assert_eq!(buffer_a_1.read_with(&cx, |b, _| b.text()), "a-contents");
3582 assert_eq!(buffer_b.read_with(&cx, |b, _| b.text()), "b-contents");
3583
3584 // There is only one buffer per path.
3585 let buffer_a_id = buffer_a_1.id();
3586 assert_eq!(buffer_a_2.id(), buffer_a_id);
3587
3588 // Open the same path again while it is still open.
3589 drop(buffer_a_1);
3590 let buffer_a_3 = project
3591 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3592 .await
3593 .unwrap();
3594
3595 // There's still only one buffer per path.
3596 assert_eq!(buffer_a_3.id(), buffer_a_id);
3597 }
3598
3599 #[gpui::test]
3600 async fn test_buffer_is_dirty(mut cx: gpui::TestAppContext) {
3601 use std::fs;
3602
3603 let dir = temp_tree(json!({
3604 "file1": "abc",
3605 "file2": "def",
3606 "file3": "ghi",
3607 }));
3608
3609 let project = Project::test(Arc::new(RealFs), &mut cx);
3610 let (worktree, _) = project
3611 .update(&mut cx, |p, cx| {
3612 p.find_or_create_local_worktree(dir.path(), false, cx)
3613 })
3614 .await
3615 .unwrap();
3616 let worktree_id = worktree.read_with(&cx, |worktree, _| worktree.id());
3617
3618 worktree.flush_fs_events(&cx).await;
3619 worktree
3620 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
3621 .await;
3622
3623 let buffer1 = project
3624 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3625 .await
3626 .unwrap();
3627 let events = Rc::new(RefCell::new(Vec::new()));
3628
3629 // initially, the buffer isn't dirty.
3630 buffer1.update(&mut cx, |buffer, cx| {
3631 cx.subscribe(&buffer1, {
3632 let events = events.clone();
3633 move |_, _, event, _| events.borrow_mut().push(event.clone())
3634 })
3635 .detach();
3636
3637 assert!(!buffer.is_dirty());
3638 assert!(events.borrow().is_empty());
3639
3640 buffer.edit(vec![1..2], "", cx);
3641 });
3642
3643 // after the first edit, the buffer is dirty, and emits a dirtied event.
3644 buffer1.update(&mut cx, |buffer, cx| {
3645 assert!(buffer.text() == "ac");
3646 assert!(buffer.is_dirty());
3647 assert_eq!(
3648 *events.borrow(),
3649 &[language::Event::Edited, language::Event::Dirtied]
3650 );
3651 events.borrow_mut().clear();
3652 buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
3653 });
3654
3655 // after saving, the buffer is not dirty, and emits a saved event.
3656 buffer1.update(&mut cx, |buffer, cx| {
3657 assert!(!buffer.is_dirty());
3658 assert_eq!(*events.borrow(), &[language::Event::Saved]);
3659 events.borrow_mut().clear();
3660
3661 buffer.edit(vec![1..1], "B", cx);
3662 buffer.edit(vec![2..2], "D", cx);
3663 });
3664
3665 // after editing again, the buffer is dirty, and emits another dirty event.
3666 buffer1.update(&mut cx, |buffer, cx| {
3667 assert!(buffer.text() == "aBDc");
3668 assert!(buffer.is_dirty());
3669 assert_eq!(
3670 *events.borrow(),
3671 &[
3672 language::Event::Edited,
3673 language::Event::Dirtied,
3674 language::Event::Edited,
3675 ],
3676 );
3677 events.borrow_mut().clear();
3678
3679 // TODO - currently, after restoring the buffer to its
3680 // previously-saved state, the is still considered dirty.
3681 buffer.edit([1..3], "", cx);
3682 assert!(buffer.text() == "ac");
3683 assert!(buffer.is_dirty());
3684 });
3685
3686 assert_eq!(*events.borrow(), &[language::Event::Edited]);
3687
3688 // When a file is deleted, the buffer is considered dirty.
3689 let events = Rc::new(RefCell::new(Vec::new()));
3690 let buffer2 = project
3691 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
3692 .await
3693 .unwrap();
3694 buffer2.update(&mut cx, |_, cx| {
3695 cx.subscribe(&buffer2, {
3696 let events = events.clone();
3697 move |_, _, event, _| events.borrow_mut().push(event.clone())
3698 })
3699 .detach();
3700 });
3701
3702 fs::remove_file(dir.path().join("file2")).unwrap();
3703 buffer2.condition(&cx, |b, _| b.is_dirty()).await;
3704 assert_eq!(
3705 *events.borrow(),
3706 &[language::Event::Dirtied, language::Event::FileHandleChanged]
3707 );
3708
3709 // When a file is already dirty when deleted, we don't emit a Dirtied event.
3710 let events = Rc::new(RefCell::new(Vec::new()));
3711 let buffer3 = project
3712 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
3713 .await
3714 .unwrap();
3715 buffer3.update(&mut cx, |_, cx| {
3716 cx.subscribe(&buffer3, {
3717 let events = events.clone();
3718 move |_, _, event, _| events.borrow_mut().push(event.clone())
3719 })
3720 .detach();
3721 });
3722
3723 worktree.flush_fs_events(&cx).await;
3724 buffer3.update(&mut cx, |buffer, cx| {
3725 buffer.edit(Some(0..0), "x", cx);
3726 });
3727 events.borrow_mut().clear();
3728 fs::remove_file(dir.path().join("file3")).unwrap();
3729 buffer3
3730 .condition(&cx, |_, _| !events.borrow().is_empty())
3731 .await;
3732 assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
3733 cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
3734 }
3735
3736 #[gpui::test]
3737 async fn test_buffer_file_changes_on_disk(mut cx: gpui::TestAppContext) {
3738 use std::fs;
3739
3740 let initial_contents = "aaa\nbbbbb\nc\n";
3741 let dir = temp_tree(json!({ "the-file": initial_contents }));
3742
3743 let project = Project::test(Arc::new(RealFs), &mut cx);
3744 let (worktree, _) = project
3745 .update(&mut cx, |p, cx| {
3746 p.find_or_create_local_worktree(dir.path(), false, cx)
3747 })
3748 .await
3749 .unwrap();
3750 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
3751
3752 worktree
3753 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
3754 .await;
3755
3756 let abs_path = dir.path().join("the-file");
3757 let buffer = project
3758 .update(&mut cx, |p, cx| {
3759 p.open_buffer((worktree_id, "the-file"), cx)
3760 })
3761 .await
3762 .unwrap();
3763
3764 // TODO
3765 // Add a cursor on each row.
3766 // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
3767 // assert!(!buffer.is_dirty());
3768 // buffer.add_selection_set(
3769 // &(0..3)
3770 // .map(|row| Selection {
3771 // id: row as usize,
3772 // start: Point::new(row, 1),
3773 // end: Point::new(row, 1),
3774 // reversed: false,
3775 // goal: SelectionGoal::None,
3776 // })
3777 // .collect::<Vec<_>>(),
3778 // cx,
3779 // )
3780 // });
3781
3782 // Change the file on disk, adding two new lines of text, and removing
3783 // one line.
3784 buffer.read_with(&cx, |buffer, _| {
3785 assert!(!buffer.is_dirty());
3786 assert!(!buffer.has_conflict());
3787 });
3788 let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
3789 fs::write(&abs_path, new_contents).unwrap();
3790
3791 // Because the buffer was not modified, it is reloaded from disk. Its
3792 // contents are edited according to the diff between the old and new
3793 // file contents.
3794 buffer
3795 .condition(&cx, |buffer, _| buffer.text() == new_contents)
3796 .await;
3797
3798 buffer.update(&mut cx, |buffer, _| {
3799 assert_eq!(buffer.text(), new_contents);
3800 assert!(!buffer.is_dirty());
3801 assert!(!buffer.has_conflict());
3802
3803 // TODO
3804 // let cursor_positions = buffer
3805 // .selection_set(selection_set_id)
3806 // .unwrap()
3807 // .selections::<Point>(&*buffer)
3808 // .map(|selection| {
3809 // assert_eq!(selection.start, selection.end);
3810 // selection.start
3811 // })
3812 // .collect::<Vec<_>>();
3813 // assert_eq!(
3814 // cursor_positions,
3815 // [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
3816 // );
3817 });
3818
3819 // Modify the buffer
3820 buffer.update(&mut cx, |buffer, cx| {
3821 buffer.edit(vec![0..0], " ", cx);
3822 assert!(buffer.is_dirty());
3823 assert!(!buffer.has_conflict());
3824 });
3825
3826 // Change the file on disk again, adding blank lines to the beginning.
3827 fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
3828
3829 // Because the buffer is modified, it doesn't reload from disk, but is
3830 // marked as having a conflict.
3831 buffer
3832 .condition(&cx, |buffer, _| buffer.has_conflict())
3833 .await;
3834 }
3835
3836 #[gpui::test]
3837 async fn test_grouped_diagnostics(mut cx: gpui::TestAppContext) {
3838 let fs = Arc::new(FakeFs::new(cx.background()));
3839 fs.insert_tree(
3840 "/the-dir",
3841 json!({
3842 "a.rs": "
3843 fn foo(mut v: Vec<usize>) {
3844 for x in &v {
3845 v.push(1);
3846 }
3847 }
3848 "
3849 .unindent(),
3850 }),
3851 )
3852 .await;
3853
3854 let project = Project::test(fs.clone(), &mut cx);
3855 let (worktree, _) = project
3856 .update(&mut cx, |p, cx| {
3857 p.find_or_create_local_worktree("/the-dir", false, cx)
3858 })
3859 .await
3860 .unwrap();
3861 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
3862
3863 let buffer = project
3864 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3865 .await
3866 .unwrap();
3867
3868 let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
3869 let message = lsp::PublishDiagnosticsParams {
3870 uri: buffer_uri.clone(),
3871 diagnostics: vec![
3872 lsp::Diagnostic {
3873 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3874 severity: Some(DiagnosticSeverity::WARNING),
3875 message: "error 1".to_string(),
3876 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3877 location: lsp::Location {
3878 uri: buffer_uri.clone(),
3879 range: lsp::Range::new(
3880 lsp::Position::new(1, 8),
3881 lsp::Position::new(1, 9),
3882 ),
3883 },
3884 message: "error 1 hint 1".to_string(),
3885 }]),
3886 ..Default::default()
3887 },
3888 lsp::Diagnostic {
3889 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3890 severity: Some(DiagnosticSeverity::HINT),
3891 message: "error 1 hint 1".to_string(),
3892 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3893 location: lsp::Location {
3894 uri: buffer_uri.clone(),
3895 range: lsp::Range::new(
3896 lsp::Position::new(1, 8),
3897 lsp::Position::new(1, 9),
3898 ),
3899 },
3900 message: "original diagnostic".to_string(),
3901 }]),
3902 ..Default::default()
3903 },
3904 lsp::Diagnostic {
3905 range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
3906 severity: Some(DiagnosticSeverity::ERROR),
3907 message: "error 2".to_string(),
3908 related_information: Some(vec![
3909 lsp::DiagnosticRelatedInformation {
3910 location: lsp::Location {
3911 uri: buffer_uri.clone(),
3912 range: lsp::Range::new(
3913 lsp::Position::new(1, 13),
3914 lsp::Position::new(1, 15),
3915 ),
3916 },
3917 message: "error 2 hint 1".to_string(),
3918 },
3919 lsp::DiagnosticRelatedInformation {
3920 location: lsp::Location {
3921 uri: buffer_uri.clone(),
3922 range: lsp::Range::new(
3923 lsp::Position::new(1, 13),
3924 lsp::Position::new(1, 15),
3925 ),
3926 },
3927 message: "error 2 hint 2".to_string(),
3928 },
3929 ]),
3930 ..Default::default()
3931 },
3932 lsp::Diagnostic {
3933 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3934 severity: Some(DiagnosticSeverity::HINT),
3935 message: "error 2 hint 1".to_string(),
3936 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3937 location: lsp::Location {
3938 uri: buffer_uri.clone(),
3939 range: lsp::Range::new(
3940 lsp::Position::new(2, 8),
3941 lsp::Position::new(2, 17),
3942 ),
3943 },
3944 message: "original diagnostic".to_string(),
3945 }]),
3946 ..Default::default()
3947 },
3948 lsp::Diagnostic {
3949 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3950 severity: Some(DiagnosticSeverity::HINT),
3951 message: "error 2 hint 2".to_string(),
3952 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3953 location: lsp::Location {
3954 uri: buffer_uri.clone(),
3955 range: lsp::Range::new(
3956 lsp::Position::new(2, 8),
3957 lsp::Position::new(2, 17),
3958 ),
3959 },
3960 message: "original diagnostic".to_string(),
3961 }]),
3962 ..Default::default()
3963 },
3964 ],
3965 version: None,
3966 };
3967
3968 project
3969 .update(&mut cx, |p, cx| {
3970 p.update_diagnostics(message, &Default::default(), cx)
3971 })
3972 .unwrap();
3973 let buffer = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3974
3975 assert_eq!(
3976 buffer
3977 .diagnostics_in_range::<_, Point>(0..buffer.len())
3978 .collect::<Vec<_>>(),
3979 &[
3980 DiagnosticEntry {
3981 range: Point::new(1, 8)..Point::new(1, 9),
3982 diagnostic: Diagnostic {
3983 severity: DiagnosticSeverity::WARNING,
3984 message: "error 1".to_string(),
3985 group_id: 0,
3986 is_primary: true,
3987 ..Default::default()
3988 }
3989 },
3990 DiagnosticEntry {
3991 range: Point::new(1, 8)..Point::new(1, 9),
3992 diagnostic: Diagnostic {
3993 severity: DiagnosticSeverity::HINT,
3994 message: "error 1 hint 1".to_string(),
3995 group_id: 0,
3996 is_primary: false,
3997 ..Default::default()
3998 }
3999 },
4000 DiagnosticEntry {
4001 range: Point::new(1, 13)..Point::new(1, 15),
4002 diagnostic: Diagnostic {
4003 severity: DiagnosticSeverity::HINT,
4004 message: "error 2 hint 1".to_string(),
4005 group_id: 1,
4006 is_primary: false,
4007 ..Default::default()
4008 }
4009 },
4010 DiagnosticEntry {
4011 range: Point::new(1, 13)..Point::new(1, 15),
4012 diagnostic: Diagnostic {
4013 severity: DiagnosticSeverity::HINT,
4014 message: "error 2 hint 2".to_string(),
4015 group_id: 1,
4016 is_primary: false,
4017 ..Default::default()
4018 }
4019 },
4020 DiagnosticEntry {
4021 range: Point::new(2, 8)..Point::new(2, 17),
4022 diagnostic: Diagnostic {
4023 severity: DiagnosticSeverity::ERROR,
4024 message: "error 2".to_string(),
4025 group_id: 1,
4026 is_primary: true,
4027 ..Default::default()
4028 }
4029 }
4030 ]
4031 );
4032
4033 assert_eq!(
4034 buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
4035 &[
4036 DiagnosticEntry {
4037 range: Point::new(1, 8)..Point::new(1, 9),
4038 diagnostic: Diagnostic {
4039 severity: DiagnosticSeverity::WARNING,
4040 message: "error 1".to_string(),
4041 group_id: 0,
4042 is_primary: true,
4043 ..Default::default()
4044 }
4045 },
4046 DiagnosticEntry {
4047 range: Point::new(1, 8)..Point::new(1, 9),
4048 diagnostic: Diagnostic {
4049 severity: DiagnosticSeverity::HINT,
4050 message: "error 1 hint 1".to_string(),
4051 group_id: 0,
4052 is_primary: false,
4053 ..Default::default()
4054 }
4055 },
4056 ]
4057 );
4058 assert_eq!(
4059 buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
4060 &[
4061 DiagnosticEntry {
4062 range: Point::new(1, 13)..Point::new(1, 15),
4063 diagnostic: Diagnostic {
4064 severity: DiagnosticSeverity::HINT,
4065 message: "error 2 hint 1".to_string(),
4066 group_id: 1,
4067 is_primary: false,
4068 ..Default::default()
4069 }
4070 },
4071 DiagnosticEntry {
4072 range: Point::new(1, 13)..Point::new(1, 15),
4073 diagnostic: Diagnostic {
4074 severity: DiagnosticSeverity::HINT,
4075 message: "error 2 hint 2".to_string(),
4076 group_id: 1,
4077 is_primary: false,
4078 ..Default::default()
4079 }
4080 },
4081 DiagnosticEntry {
4082 range: Point::new(2, 8)..Point::new(2, 17),
4083 diagnostic: Diagnostic {
4084 severity: DiagnosticSeverity::ERROR,
4085 message: "error 2".to_string(),
4086 group_id: 1,
4087 is_primary: true,
4088 ..Default::default()
4089 }
4090 }
4091 ]
4092 );
4093 }
4094}