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