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