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