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_request(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_request(remote_id, cx, Self::handle_save_buffer),
350 client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_saved),
351 client.subscribe_to_entity_request(remote_id, cx, Self::handle_format_buffers),
352 client.subscribe_to_entity_request(remote_id, cx, Self::handle_get_completions),
353 client.subscribe_to_entity_request(
354 remote_id,
355 cx,
356 Self::handle_apply_additional_edits_for_completion,
357 ),
358 client.subscribe_to_entity_request(remote_id, cx, Self::handle_get_code_actions),
359 client.subscribe_to_entity_request(remote_id, cx, Self::handle_apply_code_action),
360 client.subscribe_to_entity_request(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 async fn handle_unshare_project(
2000 this: ModelHandle<Self>,
2001 _: TypedEnvelope<proto::UnshareProject>,
2002 _: Arc<Client>,
2003 mut cx: AsyncAppContext,
2004 ) -> Result<()> {
2005 this.update(&mut cx, |this, cx| {
2006 if let ProjectClientState::Remote {
2007 sharing_has_stopped,
2008 ..
2009 } = &mut this.client_state
2010 {
2011 *sharing_has_stopped = true;
2012 this.collaborators.clear();
2013 cx.notify();
2014 } else {
2015 unreachable!()
2016 }
2017 });
2018
2019 Ok(())
2020 }
2021
2022 async fn handle_add_collaborator(
2023 this: ModelHandle<Self>,
2024 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
2025 _: Arc<Client>,
2026 mut cx: AsyncAppContext,
2027 ) -> Result<()> {
2028 let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
2029 let collaborator = envelope
2030 .payload
2031 .collaborator
2032 .take()
2033 .ok_or_else(|| anyhow!("empty collaborator"))?;
2034
2035 let collaborator = 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
2042 Ok(())
2043 }
2044
2045 async fn handle_remove_collaborator(
2046 this: ModelHandle<Self>,
2047 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
2048 _: Arc<Client>,
2049 mut cx: AsyncAppContext,
2050 ) -> Result<()> {
2051 this.update(&mut cx, |this, cx| {
2052 let peer_id = PeerId(envelope.payload.peer_id);
2053 let replica_id = this
2054 .collaborators
2055 .remove(&peer_id)
2056 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
2057 .replica_id;
2058 this.shared_buffers.remove(&peer_id);
2059 for (_, buffer) in &this.open_buffers {
2060 if let Some(buffer) = buffer.upgrade(cx) {
2061 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
2062 }
2063 }
2064 cx.notify();
2065 Ok(())
2066 })
2067 }
2068
2069 async fn handle_share_worktree(
2070 this: ModelHandle<Self>,
2071 envelope: TypedEnvelope<proto::ShareWorktree>,
2072 client: Arc<Client>,
2073 mut cx: AsyncAppContext,
2074 ) -> Result<()> {
2075 this.update(&mut cx, |this, cx| {
2076 let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
2077 let replica_id = this.replica_id();
2078 let worktree = envelope
2079 .payload
2080 .worktree
2081 .ok_or_else(|| anyhow!("invalid worktree"))?;
2082 let (worktree, load_task) =
2083 Worktree::remote(remote_id, replica_id, worktree, client, cx);
2084 this.add_worktree(&worktree, cx);
2085 load_task.detach();
2086 Ok(())
2087 })
2088 }
2089
2090 async fn handle_unregister_worktree(
2091 this: ModelHandle<Self>,
2092 envelope: TypedEnvelope<proto::UnregisterWorktree>,
2093 _: Arc<Client>,
2094 mut cx: AsyncAppContext,
2095 ) -> Result<()> {
2096 this.update(&mut cx, |this, cx| {
2097 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2098 this.remove_worktree(worktree_id, cx);
2099 Ok(())
2100 })
2101 }
2102
2103 async fn handle_update_worktree(
2104 this: ModelHandle<Self>,
2105 envelope: TypedEnvelope<proto::UpdateWorktree>,
2106 _: Arc<Client>,
2107 mut cx: AsyncAppContext,
2108 ) -> Result<()> {
2109 this.update(&mut cx, |this, cx| {
2110 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2111 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
2112 worktree.update(cx, |worktree, cx| {
2113 let worktree = worktree.as_remote_mut().unwrap();
2114 worktree.update_from_remote(envelope, cx)
2115 })?;
2116 }
2117 Ok(())
2118 })
2119 }
2120
2121 async fn handle_update_diagnostic_summary(
2122 this: ModelHandle<Self>,
2123 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
2124 _: Arc<Client>,
2125 mut cx: AsyncAppContext,
2126 ) -> Result<()> {
2127 this.update(&mut cx, |this, cx| {
2128 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2129 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
2130 if let Some(summary) = envelope.payload.summary {
2131 let project_path = ProjectPath {
2132 worktree_id,
2133 path: Path::new(&summary.path).into(),
2134 };
2135 worktree.update(cx, |worktree, _| {
2136 worktree
2137 .as_remote_mut()
2138 .unwrap()
2139 .update_diagnostic_summary(project_path.path.clone(), &summary);
2140 });
2141 cx.emit(Event::DiagnosticsUpdated(project_path));
2142 }
2143 }
2144 Ok(())
2145 })
2146 }
2147
2148 async fn handle_disk_based_diagnostics_updating(
2149 this: ModelHandle<Self>,
2150 _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
2151 _: Arc<Client>,
2152 mut cx: AsyncAppContext,
2153 ) -> Result<()> {
2154 this.update(&mut cx, |this, cx| this.disk_based_diagnostics_started(cx));
2155 Ok(())
2156 }
2157
2158 async fn handle_disk_based_diagnostics_updated(
2159 this: ModelHandle<Self>,
2160 _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
2161 _: Arc<Client>,
2162 mut cx: AsyncAppContext,
2163 ) -> Result<()> {
2164 this.update(&mut cx, |this, cx| this.disk_based_diagnostics_finished(cx));
2165 Ok(())
2166 }
2167
2168 async fn handle_update_buffer(
2169 this: ModelHandle<Self>,
2170 envelope: TypedEnvelope<proto::UpdateBuffer>,
2171 _: Arc<Client>,
2172 mut cx: AsyncAppContext,
2173 ) -> Result<()> {
2174 this.update(&mut cx, |this, cx| {
2175 let payload = envelope.payload.clone();
2176 let buffer_id = payload.buffer_id as usize;
2177 let ops = payload
2178 .operations
2179 .into_iter()
2180 .map(|op| language::proto::deserialize_operation(op))
2181 .collect::<Result<Vec<_>, _>>()?;
2182 if let Some(buffer) = this.open_buffers.get_mut(&buffer_id) {
2183 if let Some(buffer) = buffer.upgrade(cx) {
2184 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
2185 }
2186 }
2187 Ok(())
2188 })
2189 }
2190
2191 async fn handle_update_buffer_file(
2192 this: ModelHandle<Self>,
2193 envelope: TypedEnvelope<proto::UpdateBufferFile>,
2194 _: Arc<Client>,
2195 mut cx: AsyncAppContext,
2196 ) -> Result<()> {
2197 this.update(&mut cx, |this, cx| {
2198 let payload = envelope.payload.clone();
2199 let buffer_id = payload.buffer_id as usize;
2200 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
2201 let worktree = this
2202 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
2203 .ok_or_else(|| anyhow!("no such worktree"))?;
2204 let file = File::from_proto(file, worktree.clone(), cx)?;
2205 let buffer = this
2206 .open_buffers
2207 .get_mut(&buffer_id)
2208 .and_then(|b| b.upgrade(cx))
2209 .ok_or_else(|| anyhow!("no such buffer"))?;
2210 buffer.update(cx, |buffer, cx| {
2211 buffer.file_updated(Box::new(file), cx).detach();
2212 });
2213 Ok(())
2214 })
2215 }
2216
2217 async fn handle_save_buffer(
2218 this: ModelHandle<Self>,
2219 envelope: TypedEnvelope<proto::SaveBuffer>,
2220 _: Arc<Client>,
2221 mut cx: AsyncAppContext,
2222 ) -> Result<proto::BufferSaved> {
2223 let buffer_id = envelope.payload.buffer_id;
2224 let sender_id = envelope.original_sender_id()?;
2225 let (project_id, save) = this.update(&mut cx, |this, cx| {
2226 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
2227 let buffer = this
2228 .shared_buffers
2229 .get(&sender_id)
2230 .and_then(|shared_buffers| shared_buffers.get(&buffer_id).cloned())
2231 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
2232 Ok::<_, anyhow::Error>((project_id, buffer.update(cx, |buffer, cx| buffer.save(cx))))
2233 })?;
2234
2235 let (version, mtime) = save.await?;
2236 Ok(proto::BufferSaved {
2237 project_id,
2238 buffer_id,
2239 version: (&version).into(),
2240 mtime: Some(mtime.into()),
2241 })
2242 }
2243
2244 async fn handle_format_buffers(
2245 this: ModelHandle<Self>,
2246 envelope: TypedEnvelope<proto::FormatBuffers>,
2247 _: Arc<Client>,
2248 mut cx: AsyncAppContext,
2249 ) -> Result<proto::FormatBuffersResponse> {
2250 let sender_id = envelope.original_sender_id()?;
2251 let format = this.update(&mut cx, |this, cx| {
2252 let shared_buffers = this
2253 .shared_buffers
2254 .get(&sender_id)
2255 .ok_or_else(|| anyhow!("peer has no buffers"))?;
2256 let mut buffers = HashSet::default();
2257 for buffer_id in &envelope.payload.buffer_ids {
2258 buffers.insert(
2259 shared_buffers
2260 .get(buffer_id)
2261 .cloned()
2262 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
2263 );
2264 }
2265 Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
2266 })?;
2267
2268 let project_transaction = format.await?;
2269 let project_transaction = this.update(&mut cx, |this, cx| {
2270 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
2271 });
2272 Ok(proto::FormatBuffersResponse {
2273 transaction: Some(project_transaction),
2274 })
2275 }
2276
2277 async fn handle_get_completions(
2278 this: ModelHandle<Self>,
2279 envelope: TypedEnvelope<proto::GetCompletions>,
2280 _: Arc<Client>,
2281 mut cx: AsyncAppContext,
2282 ) -> Result<proto::GetCompletionsResponse> {
2283 let sender_id = envelope.original_sender_id()?;
2284 let position = envelope
2285 .payload
2286 .position
2287 .and_then(language::proto::deserialize_anchor)
2288 .ok_or_else(|| anyhow!("invalid position"))?;
2289 let completions = this.update(&mut cx, |this, cx| {
2290 let buffer = this
2291 .shared_buffers
2292 .get(&sender_id)
2293 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2294 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2295 Ok::<_, anyhow::Error>(this.completions(&buffer, position, cx))
2296 })?;
2297
2298 Ok(proto::GetCompletionsResponse {
2299 completions: completions
2300 .await?
2301 .iter()
2302 .map(language::proto::serialize_completion)
2303 .collect(),
2304 })
2305 }
2306
2307 async fn handle_apply_additional_edits_for_completion(
2308 this: ModelHandle<Self>,
2309 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
2310 _: Arc<Client>,
2311 mut cx: AsyncAppContext,
2312 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
2313 let sender_id = envelope.original_sender_id()?;
2314 let apply_additional_edits = this.update(&mut cx, |this, cx| {
2315 let buffer = this
2316 .shared_buffers
2317 .get(&sender_id)
2318 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2319 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2320 let language = buffer.read(cx).language();
2321 let completion = language::proto::deserialize_completion(
2322 envelope
2323 .payload
2324 .completion
2325 .ok_or_else(|| anyhow!("invalid completion"))?,
2326 language,
2327 )?;
2328 Ok::<_, anyhow::Error>(
2329 this.apply_additional_edits_for_completion(buffer, completion, false, cx),
2330 )
2331 })?;
2332
2333 Ok(proto::ApplyCompletionAdditionalEditsResponse {
2334 transaction: apply_additional_edits
2335 .await?
2336 .as_ref()
2337 .map(language::proto::serialize_transaction),
2338 })
2339 }
2340
2341 async fn handle_get_code_actions(
2342 this: ModelHandle<Self>,
2343 envelope: TypedEnvelope<proto::GetCodeActions>,
2344 _: Arc<Client>,
2345 mut cx: AsyncAppContext,
2346 ) -> Result<proto::GetCodeActionsResponse> {
2347 let sender_id = envelope.original_sender_id()?;
2348 let position = envelope
2349 .payload
2350 .position
2351 .and_then(language::proto::deserialize_anchor)
2352 .ok_or_else(|| anyhow!("invalid position"))?;
2353 let code_actions = this.update(&mut cx, |this, cx| {
2354 let buffer = this
2355 .shared_buffers
2356 .get(&sender_id)
2357 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2358 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2359 Ok::<_, anyhow::Error>(this.code_actions(&buffer, position, cx))
2360 })?;
2361
2362 Ok(proto::GetCodeActionsResponse {
2363 actions: code_actions
2364 .await?
2365 .iter()
2366 .map(language::proto::serialize_code_action)
2367 .collect(),
2368 })
2369 }
2370
2371 async fn handle_apply_code_action(
2372 this: ModelHandle<Self>,
2373 envelope: TypedEnvelope<proto::ApplyCodeAction>,
2374 _: Arc<Client>,
2375 mut cx: AsyncAppContext,
2376 ) -> Result<proto::ApplyCodeActionResponse> {
2377 let sender_id = envelope.original_sender_id()?;
2378 let action = language::proto::deserialize_code_action(
2379 envelope
2380 .payload
2381 .action
2382 .ok_or_else(|| anyhow!("invalid action"))?,
2383 )?;
2384 let apply_code_action = this.update(&mut cx, |this, cx| {
2385 let buffer = this
2386 .shared_buffers
2387 .get(&sender_id)
2388 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2389 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2390 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
2391 })?;
2392
2393 let project_transaction = apply_code_action.await?;
2394 let project_transaction = this.update(&mut cx, |this, cx| {
2395 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
2396 });
2397 Ok(proto::ApplyCodeActionResponse {
2398 transaction: Some(project_transaction),
2399 })
2400 }
2401
2402 async fn handle_get_definition(
2403 this: ModelHandle<Self>,
2404 envelope: TypedEnvelope<proto::GetDefinition>,
2405 _: Arc<Client>,
2406 mut cx: AsyncAppContext,
2407 ) -> Result<proto::GetDefinitionResponse> {
2408 let sender_id = envelope.original_sender_id()?;
2409 let position = envelope
2410 .payload
2411 .position
2412 .and_then(deserialize_anchor)
2413 .ok_or_else(|| anyhow!("invalid position"))?;
2414 let definitions = this.update(&mut cx, |this, cx| {
2415 let source_buffer = this
2416 .shared_buffers
2417 .get(&sender_id)
2418 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2419 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2420 if source_buffer.read(cx).can_resolve(&position) {
2421 Ok(this.definition(&source_buffer, position, cx))
2422 } else {
2423 Err(anyhow!("cannot resolve position"))
2424 }
2425 })?;
2426
2427 let definitions = definitions.await?;
2428
2429 this.update(&mut cx, |this, cx| {
2430 let mut response = proto::GetDefinitionResponse {
2431 definitions: Default::default(),
2432 };
2433 for definition in definitions {
2434 let buffer =
2435 this.serialize_buffer_for_peer(&definition.target_buffer, sender_id, cx);
2436 response.definitions.push(proto::Definition {
2437 target_start: Some(serialize_anchor(&definition.target_range.start)),
2438 target_end: Some(serialize_anchor(&definition.target_range.end)),
2439 buffer: Some(buffer),
2440 });
2441 }
2442 Ok(response)
2443 })
2444 }
2445
2446 async fn handle_open_buffer(
2447 this: ModelHandle<Self>,
2448 envelope: TypedEnvelope<proto::OpenBuffer>,
2449 _: Arc<Client>,
2450 mut cx: AsyncAppContext,
2451 ) -> anyhow::Result<proto::OpenBufferResponse> {
2452 let peer_id = envelope.original_sender_id()?;
2453 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2454 let open_buffer = this.update(&mut cx, |this, cx| {
2455 this.open_buffer(
2456 ProjectPath {
2457 worktree_id,
2458 path: PathBuf::from(envelope.payload.path).into(),
2459 },
2460 cx,
2461 )
2462 });
2463
2464 let buffer = open_buffer.await?;
2465 this.update(&mut cx, |this, cx| {
2466 Ok(proto::OpenBufferResponse {
2467 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
2468 })
2469 })
2470 }
2471
2472 fn serialize_project_transaction_for_peer(
2473 &mut self,
2474 project_transaction: ProjectTransaction,
2475 peer_id: PeerId,
2476 cx: &AppContext,
2477 ) -> proto::ProjectTransaction {
2478 let mut serialized_transaction = proto::ProjectTransaction {
2479 buffers: Default::default(),
2480 transactions: Default::default(),
2481 };
2482 for (buffer, transaction) in project_transaction.0 {
2483 serialized_transaction
2484 .buffers
2485 .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
2486 serialized_transaction
2487 .transactions
2488 .push(language::proto::serialize_transaction(&transaction));
2489 }
2490 serialized_transaction
2491 }
2492
2493 fn deserialize_project_transaction(
2494 &mut self,
2495 message: proto::ProjectTransaction,
2496 push_to_history: bool,
2497 cx: &mut ModelContext<Self>,
2498 ) -> Task<Result<ProjectTransaction>> {
2499 let mut project_transaction = ProjectTransaction::default();
2500 for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
2501 let buffer = match self.deserialize_buffer(buffer, cx) {
2502 Ok(buffer) => buffer,
2503 Err(error) => return Task::ready(Err(error)),
2504 };
2505 let transaction = match language::proto::deserialize_transaction(transaction) {
2506 Ok(transaction) => transaction,
2507 Err(error) => return Task::ready(Err(error)),
2508 };
2509 project_transaction.0.insert(buffer, transaction);
2510 }
2511
2512 cx.spawn_weak(|_, mut cx| async move {
2513 for (buffer, transaction) in &project_transaction.0 {
2514 buffer
2515 .update(&mut cx, |buffer, _| {
2516 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
2517 })
2518 .await;
2519
2520 if push_to_history {
2521 buffer.update(&mut cx, |buffer, _| {
2522 buffer.push_transaction(transaction.clone(), Instant::now());
2523 });
2524 }
2525 }
2526
2527 Ok(project_transaction)
2528 })
2529 }
2530
2531 fn serialize_buffer_for_peer(
2532 &mut self,
2533 buffer: &ModelHandle<Buffer>,
2534 peer_id: PeerId,
2535 cx: &AppContext,
2536 ) -> proto::Buffer {
2537 let buffer_id = buffer.read(cx).remote_id();
2538 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
2539 match shared_buffers.entry(buffer_id) {
2540 hash_map::Entry::Occupied(_) => proto::Buffer {
2541 variant: Some(proto::buffer::Variant::Id(buffer_id)),
2542 },
2543 hash_map::Entry::Vacant(entry) => {
2544 entry.insert(buffer.clone());
2545 proto::Buffer {
2546 variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
2547 }
2548 }
2549 }
2550 }
2551
2552 fn deserialize_buffer(
2553 &mut self,
2554 buffer: proto::Buffer,
2555 cx: &mut ModelContext<Self>,
2556 ) -> Result<ModelHandle<Buffer>> {
2557 match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
2558 proto::buffer::Variant::Id(id) => self
2559 .open_buffers
2560 .get(&(id as usize))
2561 .and_then(|buffer| buffer.upgrade(cx))
2562 .ok_or_else(|| anyhow!("no buffer exists for id {}", id)),
2563 proto::buffer::Variant::State(mut buffer) => {
2564 let mut buffer_worktree = None;
2565 let mut buffer_file = None;
2566 if let Some(file) = buffer.file.take() {
2567 let worktree_id = WorktreeId::from_proto(file.worktree_id);
2568 let worktree = self
2569 .worktree_for_id(worktree_id, cx)
2570 .ok_or_else(|| anyhow!("no worktree found for id {}", file.worktree_id))?;
2571 buffer_file = Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
2572 as Box<dyn language::File>);
2573 buffer_worktree = Some(worktree);
2574 }
2575
2576 let buffer = cx.add_model(|cx| {
2577 Buffer::from_proto(self.replica_id(), buffer, buffer_file, cx).unwrap()
2578 });
2579 self.register_buffer(&buffer, buffer_worktree.as_ref(), cx)?;
2580 Ok(buffer)
2581 }
2582 }
2583 }
2584
2585 async fn handle_close_buffer(
2586 this: ModelHandle<Self>,
2587 envelope: TypedEnvelope<proto::CloseBuffer>,
2588 _: Arc<Client>,
2589 mut cx: AsyncAppContext,
2590 ) -> anyhow::Result<()> {
2591 this.update(&mut cx, |this, cx| {
2592 if let Some(shared_buffers) =
2593 this.shared_buffers.get_mut(&envelope.original_sender_id()?)
2594 {
2595 shared_buffers.remove(&envelope.payload.buffer_id);
2596 cx.notify();
2597 }
2598 Ok(())
2599 })
2600 }
2601
2602 async fn handle_buffer_saved(
2603 this: ModelHandle<Self>,
2604 envelope: TypedEnvelope<proto::BufferSaved>,
2605 _: Arc<Client>,
2606 mut cx: AsyncAppContext,
2607 ) -> Result<()> {
2608 let version = envelope.payload.version.try_into()?;
2609 let mtime = envelope
2610 .payload
2611 .mtime
2612 .ok_or_else(|| anyhow!("missing mtime"))?
2613 .into();
2614
2615 this.update(&mut cx, |this, cx| {
2616 let buffer = this
2617 .open_buffers
2618 .get(&(envelope.payload.buffer_id as usize))
2619 .and_then(|buffer| buffer.upgrade(cx));
2620 if let Some(buffer) = buffer {
2621 buffer.update(cx, |buffer, cx| {
2622 buffer.did_save(version, mtime, None, cx);
2623 });
2624 }
2625 Ok(())
2626 })
2627 }
2628
2629 async fn handle_buffer_reloaded(
2630 this: ModelHandle<Self>,
2631 envelope: TypedEnvelope<proto::BufferReloaded>,
2632 _: Arc<Client>,
2633 mut cx: AsyncAppContext,
2634 ) -> Result<()> {
2635 let payload = envelope.payload.clone();
2636 let version = payload.version.try_into()?;
2637 let mtime = payload
2638 .mtime
2639 .ok_or_else(|| anyhow!("missing mtime"))?
2640 .into();
2641 this.update(&mut cx, |this, cx| {
2642 let buffer = this
2643 .open_buffers
2644 .get(&(payload.buffer_id as usize))
2645 .and_then(|buffer| buffer.upgrade(cx));
2646 if let Some(buffer) = buffer {
2647 buffer.update(cx, |buffer, cx| {
2648 buffer.did_reload(version, mtime, cx);
2649 });
2650 }
2651 Ok(())
2652 })
2653 }
2654
2655 pub fn match_paths<'a>(
2656 &self,
2657 query: &'a str,
2658 include_ignored: bool,
2659 smart_case: bool,
2660 max_results: usize,
2661 cancel_flag: &'a AtomicBool,
2662 cx: &AppContext,
2663 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
2664 let worktrees = self
2665 .worktrees(cx)
2666 .filter(|worktree| !worktree.read(cx).is_weak())
2667 .collect::<Vec<_>>();
2668 let include_root_name = worktrees.len() > 1;
2669 let candidate_sets = worktrees
2670 .into_iter()
2671 .map(|worktree| CandidateSet {
2672 snapshot: worktree.read(cx).snapshot(),
2673 include_ignored,
2674 include_root_name,
2675 })
2676 .collect::<Vec<_>>();
2677
2678 let background = cx.background().clone();
2679 async move {
2680 fuzzy::match_paths(
2681 candidate_sets.as_slice(),
2682 query,
2683 smart_case,
2684 max_results,
2685 cancel_flag,
2686 background,
2687 )
2688 .await
2689 }
2690 }
2691}
2692
2693impl WorktreeHandle {
2694 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
2695 match self {
2696 WorktreeHandle::Strong(handle) => Some(handle.clone()),
2697 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
2698 }
2699 }
2700}
2701
2702struct CandidateSet {
2703 snapshot: Snapshot,
2704 include_ignored: bool,
2705 include_root_name: bool,
2706}
2707
2708impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
2709 type Candidates = CandidateSetIter<'a>;
2710
2711 fn id(&self) -> usize {
2712 self.snapshot.id().to_usize()
2713 }
2714
2715 fn len(&self) -> usize {
2716 if self.include_ignored {
2717 self.snapshot.file_count()
2718 } else {
2719 self.snapshot.visible_file_count()
2720 }
2721 }
2722
2723 fn prefix(&self) -> Arc<str> {
2724 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
2725 self.snapshot.root_name().into()
2726 } else if self.include_root_name {
2727 format!("{}/", self.snapshot.root_name()).into()
2728 } else {
2729 "".into()
2730 }
2731 }
2732
2733 fn candidates(&'a self, start: usize) -> Self::Candidates {
2734 CandidateSetIter {
2735 traversal: self.snapshot.files(self.include_ignored, start),
2736 }
2737 }
2738}
2739
2740struct CandidateSetIter<'a> {
2741 traversal: Traversal<'a>,
2742}
2743
2744impl<'a> Iterator for CandidateSetIter<'a> {
2745 type Item = PathMatchCandidate<'a>;
2746
2747 fn next(&mut self) -> Option<Self::Item> {
2748 self.traversal.next().map(|entry| {
2749 if let EntryKind::File(char_bag) = entry.kind {
2750 PathMatchCandidate {
2751 path: &entry.path,
2752 char_bag,
2753 }
2754 } else {
2755 unreachable!()
2756 }
2757 })
2758 }
2759}
2760
2761impl Entity for Project {
2762 type Event = Event;
2763
2764 fn release(&mut self, _: &mut gpui::MutableAppContext) {
2765 match &self.client_state {
2766 ProjectClientState::Local { remote_id_rx, .. } => {
2767 if let Some(project_id) = *remote_id_rx.borrow() {
2768 self.client
2769 .send(proto::UnregisterProject { project_id })
2770 .log_err();
2771 }
2772 }
2773 ProjectClientState::Remote { remote_id, .. } => {
2774 self.client
2775 .send(proto::LeaveProject {
2776 project_id: *remote_id,
2777 })
2778 .log_err();
2779 }
2780 }
2781 }
2782
2783 fn app_will_quit(
2784 &mut self,
2785 _: &mut MutableAppContext,
2786 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
2787 use futures::FutureExt;
2788
2789 let shutdown_futures = self
2790 .language_servers
2791 .drain()
2792 .filter_map(|(_, server)| server.shutdown())
2793 .collect::<Vec<_>>();
2794 Some(
2795 async move {
2796 futures::future::join_all(shutdown_futures).await;
2797 }
2798 .boxed(),
2799 )
2800 }
2801}
2802
2803impl Collaborator {
2804 fn from_proto(
2805 message: proto::Collaborator,
2806 user_store: &ModelHandle<UserStore>,
2807 cx: &mut AsyncAppContext,
2808 ) -> impl Future<Output = Result<Self>> {
2809 let user = user_store.update(cx, |user_store, cx| {
2810 user_store.fetch_user(message.user_id, cx)
2811 });
2812
2813 async move {
2814 Ok(Self {
2815 peer_id: PeerId(message.peer_id),
2816 user: user.await?,
2817 replica_id: message.replica_id as ReplicaId,
2818 })
2819 }
2820 }
2821}
2822
2823impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
2824 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
2825 Self {
2826 worktree_id,
2827 path: path.as_ref().into(),
2828 }
2829 }
2830}
2831
2832impl From<lsp::CreateFileOptions> for fs::CreateOptions {
2833 fn from(options: lsp::CreateFileOptions) -> Self {
2834 Self {
2835 overwrite: options.overwrite.unwrap_or(false),
2836 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2837 }
2838 }
2839}
2840
2841impl From<lsp::RenameFileOptions> for fs::RenameOptions {
2842 fn from(options: lsp::RenameFileOptions) -> Self {
2843 Self {
2844 overwrite: options.overwrite.unwrap_or(false),
2845 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2846 }
2847 }
2848}
2849
2850impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
2851 fn from(options: lsp::DeleteFileOptions) -> Self {
2852 Self {
2853 recursive: options.recursive.unwrap_or(false),
2854 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
2855 }
2856 }
2857}
2858
2859#[cfg(test)]
2860mod tests {
2861 use super::{Event, *};
2862 use client::test::FakeHttpClient;
2863 use fs::RealFs;
2864 use futures::StreamExt;
2865 use gpui::test::subscribe;
2866 use language::{
2867 tree_sitter_rust, AnchorRangeExt, Diagnostic, LanguageConfig, LanguageRegistry,
2868 LanguageServerConfig, Point,
2869 };
2870 use lsp::Url;
2871 use serde_json::json;
2872 use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
2873 use unindent::Unindent as _;
2874 use util::test::temp_tree;
2875 use worktree::WorktreeHandle as _;
2876
2877 #[gpui::test]
2878 async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
2879 let dir = temp_tree(json!({
2880 "root": {
2881 "apple": "",
2882 "banana": {
2883 "carrot": {
2884 "date": "",
2885 "endive": "",
2886 }
2887 },
2888 "fennel": {
2889 "grape": "",
2890 }
2891 }
2892 }));
2893
2894 let root_link_path = dir.path().join("root_link");
2895 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
2896 unix::fs::symlink(
2897 &dir.path().join("root/fennel"),
2898 &dir.path().join("root/finnochio"),
2899 )
2900 .unwrap();
2901
2902 let project = Project::test(Arc::new(RealFs), &mut cx);
2903
2904 let (tree, _) = project
2905 .update(&mut cx, |project, cx| {
2906 project.find_or_create_local_worktree(&root_link_path, false, cx)
2907 })
2908 .await
2909 .unwrap();
2910
2911 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2912 .await;
2913 cx.read(|cx| {
2914 let tree = tree.read(cx);
2915 assert_eq!(tree.file_count(), 5);
2916 assert_eq!(
2917 tree.inode_for_path("fennel/grape"),
2918 tree.inode_for_path("finnochio/grape")
2919 );
2920 });
2921
2922 let cancel_flag = Default::default();
2923 let results = project
2924 .read_with(&cx, |project, cx| {
2925 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
2926 })
2927 .await;
2928 assert_eq!(
2929 results
2930 .into_iter()
2931 .map(|result| result.path)
2932 .collect::<Vec<Arc<Path>>>(),
2933 vec![
2934 PathBuf::from("banana/carrot/date").into(),
2935 PathBuf::from("banana/carrot/endive").into(),
2936 ]
2937 );
2938 }
2939
2940 #[gpui::test]
2941 async fn test_language_server_diagnostics(mut cx: gpui::TestAppContext) {
2942 let (language_server_config, mut fake_server) = LanguageServerConfig::fake(&cx).await;
2943 let progress_token = language_server_config
2944 .disk_based_diagnostics_progress_token
2945 .clone()
2946 .unwrap();
2947
2948 let mut languages = LanguageRegistry::new();
2949 languages.add(Arc::new(Language::new(
2950 LanguageConfig {
2951 name: "Rust".to_string(),
2952 path_suffixes: vec!["rs".to_string()],
2953 language_server: Some(language_server_config),
2954 ..Default::default()
2955 },
2956 Some(tree_sitter_rust::language()),
2957 )));
2958
2959 let dir = temp_tree(json!({
2960 "a.rs": "fn a() { A }",
2961 "b.rs": "const y: i32 = 1",
2962 }));
2963
2964 let http_client = FakeHttpClient::with_404_response();
2965 let client = Client::new(http_client.clone());
2966 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
2967
2968 let project = cx.update(|cx| {
2969 Project::local(
2970 client,
2971 user_store,
2972 Arc::new(languages),
2973 Arc::new(RealFs),
2974 cx,
2975 )
2976 });
2977
2978 let (tree, _) = project
2979 .update(&mut cx, |project, cx| {
2980 project.find_or_create_local_worktree(dir.path(), false, cx)
2981 })
2982 .await
2983 .unwrap();
2984 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
2985
2986 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2987 .await;
2988
2989 // Cause worktree to start the fake language server
2990 let _buffer = project
2991 .update(&mut cx, |project, cx| {
2992 project.open_buffer(
2993 ProjectPath {
2994 worktree_id,
2995 path: Path::new("b.rs").into(),
2996 },
2997 cx,
2998 )
2999 })
3000 .await
3001 .unwrap();
3002
3003 let mut events = subscribe(&project, &mut cx);
3004
3005 fake_server.start_progress(&progress_token).await;
3006 assert_eq!(
3007 events.next().await.unwrap(),
3008 Event::DiskBasedDiagnosticsStarted
3009 );
3010
3011 fake_server.start_progress(&progress_token).await;
3012 fake_server.end_progress(&progress_token).await;
3013 fake_server.start_progress(&progress_token).await;
3014
3015 fake_server
3016 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
3017 uri: Url::from_file_path(dir.path().join("a.rs")).unwrap(),
3018 version: None,
3019 diagnostics: vec![lsp::Diagnostic {
3020 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3021 severity: Some(lsp::DiagnosticSeverity::ERROR),
3022 message: "undefined variable 'A'".to_string(),
3023 ..Default::default()
3024 }],
3025 })
3026 .await;
3027 assert_eq!(
3028 events.next().await.unwrap(),
3029 Event::DiagnosticsUpdated(ProjectPath {
3030 worktree_id,
3031 path: Arc::from(Path::new("a.rs"))
3032 })
3033 );
3034
3035 fake_server.end_progress(&progress_token).await;
3036 fake_server.end_progress(&progress_token).await;
3037 assert_eq!(
3038 events.next().await.unwrap(),
3039 Event::DiskBasedDiagnosticsUpdated
3040 );
3041 assert_eq!(
3042 events.next().await.unwrap(),
3043 Event::DiskBasedDiagnosticsFinished
3044 );
3045
3046 let buffer = project
3047 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3048 .await
3049 .unwrap();
3050
3051 buffer.read_with(&cx, |buffer, _| {
3052 let snapshot = buffer.snapshot();
3053 let diagnostics = snapshot
3054 .diagnostics_in_range::<_, Point>(0..buffer.len())
3055 .collect::<Vec<_>>();
3056 assert_eq!(
3057 diagnostics,
3058 &[DiagnosticEntry {
3059 range: Point::new(0, 9)..Point::new(0, 10),
3060 diagnostic: Diagnostic {
3061 severity: lsp::DiagnosticSeverity::ERROR,
3062 message: "undefined variable 'A'".to_string(),
3063 group_id: 0,
3064 is_primary: true,
3065 ..Default::default()
3066 }
3067 }]
3068 )
3069 });
3070 }
3071
3072 #[gpui::test]
3073 async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
3074 let dir = temp_tree(json!({
3075 "root": {
3076 "dir1": {},
3077 "dir2": {
3078 "dir3": {}
3079 }
3080 }
3081 }));
3082
3083 let project = Project::test(Arc::new(RealFs), &mut cx);
3084 let (tree, _) = project
3085 .update(&mut cx, |project, cx| {
3086 project.find_or_create_local_worktree(&dir.path(), false, cx)
3087 })
3088 .await
3089 .unwrap();
3090
3091 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3092 .await;
3093
3094 let cancel_flag = Default::default();
3095 let results = project
3096 .read_with(&cx, |project, cx| {
3097 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
3098 })
3099 .await;
3100
3101 assert!(results.is_empty());
3102 }
3103
3104 #[gpui::test]
3105 async fn test_definition(mut cx: gpui::TestAppContext) {
3106 let (language_server_config, mut fake_server) = LanguageServerConfig::fake(&cx).await;
3107
3108 let mut languages = LanguageRegistry::new();
3109 languages.add(Arc::new(Language::new(
3110 LanguageConfig {
3111 name: "Rust".to_string(),
3112 path_suffixes: vec!["rs".to_string()],
3113 language_server: Some(language_server_config),
3114 ..Default::default()
3115 },
3116 Some(tree_sitter_rust::language()),
3117 )));
3118
3119 let dir = temp_tree(json!({
3120 "a.rs": "const fn a() { A }",
3121 "b.rs": "const y: i32 = crate::a()",
3122 }));
3123 let dir_path = dir.path().to_path_buf();
3124
3125 let http_client = FakeHttpClient::with_404_response();
3126 let client = Client::new(http_client.clone());
3127 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3128 let project = cx.update(|cx| {
3129 Project::local(
3130 client,
3131 user_store,
3132 Arc::new(languages),
3133 Arc::new(RealFs),
3134 cx,
3135 )
3136 });
3137
3138 let (tree, _) = project
3139 .update(&mut cx, |project, cx| {
3140 project.find_or_create_local_worktree(dir.path().join("b.rs"), false, cx)
3141 })
3142 .await
3143 .unwrap();
3144 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3145 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3146 .await;
3147
3148 let buffer = project
3149 .update(&mut cx, |project, cx| {
3150 project.open_buffer(
3151 ProjectPath {
3152 worktree_id,
3153 path: Path::new("").into(),
3154 },
3155 cx,
3156 )
3157 })
3158 .await
3159 .unwrap();
3160
3161 fake_server.handle_request::<lsp::request::GotoDefinition, _>(move |params| {
3162 let params = params.text_document_position_params;
3163 assert_eq!(
3164 params.text_document.uri.to_file_path().unwrap(),
3165 dir_path.join("b.rs")
3166 );
3167 assert_eq!(params.position, lsp::Position::new(0, 22));
3168
3169 Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
3170 lsp::Url::from_file_path(dir_path.join("a.rs")).unwrap(),
3171 lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3172 )))
3173 });
3174
3175 let mut definitions = project
3176 .update(&mut cx, |project, cx| project.definition(&buffer, 22, cx))
3177 .await
3178 .unwrap();
3179
3180 assert_eq!(definitions.len(), 1);
3181 let definition = definitions.pop().unwrap();
3182 cx.update(|cx| {
3183 let target_buffer = definition.target_buffer.read(cx);
3184 assert_eq!(
3185 target_buffer
3186 .file()
3187 .unwrap()
3188 .as_local()
3189 .unwrap()
3190 .abs_path(cx),
3191 dir.path().join("a.rs")
3192 );
3193 assert_eq!(definition.target_range.to_offset(target_buffer), 9..10);
3194 assert_eq!(
3195 list_worktrees(&project, cx),
3196 [
3197 (dir.path().join("b.rs"), false),
3198 (dir.path().join("a.rs"), true)
3199 ]
3200 );
3201
3202 drop(definition);
3203 });
3204 cx.read(|cx| {
3205 assert_eq!(
3206 list_worktrees(&project, cx),
3207 [(dir.path().join("b.rs"), false)]
3208 );
3209 });
3210
3211 fn list_worktrees(project: &ModelHandle<Project>, cx: &AppContext) -> Vec<(PathBuf, bool)> {
3212 project
3213 .read(cx)
3214 .worktrees(cx)
3215 .map(|worktree| {
3216 let worktree = worktree.read(cx);
3217 (
3218 worktree.as_local().unwrap().abs_path().to_path_buf(),
3219 worktree.is_weak(),
3220 )
3221 })
3222 .collect::<Vec<_>>()
3223 }
3224 }
3225
3226 #[gpui::test]
3227 async fn test_save_file(mut cx: gpui::TestAppContext) {
3228 let fs = Arc::new(FakeFs::new(cx.background()));
3229 fs.insert_tree(
3230 "/dir",
3231 json!({
3232 "file1": "the old contents",
3233 }),
3234 )
3235 .await;
3236
3237 let project = Project::test(fs.clone(), &mut cx);
3238 let worktree_id = project
3239 .update(&mut cx, |p, cx| {
3240 p.find_or_create_local_worktree("/dir", false, cx)
3241 })
3242 .await
3243 .unwrap()
3244 .0
3245 .read_with(&cx, |tree, _| tree.id());
3246
3247 let buffer = project
3248 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3249 .await
3250 .unwrap();
3251 buffer
3252 .update(&mut cx, |buffer, cx| {
3253 assert_eq!(buffer.text(), "the old contents");
3254 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3255 buffer.save(cx)
3256 })
3257 .await
3258 .unwrap();
3259
3260 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3261 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3262 }
3263
3264 #[gpui::test]
3265 async fn test_save_in_single_file_worktree(mut cx: gpui::TestAppContext) {
3266 let fs = Arc::new(FakeFs::new(cx.background()));
3267 fs.insert_tree(
3268 "/dir",
3269 json!({
3270 "file1": "the old contents",
3271 }),
3272 )
3273 .await;
3274
3275 let project = Project::test(fs.clone(), &mut cx);
3276 let worktree_id = project
3277 .update(&mut cx, |p, cx| {
3278 p.find_or_create_local_worktree("/dir/file1", false, cx)
3279 })
3280 .await
3281 .unwrap()
3282 .0
3283 .read_with(&cx, |tree, _| tree.id());
3284
3285 let buffer = project
3286 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
3287 .await
3288 .unwrap();
3289 buffer
3290 .update(&mut cx, |buffer, cx| {
3291 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3292 buffer.save(cx)
3293 })
3294 .await
3295 .unwrap();
3296
3297 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3298 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3299 }
3300
3301 #[gpui::test(retries = 5)]
3302 async fn test_rescan_and_remote_updates(mut cx: gpui::TestAppContext) {
3303 let dir = temp_tree(json!({
3304 "a": {
3305 "file1": "",
3306 "file2": "",
3307 "file3": "",
3308 },
3309 "b": {
3310 "c": {
3311 "file4": "",
3312 "file5": "",
3313 }
3314 }
3315 }));
3316
3317 let project = Project::test(Arc::new(RealFs), &mut cx);
3318 let rpc = project.read_with(&cx, |p, _| p.client.clone());
3319
3320 let (tree, _) = project
3321 .update(&mut cx, |p, cx| {
3322 p.find_or_create_local_worktree(dir.path(), false, cx)
3323 })
3324 .await
3325 .unwrap();
3326 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3327
3328 let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
3329 let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
3330 async move { buffer.await.unwrap() }
3331 };
3332 let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
3333 tree.read_with(cx, |tree, _| {
3334 tree.entry_for_path(path)
3335 .expect(&format!("no entry for path {}", path))
3336 .id
3337 })
3338 };
3339
3340 let buffer2 = buffer_for_path("a/file2", &mut cx).await;
3341 let buffer3 = buffer_for_path("a/file3", &mut cx).await;
3342 let buffer4 = buffer_for_path("b/c/file4", &mut cx).await;
3343 let buffer5 = buffer_for_path("b/c/file5", &mut cx).await;
3344
3345 let file2_id = id_for_path("a/file2", &cx);
3346 let file3_id = id_for_path("a/file3", &cx);
3347 let file4_id = id_for_path("b/c/file4", &cx);
3348
3349 // Wait for the initial scan.
3350 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3351 .await;
3352
3353 // Create a remote copy of this worktree.
3354 let initial_snapshot = tree.read_with(&cx, |tree, _| tree.snapshot());
3355 let (remote, load_task) = cx.update(|cx| {
3356 Worktree::remote(
3357 1,
3358 1,
3359 initial_snapshot.to_proto(&Default::default(), Default::default()),
3360 rpc.clone(),
3361 cx,
3362 )
3363 });
3364 load_task.await;
3365
3366 cx.read(|cx| {
3367 assert!(!buffer2.read(cx).is_dirty());
3368 assert!(!buffer3.read(cx).is_dirty());
3369 assert!(!buffer4.read(cx).is_dirty());
3370 assert!(!buffer5.read(cx).is_dirty());
3371 });
3372
3373 // Rename and delete files and directories.
3374 tree.flush_fs_events(&cx).await;
3375 std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
3376 std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
3377 std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
3378 std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
3379 tree.flush_fs_events(&cx).await;
3380
3381 let expected_paths = vec![
3382 "a",
3383 "a/file1",
3384 "a/file2.new",
3385 "b",
3386 "d",
3387 "d/file3",
3388 "d/file4",
3389 ];
3390
3391 cx.read(|app| {
3392 assert_eq!(
3393 tree.read(app)
3394 .paths()
3395 .map(|p| p.to_str().unwrap())
3396 .collect::<Vec<_>>(),
3397 expected_paths
3398 );
3399
3400 assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
3401 assert_eq!(id_for_path("d/file3", &cx), file3_id);
3402 assert_eq!(id_for_path("d/file4", &cx), file4_id);
3403
3404 assert_eq!(
3405 buffer2.read(app).file().unwrap().path().as_ref(),
3406 Path::new("a/file2.new")
3407 );
3408 assert_eq!(
3409 buffer3.read(app).file().unwrap().path().as_ref(),
3410 Path::new("d/file3")
3411 );
3412 assert_eq!(
3413 buffer4.read(app).file().unwrap().path().as_ref(),
3414 Path::new("d/file4")
3415 );
3416 assert_eq!(
3417 buffer5.read(app).file().unwrap().path().as_ref(),
3418 Path::new("b/c/file5")
3419 );
3420
3421 assert!(!buffer2.read(app).file().unwrap().is_deleted());
3422 assert!(!buffer3.read(app).file().unwrap().is_deleted());
3423 assert!(!buffer4.read(app).file().unwrap().is_deleted());
3424 assert!(buffer5.read(app).file().unwrap().is_deleted());
3425 });
3426
3427 // Update the remote worktree. Check that it becomes consistent with the
3428 // local worktree.
3429 remote.update(&mut cx, |remote, cx| {
3430 let update_message =
3431 tree.read(cx)
3432 .snapshot()
3433 .build_update(&initial_snapshot, 1, 1, true);
3434 remote
3435 .as_remote_mut()
3436 .unwrap()
3437 .snapshot
3438 .apply_remote_update(update_message)
3439 .unwrap();
3440
3441 assert_eq!(
3442 remote
3443 .paths()
3444 .map(|p| p.to_str().unwrap())
3445 .collect::<Vec<_>>(),
3446 expected_paths
3447 );
3448 });
3449 }
3450
3451 #[gpui::test]
3452 async fn test_buffer_deduping(mut cx: gpui::TestAppContext) {
3453 let fs = Arc::new(FakeFs::new(cx.background()));
3454 fs.insert_tree(
3455 "/the-dir",
3456 json!({
3457 "a.txt": "a-contents",
3458 "b.txt": "b-contents",
3459 }),
3460 )
3461 .await;
3462
3463 let project = Project::test(fs.clone(), &mut cx);
3464 let worktree_id = project
3465 .update(&mut cx, |p, cx| {
3466 p.find_or_create_local_worktree("/the-dir", false, cx)
3467 })
3468 .await
3469 .unwrap()
3470 .0
3471 .read_with(&cx, |tree, _| tree.id());
3472
3473 // Spawn multiple tasks to open paths, repeating some paths.
3474 let (buffer_a_1, buffer_b, buffer_a_2) = project.update(&mut cx, |p, cx| {
3475 (
3476 p.open_buffer((worktree_id, "a.txt"), cx),
3477 p.open_buffer((worktree_id, "b.txt"), cx),
3478 p.open_buffer((worktree_id, "a.txt"), cx),
3479 )
3480 });
3481
3482 let buffer_a_1 = buffer_a_1.await.unwrap();
3483 let buffer_a_2 = buffer_a_2.await.unwrap();
3484 let buffer_b = buffer_b.await.unwrap();
3485 assert_eq!(buffer_a_1.read_with(&cx, |b, _| b.text()), "a-contents");
3486 assert_eq!(buffer_b.read_with(&cx, |b, _| b.text()), "b-contents");
3487
3488 // There is only one buffer per path.
3489 let buffer_a_id = buffer_a_1.id();
3490 assert_eq!(buffer_a_2.id(), buffer_a_id);
3491
3492 // Open the same path again while it is still open.
3493 drop(buffer_a_1);
3494 let buffer_a_3 = project
3495 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3496 .await
3497 .unwrap();
3498
3499 // There's still only one buffer per path.
3500 assert_eq!(buffer_a_3.id(), buffer_a_id);
3501 }
3502
3503 #[gpui::test]
3504 async fn test_buffer_is_dirty(mut cx: gpui::TestAppContext) {
3505 use std::fs;
3506
3507 let dir = temp_tree(json!({
3508 "file1": "abc",
3509 "file2": "def",
3510 "file3": "ghi",
3511 }));
3512
3513 let project = Project::test(Arc::new(RealFs), &mut cx);
3514 let (worktree, _) = project
3515 .update(&mut cx, |p, cx| {
3516 p.find_or_create_local_worktree(dir.path(), false, cx)
3517 })
3518 .await
3519 .unwrap();
3520 let worktree_id = worktree.read_with(&cx, |worktree, _| worktree.id());
3521
3522 worktree.flush_fs_events(&cx).await;
3523 worktree
3524 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
3525 .await;
3526
3527 let buffer1 = project
3528 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3529 .await
3530 .unwrap();
3531 let events = Rc::new(RefCell::new(Vec::new()));
3532
3533 // initially, the buffer isn't dirty.
3534 buffer1.update(&mut cx, |buffer, cx| {
3535 cx.subscribe(&buffer1, {
3536 let events = events.clone();
3537 move |_, _, event, _| events.borrow_mut().push(event.clone())
3538 })
3539 .detach();
3540
3541 assert!(!buffer.is_dirty());
3542 assert!(events.borrow().is_empty());
3543
3544 buffer.edit(vec![1..2], "", cx);
3545 });
3546
3547 // after the first edit, the buffer is dirty, and emits a dirtied event.
3548 buffer1.update(&mut cx, |buffer, cx| {
3549 assert!(buffer.text() == "ac");
3550 assert!(buffer.is_dirty());
3551 assert_eq!(
3552 *events.borrow(),
3553 &[language::Event::Edited, language::Event::Dirtied]
3554 );
3555 events.borrow_mut().clear();
3556 buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
3557 });
3558
3559 // after saving, the buffer is not dirty, and emits a saved event.
3560 buffer1.update(&mut cx, |buffer, cx| {
3561 assert!(!buffer.is_dirty());
3562 assert_eq!(*events.borrow(), &[language::Event::Saved]);
3563 events.borrow_mut().clear();
3564
3565 buffer.edit(vec![1..1], "B", cx);
3566 buffer.edit(vec![2..2], "D", cx);
3567 });
3568
3569 // after editing again, the buffer is dirty, and emits another dirty event.
3570 buffer1.update(&mut cx, |buffer, cx| {
3571 assert!(buffer.text() == "aBDc");
3572 assert!(buffer.is_dirty());
3573 assert_eq!(
3574 *events.borrow(),
3575 &[
3576 language::Event::Edited,
3577 language::Event::Dirtied,
3578 language::Event::Edited,
3579 ],
3580 );
3581 events.borrow_mut().clear();
3582
3583 // TODO - currently, after restoring the buffer to its
3584 // previously-saved state, the is still considered dirty.
3585 buffer.edit([1..3], "", cx);
3586 assert!(buffer.text() == "ac");
3587 assert!(buffer.is_dirty());
3588 });
3589
3590 assert_eq!(*events.borrow(), &[language::Event::Edited]);
3591
3592 // When a file is deleted, the buffer is considered dirty.
3593 let events = Rc::new(RefCell::new(Vec::new()));
3594 let buffer2 = project
3595 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
3596 .await
3597 .unwrap();
3598 buffer2.update(&mut cx, |_, cx| {
3599 cx.subscribe(&buffer2, {
3600 let events = events.clone();
3601 move |_, _, event, _| events.borrow_mut().push(event.clone())
3602 })
3603 .detach();
3604 });
3605
3606 fs::remove_file(dir.path().join("file2")).unwrap();
3607 buffer2.condition(&cx, |b, _| b.is_dirty()).await;
3608 assert_eq!(
3609 *events.borrow(),
3610 &[language::Event::Dirtied, language::Event::FileHandleChanged]
3611 );
3612
3613 // When a file is already dirty when deleted, we don't emit a Dirtied event.
3614 let events = Rc::new(RefCell::new(Vec::new()));
3615 let buffer3 = project
3616 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
3617 .await
3618 .unwrap();
3619 buffer3.update(&mut cx, |_, cx| {
3620 cx.subscribe(&buffer3, {
3621 let events = events.clone();
3622 move |_, _, event, _| events.borrow_mut().push(event.clone())
3623 })
3624 .detach();
3625 });
3626
3627 worktree.flush_fs_events(&cx).await;
3628 buffer3.update(&mut cx, |buffer, cx| {
3629 buffer.edit(Some(0..0), "x", cx);
3630 });
3631 events.borrow_mut().clear();
3632 fs::remove_file(dir.path().join("file3")).unwrap();
3633 buffer3
3634 .condition(&cx, |_, _| !events.borrow().is_empty())
3635 .await;
3636 assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
3637 cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
3638 }
3639
3640 #[gpui::test]
3641 async fn test_buffer_file_changes_on_disk(mut cx: gpui::TestAppContext) {
3642 use std::fs;
3643
3644 let initial_contents = "aaa\nbbbbb\nc\n";
3645 let dir = temp_tree(json!({ "the-file": initial_contents }));
3646
3647 let project = Project::test(Arc::new(RealFs), &mut cx);
3648 let (worktree, _) = project
3649 .update(&mut cx, |p, cx| {
3650 p.find_or_create_local_worktree(dir.path(), false, cx)
3651 })
3652 .await
3653 .unwrap();
3654 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
3655
3656 worktree
3657 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
3658 .await;
3659
3660 let abs_path = dir.path().join("the-file");
3661 let buffer = project
3662 .update(&mut cx, |p, cx| {
3663 p.open_buffer((worktree_id, "the-file"), cx)
3664 })
3665 .await
3666 .unwrap();
3667
3668 // TODO
3669 // Add a cursor on each row.
3670 // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
3671 // assert!(!buffer.is_dirty());
3672 // buffer.add_selection_set(
3673 // &(0..3)
3674 // .map(|row| Selection {
3675 // id: row as usize,
3676 // start: Point::new(row, 1),
3677 // end: Point::new(row, 1),
3678 // reversed: false,
3679 // goal: SelectionGoal::None,
3680 // })
3681 // .collect::<Vec<_>>(),
3682 // cx,
3683 // )
3684 // });
3685
3686 // Change the file on disk, adding two new lines of text, and removing
3687 // one line.
3688 buffer.read_with(&cx, |buffer, _| {
3689 assert!(!buffer.is_dirty());
3690 assert!(!buffer.has_conflict());
3691 });
3692 let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
3693 fs::write(&abs_path, new_contents).unwrap();
3694
3695 // Because the buffer was not modified, it is reloaded from disk. Its
3696 // contents are edited according to the diff between the old and new
3697 // file contents.
3698 buffer
3699 .condition(&cx, |buffer, _| buffer.text() == new_contents)
3700 .await;
3701
3702 buffer.update(&mut cx, |buffer, _| {
3703 assert_eq!(buffer.text(), new_contents);
3704 assert!(!buffer.is_dirty());
3705 assert!(!buffer.has_conflict());
3706
3707 // TODO
3708 // let cursor_positions = buffer
3709 // .selection_set(selection_set_id)
3710 // .unwrap()
3711 // .selections::<Point>(&*buffer)
3712 // .map(|selection| {
3713 // assert_eq!(selection.start, selection.end);
3714 // selection.start
3715 // })
3716 // .collect::<Vec<_>>();
3717 // assert_eq!(
3718 // cursor_positions,
3719 // [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
3720 // );
3721 });
3722
3723 // Modify the buffer
3724 buffer.update(&mut cx, |buffer, cx| {
3725 buffer.edit(vec![0..0], " ", cx);
3726 assert!(buffer.is_dirty());
3727 assert!(!buffer.has_conflict());
3728 });
3729
3730 // Change the file on disk again, adding blank lines to the beginning.
3731 fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
3732
3733 // Because the buffer is modified, it doesn't reload from disk, but is
3734 // marked as having a conflict.
3735 buffer
3736 .condition(&cx, |buffer, _| buffer.has_conflict())
3737 .await;
3738 }
3739
3740 #[gpui::test]
3741 async fn test_grouped_diagnostics(mut cx: gpui::TestAppContext) {
3742 let fs = Arc::new(FakeFs::new(cx.background()));
3743 fs.insert_tree(
3744 "/the-dir",
3745 json!({
3746 "a.rs": "
3747 fn foo(mut v: Vec<usize>) {
3748 for x in &v {
3749 v.push(1);
3750 }
3751 }
3752 "
3753 .unindent(),
3754 }),
3755 )
3756 .await;
3757
3758 let project = Project::test(fs.clone(), &mut cx);
3759 let (worktree, _) = project
3760 .update(&mut cx, |p, cx| {
3761 p.find_or_create_local_worktree("/the-dir", false, cx)
3762 })
3763 .await
3764 .unwrap();
3765 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
3766
3767 let buffer = project
3768 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3769 .await
3770 .unwrap();
3771
3772 let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
3773 let message = lsp::PublishDiagnosticsParams {
3774 uri: buffer_uri.clone(),
3775 diagnostics: vec![
3776 lsp::Diagnostic {
3777 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3778 severity: Some(DiagnosticSeverity::WARNING),
3779 message: "error 1".to_string(),
3780 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3781 location: lsp::Location {
3782 uri: buffer_uri.clone(),
3783 range: lsp::Range::new(
3784 lsp::Position::new(1, 8),
3785 lsp::Position::new(1, 9),
3786 ),
3787 },
3788 message: "error 1 hint 1".to_string(),
3789 }]),
3790 ..Default::default()
3791 },
3792 lsp::Diagnostic {
3793 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3794 severity: Some(DiagnosticSeverity::HINT),
3795 message: "error 1 hint 1".to_string(),
3796 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3797 location: lsp::Location {
3798 uri: buffer_uri.clone(),
3799 range: lsp::Range::new(
3800 lsp::Position::new(1, 8),
3801 lsp::Position::new(1, 9),
3802 ),
3803 },
3804 message: "original diagnostic".to_string(),
3805 }]),
3806 ..Default::default()
3807 },
3808 lsp::Diagnostic {
3809 range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
3810 severity: Some(DiagnosticSeverity::ERROR),
3811 message: "error 2".to_string(),
3812 related_information: Some(vec![
3813 lsp::DiagnosticRelatedInformation {
3814 location: lsp::Location {
3815 uri: buffer_uri.clone(),
3816 range: lsp::Range::new(
3817 lsp::Position::new(1, 13),
3818 lsp::Position::new(1, 15),
3819 ),
3820 },
3821 message: "error 2 hint 1".to_string(),
3822 },
3823 lsp::DiagnosticRelatedInformation {
3824 location: lsp::Location {
3825 uri: buffer_uri.clone(),
3826 range: lsp::Range::new(
3827 lsp::Position::new(1, 13),
3828 lsp::Position::new(1, 15),
3829 ),
3830 },
3831 message: "error 2 hint 2".to_string(),
3832 },
3833 ]),
3834 ..Default::default()
3835 },
3836 lsp::Diagnostic {
3837 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3838 severity: Some(DiagnosticSeverity::HINT),
3839 message: "error 2 hint 1".to_string(),
3840 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3841 location: lsp::Location {
3842 uri: buffer_uri.clone(),
3843 range: lsp::Range::new(
3844 lsp::Position::new(2, 8),
3845 lsp::Position::new(2, 17),
3846 ),
3847 },
3848 message: "original diagnostic".to_string(),
3849 }]),
3850 ..Default::default()
3851 },
3852 lsp::Diagnostic {
3853 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3854 severity: Some(DiagnosticSeverity::HINT),
3855 message: "error 2 hint 2".to_string(),
3856 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3857 location: lsp::Location {
3858 uri: buffer_uri.clone(),
3859 range: lsp::Range::new(
3860 lsp::Position::new(2, 8),
3861 lsp::Position::new(2, 17),
3862 ),
3863 },
3864 message: "original diagnostic".to_string(),
3865 }]),
3866 ..Default::default()
3867 },
3868 ],
3869 version: None,
3870 };
3871
3872 project
3873 .update(&mut cx, |p, cx| {
3874 p.update_diagnostics(message, &Default::default(), cx)
3875 })
3876 .unwrap();
3877 let buffer = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3878
3879 assert_eq!(
3880 buffer
3881 .diagnostics_in_range::<_, Point>(0..buffer.len())
3882 .collect::<Vec<_>>(),
3883 &[
3884 DiagnosticEntry {
3885 range: Point::new(1, 8)..Point::new(1, 9),
3886 diagnostic: Diagnostic {
3887 severity: DiagnosticSeverity::WARNING,
3888 message: "error 1".to_string(),
3889 group_id: 0,
3890 is_primary: true,
3891 ..Default::default()
3892 }
3893 },
3894 DiagnosticEntry {
3895 range: Point::new(1, 8)..Point::new(1, 9),
3896 diagnostic: Diagnostic {
3897 severity: DiagnosticSeverity::HINT,
3898 message: "error 1 hint 1".to_string(),
3899 group_id: 0,
3900 is_primary: false,
3901 ..Default::default()
3902 }
3903 },
3904 DiagnosticEntry {
3905 range: Point::new(1, 13)..Point::new(1, 15),
3906 diagnostic: Diagnostic {
3907 severity: DiagnosticSeverity::HINT,
3908 message: "error 2 hint 1".to_string(),
3909 group_id: 1,
3910 is_primary: false,
3911 ..Default::default()
3912 }
3913 },
3914 DiagnosticEntry {
3915 range: Point::new(1, 13)..Point::new(1, 15),
3916 diagnostic: Diagnostic {
3917 severity: DiagnosticSeverity::HINT,
3918 message: "error 2 hint 2".to_string(),
3919 group_id: 1,
3920 is_primary: false,
3921 ..Default::default()
3922 }
3923 },
3924 DiagnosticEntry {
3925 range: Point::new(2, 8)..Point::new(2, 17),
3926 diagnostic: Diagnostic {
3927 severity: DiagnosticSeverity::ERROR,
3928 message: "error 2".to_string(),
3929 group_id: 1,
3930 is_primary: true,
3931 ..Default::default()
3932 }
3933 }
3934 ]
3935 );
3936
3937 assert_eq!(
3938 buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
3939 &[
3940 DiagnosticEntry {
3941 range: Point::new(1, 8)..Point::new(1, 9),
3942 diagnostic: Diagnostic {
3943 severity: DiagnosticSeverity::WARNING,
3944 message: "error 1".to_string(),
3945 group_id: 0,
3946 is_primary: true,
3947 ..Default::default()
3948 }
3949 },
3950 DiagnosticEntry {
3951 range: Point::new(1, 8)..Point::new(1, 9),
3952 diagnostic: Diagnostic {
3953 severity: DiagnosticSeverity::HINT,
3954 message: "error 1 hint 1".to_string(),
3955 group_id: 0,
3956 is_primary: false,
3957 ..Default::default()
3958 }
3959 },
3960 ]
3961 );
3962 assert_eq!(
3963 buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
3964 &[
3965 DiagnosticEntry {
3966 range: Point::new(1, 13)..Point::new(1, 15),
3967 diagnostic: Diagnostic {
3968 severity: DiagnosticSeverity::HINT,
3969 message: "error 2 hint 1".to_string(),
3970 group_id: 1,
3971 is_primary: false,
3972 ..Default::default()
3973 }
3974 },
3975 DiagnosticEntry {
3976 range: Point::new(1, 13)..Point::new(1, 15),
3977 diagnostic: Diagnostic {
3978 severity: DiagnosticSeverity::HINT,
3979 message: "error 2 hint 2".to_string(),
3980 group_id: 1,
3981 is_primary: false,
3982 ..Default::default()
3983 }
3984 },
3985 DiagnosticEntry {
3986 range: Point::new(2, 8)..Point::new(2, 17),
3987 diagnostic: Diagnostic {
3988 severity: DiagnosticSeverity::ERROR,
3989 message: "error 2".to_string(),
3990 group_id: 1,
3991 is_primary: true,
3992 ..Default::default()
3993 }
3994 }
3995 ]
3996 );
3997 }
3998}