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