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, StreamExt};
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 Rope, 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 pub fn search(&self, query: &str, cx: &mut ModelContext<Self>) {
2046 if self.is_local() {
2047 enum SearchItem {
2048 Path(PathBuf),
2049 Buffer((WeakModelHandle<Buffer>, Rope)),
2050 }
2051
2052 let (queue_tx, queue_rx) = smol::channel::bounded(1024);
2053
2054 // Submit all worktree paths to the queue.
2055 let snapshots = self
2056 .strong_worktrees(cx)
2057 .filter_map(|tree| {
2058 let tree = tree.read(cx).as_local()?;
2059 Some((tree.abs_path().clone(), tree.snapshot()))
2060 })
2061 .collect::<Vec<_>>();
2062 cx.background()
2063 .spawn({
2064 let queue_tx = queue_tx.clone();
2065 async move {
2066 for (snapshot_abs_path, snapshot) in snapshots {
2067 for file in snapshot.files(false, 0) {
2068 if queue_tx
2069 .send(SearchItem::Path(snapshot_abs_path.join(&file.path)))
2070 .await
2071 .is_err()
2072 {
2073 return;
2074 }
2075 }
2076 }
2077 }
2078 })
2079 .detach();
2080
2081 // Submit all the currently-open buffers that are dirty to the queue.
2082 let buffers = self
2083 .open_buffers
2084 .values()
2085 .filter_map(|buffer| {
2086 if let OpenBuffer::Loaded(buffer) = buffer {
2087 Some(buffer.clone())
2088 } else {
2089 None
2090 }
2091 })
2092 .collect::<Vec<_>>();
2093 cx.spawn_weak(|_, cx| async move {
2094 for buffer in buffers.into_iter().filter_map(|buffer| buffer.upgrade(&cx)) {
2095 let text = buffer.read_with(&cx, |buffer, _| {
2096 if buffer.is_dirty() {
2097 Some(buffer.as_rope().clone())
2098 } else {
2099 None
2100 }
2101 });
2102
2103 if let Some(text) = text {
2104 if queue_tx
2105 .send(SearchItem::Buffer((buffer.downgrade(), text)))
2106 .await
2107 .is_err()
2108 {
2109 return;
2110 }
2111 }
2112 }
2113 })
2114 .detach();
2115
2116 let background = cx.background().clone();
2117 cx.background()
2118 .spawn(async move {
2119 let workers = background.num_cpus();
2120 background
2121 .scoped(|scope| {
2122 for _ in 0..workers {
2123 let mut paths_rx = queue_rx.clone();
2124 scope.spawn(async move {
2125 while let Some(item) = paths_rx.next().await {
2126 match item {
2127 SearchItem::Path(_) => todo!(),
2128 SearchItem::Buffer(_) => todo!(),
2129 }
2130 }
2131 });
2132 }
2133 })
2134 .await;
2135 })
2136 .detach();
2137 // let multiline = query.contains('\n');
2138 // let searcher = grep::searcher::SearcherBuilder::new()
2139 // .multi_line(multiline)
2140 // .build();
2141 // searcher.search_path(
2142 // "hey".to_string(),
2143 // "/hello/world",
2144 // grep::searcher::sinks::Lossy(|row, mat| {}),
2145 // );
2146 } else {
2147 }
2148 }
2149
2150 fn request_lsp<R: LspCommand>(
2151 &self,
2152 buffer_handle: ModelHandle<Buffer>,
2153 request: R,
2154 cx: &mut ModelContext<Self>,
2155 ) -> Task<Result<R::Response>>
2156 where
2157 <R::LspRequest as lsp::request::Request>::Result: Send,
2158 {
2159 let buffer = buffer_handle.read(cx);
2160 if self.is_local() {
2161 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
2162 if let Some((file, language_server)) = file.zip(buffer.language_server().cloned()) {
2163 let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
2164 return cx.spawn(|this, cx| async move {
2165 let response = language_server
2166 .request::<R::LspRequest>(lsp_params)
2167 .await
2168 .context("lsp request failed")?;
2169 request
2170 .response_from_lsp(response, this, buffer_handle, cx)
2171 .await
2172 });
2173 }
2174 } else if let Some(project_id) = self.remote_id() {
2175 let rpc = self.client.clone();
2176 let request_handle = self.start_buffer_request(cx);
2177 let message = request.to_proto(project_id, buffer);
2178 return cx.spawn(|this, cx| async move {
2179 let response = rpc.request(message).await?;
2180 request
2181 .response_from_proto(response, this, buffer_handle, request_handle, cx)
2182 .await
2183 });
2184 }
2185 Task::ready(Ok(Default::default()))
2186 }
2187
2188 pub fn find_or_create_local_worktree(
2189 &self,
2190 abs_path: impl AsRef<Path>,
2191 weak: bool,
2192 cx: &mut ModelContext<Self>,
2193 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
2194 let abs_path = abs_path.as_ref();
2195 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
2196 Task::ready(Ok((tree.clone(), relative_path.into())))
2197 } else {
2198 let worktree = self.create_local_worktree(abs_path, weak, cx);
2199 cx.foreground()
2200 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
2201 }
2202 }
2203
2204 pub fn find_local_worktree(
2205 &self,
2206 abs_path: &Path,
2207 cx: &AppContext,
2208 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
2209 for tree in self.worktrees(cx) {
2210 if let Some(relative_path) = tree
2211 .read(cx)
2212 .as_local()
2213 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
2214 {
2215 return Some((tree.clone(), relative_path.into()));
2216 }
2217 }
2218 None
2219 }
2220
2221 pub fn is_shared(&self) -> bool {
2222 match &self.client_state {
2223 ProjectClientState::Local { is_shared, .. } => *is_shared,
2224 ProjectClientState::Remote { .. } => false,
2225 }
2226 }
2227
2228 fn create_local_worktree(
2229 &self,
2230 abs_path: impl AsRef<Path>,
2231 weak: bool,
2232 cx: &mut ModelContext<Self>,
2233 ) -> Task<Result<ModelHandle<Worktree>>> {
2234 let fs = self.fs.clone();
2235 let client = self.client.clone();
2236 let path = Arc::from(abs_path.as_ref());
2237 cx.spawn(|project, mut cx| async move {
2238 let worktree = Worktree::local(client.clone(), path, weak, fs, &mut cx).await?;
2239
2240 let (remote_project_id, is_shared) = project.update(&mut cx, |project, cx| {
2241 project.add_worktree(&worktree, cx);
2242 (project.remote_id(), project.is_shared())
2243 });
2244
2245 if let Some(project_id) = remote_project_id {
2246 worktree
2247 .update(&mut cx, |worktree, cx| {
2248 worktree.as_local_mut().unwrap().register(project_id, cx)
2249 })
2250 .await?;
2251 if is_shared {
2252 worktree
2253 .update(&mut cx, |worktree, cx| {
2254 worktree.as_local_mut().unwrap().share(project_id, cx)
2255 })
2256 .await?;
2257 }
2258 }
2259
2260 Ok(worktree)
2261 })
2262 }
2263
2264 pub fn remove_worktree(&mut self, id: WorktreeId, cx: &mut ModelContext<Self>) {
2265 self.worktrees.retain(|worktree| {
2266 worktree
2267 .upgrade(cx)
2268 .map_or(false, |w| w.read(cx).id() != id)
2269 });
2270 cx.notify();
2271 }
2272
2273 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
2274 cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
2275 if worktree.read(cx).is_local() {
2276 cx.subscribe(&worktree, |this, worktree, _, cx| {
2277 this.update_local_worktree_buffers(worktree, cx);
2278 })
2279 .detach();
2280 }
2281
2282 let push_weak_handle = {
2283 let worktree = worktree.read(cx);
2284 worktree.is_local() && worktree.is_weak()
2285 };
2286 if push_weak_handle {
2287 cx.observe_release(&worktree, |this, cx| {
2288 this.worktrees
2289 .retain(|worktree| worktree.upgrade(cx).is_some());
2290 cx.notify();
2291 })
2292 .detach();
2293 self.worktrees
2294 .push(WorktreeHandle::Weak(worktree.downgrade()));
2295 } else {
2296 self.worktrees
2297 .push(WorktreeHandle::Strong(worktree.clone()));
2298 }
2299 cx.notify();
2300 }
2301
2302 fn update_local_worktree_buffers(
2303 &mut self,
2304 worktree_handle: ModelHandle<Worktree>,
2305 cx: &mut ModelContext<Self>,
2306 ) {
2307 let snapshot = worktree_handle.read(cx).snapshot();
2308 let mut buffers_to_delete = Vec::new();
2309 for (buffer_id, buffer) in &self.buffers_state.borrow().open_buffers {
2310 if let Some(buffer) = buffer.upgrade(cx) {
2311 buffer.update(cx, |buffer, cx| {
2312 if let Some(old_file) = File::from_dyn(buffer.file()) {
2313 if old_file.worktree != worktree_handle {
2314 return;
2315 }
2316
2317 let new_file = if let Some(entry) = old_file
2318 .entry_id
2319 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
2320 {
2321 File {
2322 is_local: true,
2323 entry_id: Some(entry.id),
2324 mtime: entry.mtime,
2325 path: entry.path.clone(),
2326 worktree: worktree_handle.clone(),
2327 }
2328 } else if let Some(entry) =
2329 snapshot.entry_for_path(old_file.path().as_ref())
2330 {
2331 File {
2332 is_local: true,
2333 entry_id: Some(entry.id),
2334 mtime: entry.mtime,
2335 path: entry.path.clone(),
2336 worktree: worktree_handle.clone(),
2337 }
2338 } else {
2339 File {
2340 is_local: true,
2341 entry_id: None,
2342 path: old_file.path().clone(),
2343 mtime: old_file.mtime(),
2344 worktree: worktree_handle.clone(),
2345 }
2346 };
2347
2348 if let Some(project_id) = self.remote_id() {
2349 self.client
2350 .send(proto::UpdateBufferFile {
2351 project_id,
2352 buffer_id: *buffer_id as u64,
2353 file: Some(new_file.to_proto()),
2354 })
2355 .log_err();
2356 }
2357 buffer.file_updated(Box::new(new_file), cx).detach();
2358 }
2359 });
2360 } else {
2361 buffers_to_delete.push(*buffer_id);
2362 }
2363 }
2364
2365 for buffer_id in buffers_to_delete {
2366 self.buffers_state
2367 .borrow_mut()
2368 .open_buffers
2369 .remove(&buffer_id);
2370 }
2371 }
2372
2373 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
2374 let new_active_entry = entry.and_then(|project_path| {
2375 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
2376 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
2377 Some(ProjectEntry {
2378 worktree_id: project_path.worktree_id,
2379 entry_id: entry.id,
2380 })
2381 });
2382 if new_active_entry != self.active_entry {
2383 self.active_entry = new_active_entry;
2384 cx.emit(Event::ActiveEntryChanged(new_active_entry));
2385 }
2386 }
2387
2388 pub fn is_running_disk_based_diagnostics(&self) -> bool {
2389 self.language_servers_with_diagnostics_running > 0
2390 }
2391
2392 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
2393 let mut summary = DiagnosticSummary::default();
2394 for (_, path_summary) in self.diagnostic_summaries(cx) {
2395 summary.error_count += path_summary.error_count;
2396 summary.warning_count += path_summary.warning_count;
2397 summary.info_count += path_summary.info_count;
2398 summary.hint_count += path_summary.hint_count;
2399 }
2400 summary
2401 }
2402
2403 pub fn diagnostic_summaries<'a>(
2404 &'a self,
2405 cx: &'a AppContext,
2406 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
2407 self.worktrees(cx).flat_map(move |worktree| {
2408 let worktree = worktree.read(cx);
2409 let worktree_id = worktree.id();
2410 worktree
2411 .diagnostic_summaries()
2412 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
2413 })
2414 }
2415
2416 pub fn disk_based_diagnostics_started(&mut self, cx: &mut ModelContext<Self>) {
2417 self.language_servers_with_diagnostics_running += 1;
2418 if self.language_servers_with_diagnostics_running == 1 {
2419 cx.emit(Event::DiskBasedDiagnosticsStarted);
2420 }
2421 }
2422
2423 pub fn disk_based_diagnostics_finished(&mut self, cx: &mut ModelContext<Self>) {
2424 cx.emit(Event::DiskBasedDiagnosticsUpdated);
2425 self.language_servers_with_diagnostics_running -= 1;
2426 if self.language_servers_with_diagnostics_running == 0 {
2427 cx.emit(Event::DiskBasedDiagnosticsFinished);
2428 }
2429 }
2430
2431 pub fn active_entry(&self) -> Option<ProjectEntry> {
2432 self.active_entry
2433 }
2434
2435 // RPC message handlers
2436
2437 async fn handle_unshare_project(
2438 this: ModelHandle<Self>,
2439 _: TypedEnvelope<proto::UnshareProject>,
2440 _: Arc<Client>,
2441 mut cx: AsyncAppContext,
2442 ) -> Result<()> {
2443 this.update(&mut cx, |this, cx| {
2444 if let ProjectClientState::Remote {
2445 sharing_has_stopped,
2446 ..
2447 } = &mut this.client_state
2448 {
2449 *sharing_has_stopped = true;
2450 this.collaborators.clear();
2451 cx.notify();
2452 } else {
2453 unreachable!()
2454 }
2455 });
2456
2457 Ok(())
2458 }
2459
2460 async fn handle_add_collaborator(
2461 this: ModelHandle<Self>,
2462 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
2463 _: Arc<Client>,
2464 mut cx: AsyncAppContext,
2465 ) -> Result<()> {
2466 let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
2467 let collaborator = envelope
2468 .payload
2469 .collaborator
2470 .take()
2471 .ok_or_else(|| anyhow!("empty collaborator"))?;
2472
2473 let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
2474 this.update(&mut cx, |this, cx| {
2475 this.collaborators
2476 .insert(collaborator.peer_id, collaborator);
2477 cx.notify();
2478 });
2479
2480 Ok(())
2481 }
2482
2483 async fn handle_remove_collaborator(
2484 this: ModelHandle<Self>,
2485 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
2486 _: Arc<Client>,
2487 mut cx: AsyncAppContext,
2488 ) -> Result<()> {
2489 this.update(&mut cx, |this, cx| {
2490 let peer_id = PeerId(envelope.payload.peer_id);
2491 let replica_id = this
2492 .collaborators
2493 .remove(&peer_id)
2494 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
2495 .replica_id;
2496 this.shared_buffers.remove(&peer_id);
2497 for (_, buffer) in &this.buffers_state.borrow().open_buffers {
2498 if let Some(buffer) = buffer.upgrade(cx) {
2499 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
2500 }
2501 }
2502 cx.notify();
2503 Ok(())
2504 })
2505 }
2506
2507 async fn handle_register_worktree(
2508 this: ModelHandle<Self>,
2509 envelope: TypedEnvelope<proto::RegisterWorktree>,
2510 client: Arc<Client>,
2511 mut cx: AsyncAppContext,
2512 ) -> Result<()> {
2513 this.update(&mut cx, |this, cx| {
2514 let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
2515 let replica_id = this.replica_id();
2516 let worktree = proto::Worktree {
2517 id: envelope.payload.worktree_id,
2518 root_name: envelope.payload.root_name,
2519 entries: Default::default(),
2520 diagnostic_summaries: Default::default(),
2521 weak: envelope.payload.weak,
2522 };
2523 let (worktree, load_task) =
2524 Worktree::remote(remote_id, replica_id, worktree, client, cx);
2525 this.add_worktree(&worktree, cx);
2526 load_task.detach();
2527 Ok(())
2528 })
2529 }
2530
2531 async fn handle_unregister_worktree(
2532 this: ModelHandle<Self>,
2533 envelope: TypedEnvelope<proto::UnregisterWorktree>,
2534 _: Arc<Client>,
2535 mut cx: AsyncAppContext,
2536 ) -> Result<()> {
2537 this.update(&mut cx, |this, cx| {
2538 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2539 this.remove_worktree(worktree_id, cx);
2540 Ok(())
2541 })
2542 }
2543
2544 async fn handle_update_worktree(
2545 this: ModelHandle<Self>,
2546 envelope: TypedEnvelope<proto::UpdateWorktree>,
2547 _: Arc<Client>,
2548 mut cx: AsyncAppContext,
2549 ) -> Result<()> {
2550 this.update(&mut cx, |this, cx| {
2551 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2552 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
2553 worktree.update(cx, |worktree, _| {
2554 let worktree = worktree.as_remote_mut().unwrap();
2555 worktree.update_from_remote(envelope)
2556 })?;
2557 }
2558 Ok(())
2559 })
2560 }
2561
2562 async fn handle_update_diagnostic_summary(
2563 this: ModelHandle<Self>,
2564 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
2565 _: Arc<Client>,
2566 mut cx: AsyncAppContext,
2567 ) -> Result<()> {
2568 this.update(&mut cx, |this, cx| {
2569 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2570 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
2571 if let Some(summary) = envelope.payload.summary {
2572 let project_path = ProjectPath {
2573 worktree_id,
2574 path: Path::new(&summary.path).into(),
2575 };
2576 worktree.update(cx, |worktree, _| {
2577 worktree
2578 .as_remote_mut()
2579 .unwrap()
2580 .update_diagnostic_summary(project_path.path.clone(), &summary);
2581 });
2582 cx.emit(Event::DiagnosticsUpdated(project_path));
2583 }
2584 }
2585 Ok(())
2586 })
2587 }
2588
2589 async fn handle_disk_based_diagnostics_updating(
2590 this: ModelHandle<Self>,
2591 _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
2592 _: Arc<Client>,
2593 mut cx: AsyncAppContext,
2594 ) -> Result<()> {
2595 this.update(&mut cx, |this, cx| this.disk_based_diagnostics_started(cx));
2596 Ok(())
2597 }
2598
2599 async fn handle_disk_based_diagnostics_updated(
2600 this: ModelHandle<Self>,
2601 _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
2602 _: Arc<Client>,
2603 mut cx: AsyncAppContext,
2604 ) -> Result<()> {
2605 this.update(&mut cx, |this, cx| this.disk_based_diagnostics_finished(cx));
2606 Ok(())
2607 }
2608
2609 async fn handle_update_buffer(
2610 this: ModelHandle<Self>,
2611 envelope: TypedEnvelope<proto::UpdateBuffer>,
2612 _: Arc<Client>,
2613 mut cx: AsyncAppContext,
2614 ) -> Result<()> {
2615 this.update(&mut cx, |this, cx| {
2616 let payload = envelope.payload.clone();
2617 let buffer_id = payload.buffer_id;
2618 let ops = payload
2619 .operations
2620 .into_iter()
2621 .map(|op| language::proto::deserialize_operation(op))
2622 .collect::<Result<Vec<_>, _>>()?;
2623 let is_remote = this.is_remote();
2624 let mut buffers_state = this.buffers_state.borrow_mut();
2625 let buffer_request_count = buffers_state.buffer_request_count;
2626 match buffers_state.open_buffers.entry(buffer_id) {
2627 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
2628 OpenBuffer::Loaded(buffer) => {
2629 if let Some(buffer) = buffer.upgrade(cx) {
2630 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
2631 } else if is_remote && buffer_request_count > 0 {
2632 e.insert(OpenBuffer::Loading(ops));
2633 }
2634 }
2635 OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
2636 },
2637 hash_map::Entry::Vacant(e) => {
2638 if is_remote && buffer_request_count > 0 {
2639 e.insert(OpenBuffer::Loading(ops));
2640 }
2641 }
2642 }
2643 Ok(())
2644 })
2645 }
2646
2647 async fn handle_update_buffer_file(
2648 this: ModelHandle<Self>,
2649 envelope: TypedEnvelope<proto::UpdateBufferFile>,
2650 _: Arc<Client>,
2651 mut cx: AsyncAppContext,
2652 ) -> Result<()> {
2653 this.update(&mut cx, |this, cx| {
2654 let payload = envelope.payload.clone();
2655 let buffer_id = payload.buffer_id;
2656 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
2657 let worktree = this
2658 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
2659 .ok_or_else(|| anyhow!("no such worktree"))?;
2660 let file = File::from_proto(file, worktree.clone(), cx)?;
2661 let buffer = this
2662 .buffers_state
2663 .borrow_mut()
2664 .open_buffers
2665 .get_mut(&buffer_id)
2666 .and_then(|b| b.upgrade(cx))
2667 .ok_or_else(|| anyhow!("no such buffer"))?;
2668 buffer.update(cx, |buffer, cx| {
2669 buffer.file_updated(Box::new(file), cx).detach();
2670 });
2671 Ok(())
2672 })
2673 }
2674
2675 async fn handle_save_buffer(
2676 this: ModelHandle<Self>,
2677 envelope: TypedEnvelope<proto::SaveBuffer>,
2678 _: Arc<Client>,
2679 mut cx: AsyncAppContext,
2680 ) -> Result<proto::BufferSaved> {
2681 let buffer_id = envelope.payload.buffer_id;
2682 let sender_id = envelope.original_sender_id()?;
2683 let requested_version = envelope.payload.version.try_into()?;
2684
2685 let (project_id, buffer) = this.update(&mut cx, |this, _| {
2686 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
2687 let buffer = this
2688 .shared_buffers
2689 .get(&sender_id)
2690 .and_then(|shared_buffers| shared_buffers.get(&buffer_id).cloned())
2691 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
2692 Ok::<_, anyhow::Error>((project_id, buffer))
2693 })?;
2694
2695 if !buffer
2696 .read_with(&cx, |buffer, _| buffer.version())
2697 .observed_all(&requested_version)
2698 {
2699 Err(anyhow!("save request depends on unreceived edits"))?;
2700 }
2701
2702 let (saved_version, mtime) = buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
2703 Ok(proto::BufferSaved {
2704 project_id,
2705 buffer_id,
2706 version: (&saved_version).into(),
2707 mtime: Some(mtime.into()),
2708 })
2709 }
2710
2711 async fn handle_format_buffers(
2712 this: ModelHandle<Self>,
2713 envelope: TypedEnvelope<proto::FormatBuffers>,
2714 _: Arc<Client>,
2715 mut cx: AsyncAppContext,
2716 ) -> Result<proto::FormatBuffersResponse> {
2717 let sender_id = envelope.original_sender_id()?;
2718 let format = this.update(&mut cx, |this, cx| {
2719 let shared_buffers = this
2720 .shared_buffers
2721 .get(&sender_id)
2722 .ok_or_else(|| anyhow!("peer has no buffers"))?;
2723 let mut buffers = HashSet::default();
2724 for buffer_id in &envelope.payload.buffer_ids {
2725 buffers.insert(
2726 shared_buffers
2727 .get(buffer_id)
2728 .cloned()
2729 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
2730 );
2731 }
2732 Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
2733 })?;
2734
2735 let project_transaction = format.await?;
2736 let project_transaction = this.update(&mut cx, |this, cx| {
2737 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
2738 });
2739 Ok(proto::FormatBuffersResponse {
2740 transaction: Some(project_transaction),
2741 })
2742 }
2743
2744 async fn handle_get_completions(
2745 this: ModelHandle<Self>,
2746 envelope: TypedEnvelope<proto::GetCompletions>,
2747 _: Arc<Client>,
2748 mut cx: AsyncAppContext,
2749 ) -> Result<proto::GetCompletionsResponse> {
2750 let sender_id = envelope.original_sender_id()?;
2751 let position = envelope
2752 .payload
2753 .position
2754 .and_then(language::proto::deserialize_anchor)
2755 .ok_or_else(|| anyhow!("invalid position"))?;
2756 let version = clock::Global::from(envelope.payload.version);
2757 let buffer = this.read_with(&cx, |this, _| {
2758 this.shared_buffers
2759 .get(&sender_id)
2760 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2761 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
2762 })?;
2763 if !buffer
2764 .read_with(&cx, |buffer, _| buffer.version())
2765 .observed_all(&version)
2766 {
2767 Err(anyhow!("completion request depends on unreceived edits"))?;
2768 }
2769 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
2770 let completions = this
2771 .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
2772 .await?;
2773
2774 Ok(proto::GetCompletionsResponse {
2775 completions: completions
2776 .iter()
2777 .map(language::proto::serialize_completion)
2778 .collect(),
2779 version: (&version).into(),
2780 })
2781 }
2782
2783 async fn handle_apply_additional_edits_for_completion(
2784 this: ModelHandle<Self>,
2785 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
2786 _: Arc<Client>,
2787 mut cx: AsyncAppContext,
2788 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
2789 let sender_id = envelope.original_sender_id()?;
2790 let apply_additional_edits = this.update(&mut cx, |this, cx| {
2791 let buffer = this
2792 .shared_buffers
2793 .get(&sender_id)
2794 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2795 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2796 let language = buffer.read(cx).language();
2797 let completion = language::proto::deserialize_completion(
2798 envelope
2799 .payload
2800 .completion
2801 .ok_or_else(|| anyhow!("invalid completion"))?,
2802 language,
2803 )?;
2804 Ok::<_, anyhow::Error>(
2805 this.apply_additional_edits_for_completion(buffer, completion, false, cx),
2806 )
2807 })?;
2808
2809 Ok(proto::ApplyCompletionAdditionalEditsResponse {
2810 transaction: apply_additional_edits
2811 .await?
2812 .as_ref()
2813 .map(language::proto::serialize_transaction),
2814 })
2815 }
2816
2817 async fn handle_get_code_actions(
2818 this: ModelHandle<Self>,
2819 envelope: TypedEnvelope<proto::GetCodeActions>,
2820 _: Arc<Client>,
2821 mut cx: AsyncAppContext,
2822 ) -> Result<proto::GetCodeActionsResponse> {
2823 let sender_id = envelope.original_sender_id()?;
2824 let start = envelope
2825 .payload
2826 .start
2827 .and_then(language::proto::deserialize_anchor)
2828 .ok_or_else(|| anyhow!("invalid start"))?;
2829 let end = envelope
2830 .payload
2831 .end
2832 .and_then(language::proto::deserialize_anchor)
2833 .ok_or_else(|| anyhow!("invalid end"))?;
2834 let buffer = this.update(&mut cx, |this, _| {
2835 this.shared_buffers
2836 .get(&sender_id)
2837 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2838 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
2839 })?;
2840 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
2841 if !version.observed(start.timestamp) || !version.observed(end.timestamp) {
2842 Err(anyhow!("code action request references unreceived edits"))?;
2843 }
2844 let code_actions = this.update(&mut cx, |this, cx| {
2845 Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
2846 })?;
2847
2848 Ok(proto::GetCodeActionsResponse {
2849 actions: code_actions
2850 .await?
2851 .iter()
2852 .map(language::proto::serialize_code_action)
2853 .collect(),
2854 version: (&version).into(),
2855 })
2856 }
2857
2858 async fn handle_apply_code_action(
2859 this: ModelHandle<Self>,
2860 envelope: TypedEnvelope<proto::ApplyCodeAction>,
2861 _: Arc<Client>,
2862 mut cx: AsyncAppContext,
2863 ) -> Result<proto::ApplyCodeActionResponse> {
2864 let sender_id = envelope.original_sender_id()?;
2865 let action = language::proto::deserialize_code_action(
2866 envelope
2867 .payload
2868 .action
2869 .ok_or_else(|| anyhow!("invalid action"))?,
2870 )?;
2871 let apply_code_action = this.update(&mut cx, |this, cx| {
2872 let buffer = this
2873 .shared_buffers
2874 .get(&sender_id)
2875 .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2876 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2877 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
2878 })?;
2879
2880 let project_transaction = apply_code_action.await?;
2881 let project_transaction = this.update(&mut cx, |this, cx| {
2882 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
2883 });
2884 Ok(proto::ApplyCodeActionResponse {
2885 transaction: Some(project_transaction),
2886 })
2887 }
2888
2889 async fn handle_lsp_command<T: LspCommand>(
2890 this: ModelHandle<Self>,
2891 envelope: TypedEnvelope<T::ProtoRequest>,
2892 _: Arc<Client>,
2893 mut cx: AsyncAppContext,
2894 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
2895 where
2896 <T::LspRequest as lsp::request::Request>::Result: Send,
2897 {
2898 let sender_id = envelope.original_sender_id()?;
2899 let (request, buffer_version) = this.update(&mut cx, |this, cx| {
2900 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
2901 let buffer_handle = this
2902 .shared_buffers
2903 .get(&sender_id)
2904 .and_then(|shared_buffers| shared_buffers.get(&buffer_id).cloned())
2905 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
2906 let buffer = buffer_handle.read(cx);
2907 let buffer_version = buffer.version();
2908 let request = T::from_proto(envelope.payload, this, buffer)?;
2909 Ok::<_, anyhow::Error>((this.request_lsp(buffer_handle, request, cx), buffer_version))
2910 })?;
2911 let response = request.await?;
2912 this.update(&mut cx, |this, cx| {
2913 Ok(T::response_to_proto(
2914 response,
2915 this,
2916 sender_id,
2917 &buffer_version,
2918 cx,
2919 ))
2920 })
2921 }
2922
2923 async fn handle_get_project_symbols(
2924 this: ModelHandle<Self>,
2925 envelope: TypedEnvelope<proto::GetProjectSymbols>,
2926 _: Arc<Client>,
2927 mut cx: AsyncAppContext,
2928 ) -> Result<proto::GetProjectSymbolsResponse> {
2929 let symbols = this
2930 .update(&mut cx, |this, cx| {
2931 this.symbols(&envelope.payload.query, cx)
2932 })
2933 .await?;
2934
2935 Ok(proto::GetProjectSymbolsResponse {
2936 symbols: symbols.iter().map(serialize_symbol).collect(),
2937 })
2938 }
2939
2940 async fn handle_open_buffer_for_symbol(
2941 this: ModelHandle<Self>,
2942 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
2943 _: Arc<Client>,
2944 mut cx: AsyncAppContext,
2945 ) -> Result<proto::OpenBufferForSymbolResponse> {
2946 let peer_id = envelope.original_sender_id()?;
2947 let symbol = envelope
2948 .payload
2949 .symbol
2950 .ok_or_else(|| anyhow!("invalid symbol"))?;
2951 let symbol = this.read_with(&cx, |this, _| {
2952 let symbol = this.deserialize_symbol(symbol)?;
2953 let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
2954 if signature == symbol.signature {
2955 Ok(symbol)
2956 } else {
2957 Err(anyhow!("invalid symbol signature"))
2958 }
2959 })?;
2960 let buffer = this
2961 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
2962 .await?;
2963
2964 Ok(proto::OpenBufferForSymbolResponse {
2965 buffer: Some(this.update(&mut cx, |this, cx| {
2966 this.serialize_buffer_for_peer(&buffer, peer_id, cx)
2967 })),
2968 })
2969 }
2970
2971 fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
2972 let mut hasher = Sha256::new();
2973 hasher.update(worktree_id.to_proto().to_be_bytes());
2974 hasher.update(path.to_string_lossy().as_bytes());
2975 hasher.update(self.nonce.to_be_bytes());
2976 hasher.finalize().as_slice().try_into().unwrap()
2977 }
2978
2979 async fn handle_open_buffer(
2980 this: ModelHandle<Self>,
2981 envelope: TypedEnvelope<proto::OpenBuffer>,
2982 _: Arc<Client>,
2983 mut cx: AsyncAppContext,
2984 ) -> Result<proto::OpenBufferResponse> {
2985 let peer_id = envelope.original_sender_id()?;
2986 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2987 let open_buffer = this.update(&mut cx, |this, cx| {
2988 this.open_buffer(
2989 ProjectPath {
2990 worktree_id,
2991 path: PathBuf::from(envelope.payload.path).into(),
2992 },
2993 cx,
2994 )
2995 });
2996
2997 let buffer = open_buffer.await?;
2998 this.update(&mut cx, |this, cx| {
2999 Ok(proto::OpenBufferResponse {
3000 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
3001 })
3002 })
3003 }
3004
3005 fn serialize_project_transaction_for_peer(
3006 &mut self,
3007 project_transaction: ProjectTransaction,
3008 peer_id: PeerId,
3009 cx: &AppContext,
3010 ) -> proto::ProjectTransaction {
3011 let mut serialized_transaction = proto::ProjectTransaction {
3012 buffers: Default::default(),
3013 transactions: Default::default(),
3014 };
3015 for (buffer, transaction) in project_transaction.0 {
3016 serialized_transaction
3017 .buffers
3018 .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
3019 serialized_transaction
3020 .transactions
3021 .push(language::proto::serialize_transaction(&transaction));
3022 }
3023 serialized_transaction
3024 }
3025
3026 fn deserialize_project_transaction(
3027 &mut self,
3028 message: proto::ProjectTransaction,
3029 push_to_history: bool,
3030 request_handle: BufferRequestHandle,
3031 cx: &mut ModelContext<Self>,
3032 ) -> Task<Result<ProjectTransaction>> {
3033 cx.spawn(|this, mut cx| async move {
3034 let mut project_transaction = ProjectTransaction::default();
3035 for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
3036 let buffer = this
3037 .update(&mut cx, |this, cx| {
3038 this.deserialize_buffer(buffer, request_handle.clone(), cx)
3039 })
3040 .await?;
3041 let transaction = language::proto::deserialize_transaction(transaction)?;
3042 project_transaction.0.insert(buffer, transaction);
3043 }
3044
3045 for (buffer, transaction) in &project_transaction.0 {
3046 buffer
3047 .update(&mut cx, |buffer, _| {
3048 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3049 })
3050 .await;
3051
3052 if push_to_history {
3053 buffer.update(&mut cx, |buffer, _| {
3054 buffer.push_transaction(transaction.clone(), Instant::now());
3055 });
3056 }
3057 }
3058
3059 Ok(project_transaction)
3060 })
3061 }
3062
3063 fn serialize_buffer_for_peer(
3064 &mut self,
3065 buffer: &ModelHandle<Buffer>,
3066 peer_id: PeerId,
3067 cx: &AppContext,
3068 ) -> proto::Buffer {
3069 let buffer_id = buffer.read(cx).remote_id();
3070 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
3071 match shared_buffers.entry(buffer_id) {
3072 hash_map::Entry::Occupied(_) => proto::Buffer {
3073 variant: Some(proto::buffer::Variant::Id(buffer_id)),
3074 },
3075 hash_map::Entry::Vacant(entry) => {
3076 entry.insert(buffer.clone());
3077 proto::Buffer {
3078 variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
3079 }
3080 }
3081 }
3082 }
3083
3084 fn deserialize_buffer(
3085 &mut self,
3086 buffer: proto::Buffer,
3087 request_handle: BufferRequestHandle,
3088 cx: &mut ModelContext<Self>,
3089 ) -> Task<Result<ModelHandle<Buffer>>> {
3090 let replica_id = self.replica_id();
3091
3092 let mut opened_buffer_tx = self.opened_buffer.clone();
3093 let mut opened_buffer_rx = self.opened_buffer.subscribe();
3094 cx.spawn(|this, mut cx| async move {
3095 match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
3096 proto::buffer::Variant::Id(id) => {
3097 let buffer = loop {
3098 let buffer = this.read_with(&cx, |this, cx| {
3099 this.buffers_state
3100 .borrow()
3101 .open_buffers
3102 .get(&id)
3103 .and_then(|buffer| buffer.upgrade(cx))
3104 });
3105 if let Some(buffer) = buffer {
3106 break buffer;
3107 }
3108 opened_buffer_rx
3109 .recv()
3110 .await
3111 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
3112 };
3113 Ok(buffer)
3114 }
3115 proto::buffer::Variant::State(mut buffer) => {
3116 let mut buffer_worktree = None;
3117 let mut buffer_file = None;
3118 if let Some(file) = buffer.file.take() {
3119 this.read_with(&cx, |this, cx| {
3120 let worktree_id = WorktreeId::from_proto(file.worktree_id);
3121 let worktree =
3122 this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
3123 anyhow!("no worktree found for id {}", file.worktree_id)
3124 })?;
3125 buffer_file =
3126 Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
3127 as Box<dyn language::File>);
3128 buffer_worktree = Some(worktree);
3129 Ok::<_, anyhow::Error>(())
3130 })?;
3131 }
3132
3133 let buffer = cx.add_model(|cx| {
3134 Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
3135 });
3136
3137 request_handle.preserve_buffer(buffer.clone());
3138 this.update(&mut cx, |this, cx| {
3139 this.register_buffer(&buffer, buffer_worktree.as_ref(), cx)
3140 })?;
3141
3142 let _ = opened_buffer_tx.send(()).await;
3143 Ok(buffer)
3144 }
3145 }
3146 })
3147 }
3148
3149 fn deserialize_symbol(&self, serialized_symbol: proto::Symbol) -> Result<Symbol> {
3150 let language = self
3151 .languages
3152 .get_language(&serialized_symbol.language_name);
3153 let start = serialized_symbol
3154 .start
3155 .ok_or_else(|| anyhow!("invalid start"))?;
3156 let end = serialized_symbol
3157 .end
3158 .ok_or_else(|| anyhow!("invalid end"))?;
3159 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
3160 Ok(Symbol {
3161 source_worktree_id: WorktreeId::from_proto(serialized_symbol.source_worktree_id),
3162 worktree_id: WorktreeId::from_proto(serialized_symbol.worktree_id),
3163 language_name: serialized_symbol.language_name.clone(),
3164 label: language
3165 .and_then(|language| language.label_for_symbol(&serialized_symbol.name, kind))
3166 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None)),
3167 name: serialized_symbol.name,
3168 path: PathBuf::from(serialized_symbol.path),
3169 range: PointUtf16::new(start.row, start.column)..PointUtf16::new(end.row, end.column),
3170 kind,
3171 signature: serialized_symbol
3172 .signature
3173 .try_into()
3174 .map_err(|_| anyhow!("invalid signature"))?,
3175 })
3176 }
3177
3178 async fn handle_close_buffer(
3179 this: ModelHandle<Self>,
3180 envelope: TypedEnvelope<proto::CloseBuffer>,
3181 _: Arc<Client>,
3182 mut cx: AsyncAppContext,
3183 ) -> Result<()> {
3184 this.update(&mut cx, |this, cx| {
3185 if let Some(shared_buffers) =
3186 this.shared_buffers.get_mut(&envelope.original_sender_id()?)
3187 {
3188 shared_buffers.remove(&envelope.payload.buffer_id);
3189 cx.notify();
3190 }
3191 Ok(())
3192 })
3193 }
3194
3195 async fn handle_buffer_saved(
3196 this: ModelHandle<Self>,
3197 envelope: TypedEnvelope<proto::BufferSaved>,
3198 _: Arc<Client>,
3199 mut cx: AsyncAppContext,
3200 ) -> Result<()> {
3201 let version = envelope.payload.version.try_into()?;
3202 let mtime = envelope
3203 .payload
3204 .mtime
3205 .ok_or_else(|| anyhow!("missing mtime"))?
3206 .into();
3207
3208 this.update(&mut cx, |this, cx| {
3209 let buffer = this
3210 .buffers_state
3211 .borrow()
3212 .open_buffers
3213 .get(&envelope.payload.buffer_id)
3214 .and_then(|buffer| buffer.upgrade(cx));
3215 if let Some(buffer) = buffer {
3216 buffer.update(cx, |buffer, cx| {
3217 buffer.did_save(version, mtime, None, cx);
3218 });
3219 }
3220 Ok(())
3221 })
3222 }
3223
3224 async fn handle_buffer_reloaded(
3225 this: ModelHandle<Self>,
3226 envelope: TypedEnvelope<proto::BufferReloaded>,
3227 _: Arc<Client>,
3228 mut cx: AsyncAppContext,
3229 ) -> Result<()> {
3230 let payload = envelope.payload.clone();
3231 let version = payload.version.try_into()?;
3232 let mtime = payload
3233 .mtime
3234 .ok_or_else(|| anyhow!("missing mtime"))?
3235 .into();
3236 this.update(&mut cx, |this, cx| {
3237 let buffer = this
3238 .buffers_state
3239 .borrow()
3240 .open_buffers
3241 .get(&payload.buffer_id)
3242 .and_then(|buffer| buffer.upgrade(cx));
3243 if let Some(buffer) = buffer {
3244 buffer.update(cx, |buffer, cx| {
3245 buffer.did_reload(version, mtime, cx);
3246 });
3247 }
3248 Ok(())
3249 })
3250 }
3251
3252 pub fn match_paths<'a>(
3253 &self,
3254 query: &'a str,
3255 include_ignored: bool,
3256 smart_case: bool,
3257 max_results: usize,
3258 cancel_flag: &'a AtomicBool,
3259 cx: &AppContext,
3260 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
3261 let worktrees = self
3262 .worktrees(cx)
3263 .filter(|worktree| !worktree.read(cx).is_weak())
3264 .collect::<Vec<_>>();
3265 let include_root_name = worktrees.len() > 1;
3266 let candidate_sets = worktrees
3267 .into_iter()
3268 .map(|worktree| CandidateSet {
3269 snapshot: worktree.read(cx).snapshot(),
3270 include_ignored,
3271 include_root_name,
3272 })
3273 .collect::<Vec<_>>();
3274
3275 let background = cx.background().clone();
3276 async move {
3277 fuzzy::match_paths(
3278 candidate_sets.as_slice(),
3279 query,
3280 smart_case,
3281 max_results,
3282 cancel_flag,
3283 background,
3284 )
3285 .await
3286 }
3287 }
3288}
3289
3290impl BufferRequestHandle {
3291 fn new(state: Rc<RefCell<ProjectBuffers>>, cx: &AppContext) -> Self {
3292 {
3293 let state = &mut *state.borrow_mut();
3294 state.buffer_request_count += 1;
3295 if state.buffer_request_count == 1 {
3296 state.preserved_buffers.extend(
3297 state
3298 .open_buffers
3299 .values()
3300 .filter_map(|buffer| buffer.upgrade(cx)),
3301 )
3302 }
3303 }
3304 Self(state)
3305 }
3306
3307 fn preserve_buffer(&self, buffer: ModelHandle<Buffer>) {
3308 self.0.borrow_mut().preserved_buffers.push(buffer);
3309 }
3310}
3311
3312impl Clone for BufferRequestHandle {
3313 fn clone(&self) -> Self {
3314 self.0.borrow_mut().buffer_request_count += 1;
3315 Self(self.0.clone())
3316 }
3317}
3318
3319impl Drop for BufferRequestHandle {
3320 fn drop(&mut self) {
3321 let mut state = self.0.borrow_mut();
3322 state.buffer_request_count -= 1;
3323 if state.buffer_request_count == 0 {
3324 state.preserved_buffers.clear();
3325 state
3326 .open_buffers
3327 .retain(|_, buffer| matches!(buffer, OpenBuffer::Loaded(_)))
3328 }
3329 }
3330}
3331
3332impl WorktreeHandle {
3333 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
3334 match self {
3335 WorktreeHandle::Strong(handle) => Some(handle.clone()),
3336 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
3337 }
3338 }
3339}
3340
3341impl OpenBuffer {
3342 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
3343 match self {
3344 OpenBuffer::Loaded(handle) => handle.upgrade(cx),
3345 OpenBuffer::Loading(_) => None,
3346 }
3347 }
3348}
3349
3350struct CandidateSet {
3351 snapshot: Snapshot,
3352 include_ignored: bool,
3353 include_root_name: bool,
3354}
3355
3356impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
3357 type Candidates = CandidateSetIter<'a>;
3358
3359 fn id(&self) -> usize {
3360 self.snapshot.id().to_usize()
3361 }
3362
3363 fn len(&self) -> usize {
3364 if self.include_ignored {
3365 self.snapshot.file_count()
3366 } else {
3367 self.snapshot.visible_file_count()
3368 }
3369 }
3370
3371 fn prefix(&self) -> Arc<str> {
3372 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
3373 self.snapshot.root_name().into()
3374 } else if self.include_root_name {
3375 format!("{}/", self.snapshot.root_name()).into()
3376 } else {
3377 "".into()
3378 }
3379 }
3380
3381 fn candidates(&'a self, start: usize) -> Self::Candidates {
3382 CandidateSetIter {
3383 traversal: self.snapshot.files(self.include_ignored, start),
3384 }
3385 }
3386}
3387
3388struct CandidateSetIter<'a> {
3389 traversal: Traversal<'a>,
3390}
3391
3392impl<'a> Iterator for CandidateSetIter<'a> {
3393 type Item = PathMatchCandidate<'a>;
3394
3395 fn next(&mut self) -> Option<Self::Item> {
3396 self.traversal.next().map(|entry| {
3397 if let EntryKind::File(char_bag) = entry.kind {
3398 PathMatchCandidate {
3399 path: &entry.path,
3400 char_bag,
3401 }
3402 } else {
3403 unreachable!()
3404 }
3405 })
3406 }
3407}
3408
3409impl Entity for Project {
3410 type Event = Event;
3411
3412 fn release(&mut self, _: &mut gpui::MutableAppContext) {
3413 match &self.client_state {
3414 ProjectClientState::Local { remote_id_rx, .. } => {
3415 if let Some(project_id) = *remote_id_rx.borrow() {
3416 self.client
3417 .send(proto::UnregisterProject { project_id })
3418 .log_err();
3419 }
3420 }
3421 ProjectClientState::Remote { remote_id, .. } => {
3422 self.client
3423 .send(proto::LeaveProject {
3424 project_id: *remote_id,
3425 })
3426 .log_err();
3427 }
3428 }
3429 }
3430
3431 fn app_will_quit(
3432 &mut self,
3433 _: &mut MutableAppContext,
3434 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
3435 let shutdown_futures = self
3436 .language_servers
3437 .drain()
3438 .filter_map(|(_, server)| server.shutdown())
3439 .collect::<Vec<_>>();
3440 Some(
3441 async move {
3442 futures::future::join_all(shutdown_futures).await;
3443 }
3444 .boxed(),
3445 )
3446 }
3447}
3448
3449impl Collaborator {
3450 fn from_proto(
3451 message: proto::Collaborator,
3452 user_store: &ModelHandle<UserStore>,
3453 cx: &mut AsyncAppContext,
3454 ) -> impl Future<Output = Result<Self>> {
3455 let user = user_store.update(cx, |user_store, cx| {
3456 user_store.fetch_user(message.user_id, cx)
3457 });
3458
3459 async move {
3460 Ok(Self {
3461 peer_id: PeerId(message.peer_id),
3462 user: user.await?,
3463 replica_id: message.replica_id as ReplicaId,
3464 })
3465 }
3466 }
3467}
3468
3469impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
3470 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
3471 Self {
3472 worktree_id,
3473 path: path.as_ref().into(),
3474 }
3475 }
3476}
3477
3478impl From<lsp::CreateFileOptions> for fs::CreateOptions {
3479 fn from(options: lsp::CreateFileOptions) -> Self {
3480 Self {
3481 overwrite: options.overwrite.unwrap_or(false),
3482 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
3483 }
3484 }
3485}
3486
3487impl From<lsp::RenameFileOptions> for fs::RenameOptions {
3488 fn from(options: lsp::RenameFileOptions) -> Self {
3489 Self {
3490 overwrite: options.overwrite.unwrap_or(false),
3491 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
3492 }
3493 }
3494}
3495
3496impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
3497 fn from(options: lsp::DeleteFileOptions) -> Self {
3498 Self {
3499 recursive: options.recursive.unwrap_or(false),
3500 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
3501 }
3502 }
3503}
3504
3505fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
3506 proto::Symbol {
3507 source_worktree_id: symbol.source_worktree_id.to_proto(),
3508 worktree_id: symbol.worktree_id.to_proto(),
3509 language_name: symbol.language_name.clone(),
3510 name: symbol.name.clone(),
3511 kind: unsafe { mem::transmute(symbol.kind) },
3512 path: symbol.path.to_string_lossy().to_string(),
3513 start: Some(proto::Point {
3514 row: symbol.range.start.row,
3515 column: symbol.range.start.column,
3516 }),
3517 end: Some(proto::Point {
3518 row: symbol.range.end.row,
3519 column: symbol.range.end.column,
3520 }),
3521 signature: symbol.signature.to_vec(),
3522 }
3523}
3524
3525fn relativize_path(base: &Path, path: &Path) -> PathBuf {
3526 let mut path_components = path.components();
3527 let mut base_components = base.components();
3528 let mut components: Vec<Component> = Vec::new();
3529 loop {
3530 match (path_components.next(), base_components.next()) {
3531 (None, None) => break,
3532 (Some(a), None) => {
3533 components.push(a);
3534 components.extend(path_components.by_ref());
3535 break;
3536 }
3537 (None, _) => components.push(Component::ParentDir),
3538 (Some(a), Some(b)) if components.is_empty() && a == b => (),
3539 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
3540 (Some(a), Some(_)) => {
3541 components.push(Component::ParentDir);
3542 for _ in base_components {
3543 components.push(Component::ParentDir);
3544 }
3545 components.push(a);
3546 components.extend(path_components.by_ref());
3547 break;
3548 }
3549 }
3550 }
3551 components.iter().map(|c| c.as_os_str()).collect()
3552}
3553
3554#[cfg(test)]
3555mod tests {
3556 use super::{Event, *};
3557 use fs::RealFs;
3558 use futures::StreamExt;
3559 use gpui::test::subscribe;
3560 use language::{
3561 tree_sitter_rust, AnchorRangeExt, Diagnostic, LanguageConfig, LanguageServerConfig, Point,
3562 };
3563 use lsp::Url;
3564 use serde_json::json;
3565 use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
3566 use unindent::Unindent as _;
3567 use util::test::temp_tree;
3568 use worktree::WorktreeHandle as _;
3569
3570 #[gpui::test]
3571 async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
3572 let dir = temp_tree(json!({
3573 "root": {
3574 "apple": "",
3575 "banana": {
3576 "carrot": {
3577 "date": "",
3578 "endive": "",
3579 }
3580 },
3581 "fennel": {
3582 "grape": "",
3583 }
3584 }
3585 }));
3586
3587 let root_link_path = dir.path().join("root_link");
3588 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
3589 unix::fs::symlink(
3590 &dir.path().join("root/fennel"),
3591 &dir.path().join("root/finnochio"),
3592 )
3593 .unwrap();
3594
3595 let project = Project::test(Arc::new(RealFs), &mut cx);
3596
3597 let (tree, _) = project
3598 .update(&mut cx, |project, cx| {
3599 project.find_or_create_local_worktree(&root_link_path, false, cx)
3600 })
3601 .await
3602 .unwrap();
3603
3604 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3605 .await;
3606 cx.read(|cx| {
3607 let tree = tree.read(cx);
3608 assert_eq!(tree.file_count(), 5);
3609 assert_eq!(
3610 tree.inode_for_path("fennel/grape"),
3611 tree.inode_for_path("finnochio/grape")
3612 );
3613 });
3614
3615 let cancel_flag = Default::default();
3616 let results = project
3617 .read_with(&cx, |project, cx| {
3618 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
3619 })
3620 .await;
3621 assert_eq!(
3622 results
3623 .into_iter()
3624 .map(|result| result.path)
3625 .collect::<Vec<Arc<Path>>>(),
3626 vec![
3627 PathBuf::from("banana/carrot/date").into(),
3628 PathBuf::from("banana/carrot/endive").into(),
3629 ]
3630 );
3631 }
3632
3633 #[gpui::test]
3634 async fn test_language_server_diagnostics(mut cx: gpui::TestAppContext) {
3635 let (language_server_config, mut fake_servers) = LanguageServerConfig::fake();
3636 let progress_token = language_server_config
3637 .disk_based_diagnostics_progress_token
3638 .clone()
3639 .unwrap();
3640
3641 let language = Arc::new(Language::new(
3642 LanguageConfig {
3643 name: "Rust".into(),
3644 path_suffixes: vec!["rs".to_string()],
3645 language_server: Some(language_server_config),
3646 ..Default::default()
3647 },
3648 Some(tree_sitter_rust::language()),
3649 ));
3650
3651 let fs = FakeFs::new(cx.background());
3652 fs.insert_tree(
3653 "/dir",
3654 json!({
3655 "a.rs": "fn a() { A }",
3656 "b.rs": "const y: i32 = 1",
3657 }),
3658 )
3659 .await;
3660
3661 let project = Project::test(fs, &mut cx);
3662 project.update(&mut cx, |project, _| {
3663 Arc::get_mut(&mut project.languages).unwrap().add(language);
3664 });
3665
3666 let (tree, _) = project
3667 .update(&mut cx, |project, cx| {
3668 project.find_or_create_local_worktree("/dir", false, cx)
3669 })
3670 .await
3671 .unwrap();
3672 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3673
3674 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3675 .await;
3676
3677 // Cause worktree to start the fake language server
3678 let _buffer = project
3679 .update(&mut cx, |project, cx| {
3680 project.open_buffer((worktree_id, Path::new("b.rs")), cx)
3681 })
3682 .await
3683 .unwrap();
3684
3685 let mut events = subscribe(&project, &mut cx);
3686
3687 let mut fake_server = fake_servers.next().await.unwrap();
3688 fake_server.start_progress(&progress_token).await;
3689 assert_eq!(
3690 events.next().await.unwrap(),
3691 Event::DiskBasedDiagnosticsStarted
3692 );
3693
3694 fake_server.start_progress(&progress_token).await;
3695 fake_server.end_progress(&progress_token).await;
3696 fake_server.start_progress(&progress_token).await;
3697
3698 fake_server
3699 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
3700 uri: Url::from_file_path("/dir/a.rs").unwrap(),
3701 version: None,
3702 diagnostics: vec![lsp::Diagnostic {
3703 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3704 severity: Some(lsp::DiagnosticSeverity::ERROR),
3705 message: "undefined variable 'A'".to_string(),
3706 ..Default::default()
3707 }],
3708 })
3709 .await;
3710 assert_eq!(
3711 events.next().await.unwrap(),
3712 Event::DiagnosticsUpdated((worktree_id, Path::new("a.rs")).into())
3713 );
3714
3715 fake_server.end_progress(&progress_token).await;
3716 fake_server.end_progress(&progress_token).await;
3717 assert_eq!(
3718 events.next().await.unwrap(),
3719 Event::DiskBasedDiagnosticsUpdated
3720 );
3721 assert_eq!(
3722 events.next().await.unwrap(),
3723 Event::DiskBasedDiagnosticsFinished
3724 );
3725
3726 let buffer = project
3727 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3728 .await
3729 .unwrap();
3730
3731 buffer.read_with(&cx, |buffer, _| {
3732 let snapshot = buffer.snapshot();
3733 let diagnostics = snapshot
3734 .diagnostics_in_range::<_, Point>(0..buffer.len())
3735 .collect::<Vec<_>>();
3736 assert_eq!(
3737 diagnostics,
3738 &[DiagnosticEntry {
3739 range: Point::new(0, 9)..Point::new(0, 10),
3740 diagnostic: Diagnostic {
3741 severity: lsp::DiagnosticSeverity::ERROR,
3742 message: "undefined variable 'A'".to_string(),
3743 group_id: 0,
3744 is_primary: true,
3745 ..Default::default()
3746 }
3747 }]
3748 )
3749 });
3750 }
3751
3752 #[gpui::test]
3753 async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
3754 let dir = temp_tree(json!({
3755 "root": {
3756 "dir1": {},
3757 "dir2": {
3758 "dir3": {}
3759 }
3760 }
3761 }));
3762
3763 let project = Project::test(Arc::new(RealFs), &mut cx);
3764 let (tree, _) = project
3765 .update(&mut cx, |project, cx| {
3766 project.find_or_create_local_worktree(&dir.path(), false, cx)
3767 })
3768 .await
3769 .unwrap();
3770
3771 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3772 .await;
3773
3774 let cancel_flag = Default::default();
3775 let results = project
3776 .read_with(&cx, |project, cx| {
3777 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
3778 })
3779 .await;
3780
3781 assert!(results.is_empty());
3782 }
3783
3784 #[gpui::test]
3785 async fn test_definition(mut cx: gpui::TestAppContext) {
3786 let (language_server_config, mut fake_servers) = LanguageServerConfig::fake();
3787 let language = Arc::new(Language::new(
3788 LanguageConfig {
3789 name: "Rust".into(),
3790 path_suffixes: vec!["rs".to_string()],
3791 language_server: Some(language_server_config),
3792 ..Default::default()
3793 },
3794 Some(tree_sitter_rust::language()),
3795 ));
3796
3797 let fs = FakeFs::new(cx.background());
3798 fs.insert_tree(
3799 "/dir",
3800 json!({
3801 "a.rs": "const fn a() { A }",
3802 "b.rs": "const y: i32 = crate::a()",
3803 }),
3804 )
3805 .await;
3806
3807 let project = Project::test(fs, &mut cx);
3808 project.update(&mut cx, |project, _| {
3809 Arc::get_mut(&mut project.languages).unwrap().add(language);
3810 });
3811
3812 let (tree, _) = project
3813 .update(&mut cx, |project, cx| {
3814 project.find_or_create_local_worktree("/dir/b.rs", false, cx)
3815 })
3816 .await
3817 .unwrap();
3818 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3819 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3820 .await;
3821
3822 let buffer = project
3823 .update(&mut cx, |project, cx| {
3824 project.open_buffer(
3825 ProjectPath {
3826 worktree_id,
3827 path: Path::new("").into(),
3828 },
3829 cx,
3830 )
3831 })
3832 .await
3833 .unwrap();
3834
3835 let mut fake_server = fake_servers.next().await.unwrap();
3836 fake_server.handle_request::<lsp::request::GotoDefinition, _>(move |params, _| {
3837 let params = params.text_document_position_params;
3838 assert_eq!(
3839 params.text_document.uri.to_file_path().unwrap(),
3840 Path::new("/dir/b.rs"),
3841 );
3842 assert_eq!(params.position, lsp::Position::new(0, 22));
3843
3844 Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
3845 lsp::Url::from_file_path("/dir/a.rs").unwrap(),
3846 lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3847 )))
3848 });
3849
3850 let mut definitions = project
3851 .update(&mut cx, |project, cx| project.definition(&buffer, 22, cx))
3852 .await
3853 .unwrap();
3854
3855 assert_eq!(definitions.len(), 1);
3856 let definition = definitions.pop().unwrap();
3857 cx.update(|cx| {
3858 let target_buffer = definition.buffer.read(cx);
3859 assert_eq!(
3860 target_buffer
3861 .file()
3862 .unwrap()
3863 .as_local()
3864 .unwrap()
3865 .abs_path(cx),
3866 Path::new("/dir/a.rs"),
3867 );
3868 assert_eq!(definition.range.to_offset(target_buffer), 9..10);
3869 assert_eq!(
3870 list_worktrees(&project, cx),
3871 [("/dir/b.rs".as_ref(), false), ("/dir/a.rs".as_ref(), true)]
3872 );
3873
3874 drop(definition);
3875 });
3876 cx.read(|cx| {
3877 assert_eq!(
3878 list_worktrees(&project, cx),
3879 [("/dir/b.rs".as_ref(), false)]
3880 );
3881 });
3882
3883 fn list_worktrees<'a>(
3884 project: &'a ModelHandle<Project>,
3885 cx: &'a AppContext,
3886 ) -> Vec<(&'a Path, bool)> {
3887 project
3888 .read(cx)
3889 .worktrees(cx)
3890 .map(|worktree| {
3891 let worktree = worktree.read(cx);
3892 (
3893 worktree.as_local().unwrap().abs_path().as_ref(),
3894 worktree.is_weak(),
3895 )
3896 })
3897 .collect::<Vec<_>>()
3898 }
3899 }
3900
3901 #[gpui::test]
3902 async fn test_save_file(mut cx: gpui::TestAppContext) {
3903 let fs = FakeFs::new(cx.background());
3904 fs.insert_tree(
3905 "/dir",
3906 json!({
3907 "file1": "the old contents",
3908 }),
3909 )
3910 .await;
3911
3912 let project = Project::test(fs.clone(), &mut cx);
3913 let worktree_id = project
3914 .update(&mut cx, |p, cx| {
3915 p.find_or_create_local_worktree("/dir", false, cx)
3916 })
3917 .await
3918 .unwrap()
3919 .0
3920 .read_with(&cx, |tree, _| tree.id());
3921
3922 let buffer = project
3923 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3924 .await
3925 .unwrap();
3926 buffer
3927 .update(&mut cx, |buffer, cx| {
3928 assert_eq!(buffer.text(), "the old contents");
3929 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3930 buffer.save(cx)
3931 })
3932 .await
3933 .unwrap();
3934
3935 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3936 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3937 }
3938
3939 #[gpui::test]
3940 async fn test_save_in_single_file_worktree(mut cx: gpui::TestAppContext) {
3941 let fs = FakeFs::new(cx.background());
3942 fs.insert_tree(
3943 "/dir",
3944 json!({
3945 "file1": "the old contents",
3946 }),
3947 )
3948 .await;
3949
3950 let project = Project::test(fs.clone(), &mut cx);
3951 let worktree_id = project
3952 .update(&mut cx, |p, cx| {
3953 p.find_or_create_local_worktree("/dir/file1", false, cx)
3954 })
3955 .await
3956 .unwrap()
3957 .0
3958 .read_with(&cx, |tree, _| tree.id());
3959
3960 let buffer = project
3961 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
3962 .await
3963 .unwrap();
3964 buffer
3965 .update(&mut cx, |buffer, cx| {
3966 buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3967 buffer.save(cx)
3968 })
3969 .await
3970 .unwrap();
3971
3972 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3973 assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3974 }
3975
3976 #[gpui::test(retries = 5)]
3977 async fn test_rescan_and_remote_updates(mut cx: gpui::TestAppContext) {
3978 let dir = temp_tree(json!({
3979 "a": {
3980 "file1": "",
3981 "file2": "",
3982 "file3": "",
3983 },
3984 "b": {
3985 "c": {
3986 "file4": "",
3987 "file5": "",
3988 }
3989 }
3990 }));
3991
3992 let project = Project::test(Arc::new(RealFs), &mut cx);
3993 let rpc = project.read_with(&cx, |p, _| p.client.clone());
3994
3995 let (tree, _) = project
3996 .update(&mut cx, |p, cx| {
3997 p.find_or_create_local_worktree(dir.path(), false, cx)
3998 })
3999 .await
4000 .unwrap();
4001 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
4002
4003 let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
4004 let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
4005 async move { buffer.await.unwrap() }
4006 };
4007 let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
4008 tree.read_with(cx, |tree, _| {
4009 tree.entry_for_path(path)
4010 .expect(&format!("no entry for path {}", path))
4011 .id
4012 })
4013 };
4014
4015 let buffer2 = buffer_for_path("a/file2", &mut cx).await;
4016 let buffer3 = buffer_for_path("a/file3", &mut cx).await;
4017 let buffer4 = buffer_for_path("b/c/file4", &mut cx).await;
4018 let buffer5 = buffer_for_path("b/c/file5", &mut cx).await;
4019
4020 let file2_id = id_for_path("a/file2", &cx);
4021 let file3_id = id_for_path("a/file3", &cx);
4022 let file4_id = id_for_path("b/c/file4", &cx);
4023
4024 // Wait for the initial scan.
4025 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4026 .await;
4027
4028 // Create a remote copy of this worktree.
4029 let initial_snapshot = tree.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
4030 let (remote, load_task) = cx.update(|cx| {
4031 Worktree::remote(
4032 1,
4033 1,
4034 initial_snapshot.to_proto(&Default::default(), Default::default()),
4035 rpc.clone(),
4036 cx,
4037 )
4038 });
4039 load_task.await;
4040
4041 cx.read(|cx| {
4042 assert!(!buffer2.read(cx).is_dirty());
4043 assert!(!buffer3.read(cx).is_dirty());
4044 assert!(!buffer4.read(cx).is_dirty());
4045 assert!(!buffer5.read(cx).is_dirty());
4046 });
4047
4048 // Rename and delete files and directories.
4049 tree.flush_fs_events(&cx).await;
4050 std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
4051 std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
4052 std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
4053 std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
4054 tree.flush_fs_events(&cx).await;
4055
4056 let expected_paths = vec![
4057 "a",
4058 "a/file1",
4059 "a/file2.new",
4060 "b",
4061 "d",
4062 "d/file3",
4063 "d/file4",
4064 ];
4065
4066 cx.read(|app| {
4067 assert_eq!(
4068 tree.read(app)
4069 .paths()
4070 .map(|p| p.to_str().unwrap())
4071 .collect::<Vec<_>>(),
4072 expected_paths
4073 );
4074
4075 assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
4076 assert_eq!(id_for_path("d/file3", &cx), file3_id);
4077 assert_eq!(id_for_path("d/file4", &cx), file4_id);
4078
4079 assert_eq!(
4080 buffer2.read(app).file().unwrap().path().as_ref(),
4081 Path::new("a/file2.new")
4082 );
4083 assert_eq!(
4084 buffer3.read(app).file().unwrap().path().as_ref(),
4085 Path::new("d/file3")
4086 );
4087 assert_eq!(
4088 buffer4.read(app).file().unwrap().path().as_ref(),
4089 Path::new("d/file4")
4090 );
4091 assert_eq!(
4092 buffer5.read(app).file().unwrap().path().as_ref(),
4093 Path::new("b/c/file5")
4094 );
4095
4096 assert!(!buffer2.read(app).file().unwrap().is_deleted());
4097 assert!(!buffer3.read(app).file().unwrap().is_deleted());
4098 assert!(!buffer4.read(app).file().unwrap().is_deleted());
4099 assert!(buffer5.read(app).file().unwrap().is_deleted());
4100 });
4101
4102 // Update the remote worktree. Check that it becomes consistent with the
4103 // local worktree.
4104 remote.update(&mut cx, |remote, cx| {
4105 let update_message = tree.read(cx).as_local().unwrap().snapshot().build_update(
4106 &initial_snapshot,
4107 1,
4108 1,
4109 true,
4110 );
4111 remote
4112 .as_remote_mut()
4113 .unwrap()
4114 .snapshot
4115 .apply_remote_update(update_message)
4116 .unwrap();
4117
4118 assert_eq!(
4119 remote
4120 .paths()
4121 .map(|p| p.to_str().unwrap())
4122 .collect::<Vec<_>>(),
4123 expected_paths
4124 );
4125 });
4126 }
4127
4128 #[gpui::test]
4129 async fn test_buffer_deduping(mut cx: gpui::TestAppContext) {
4130 let fs = FakeFs::new(cx.background());
4131 fs.insert_tree(
4132 "/the-dir",
4133 json!({
4134 "a.txt": "a-contents",
4135 "b.txt": "b-contents",
4136 }),
4137 )
4138 .await;
4139
4140 let project = Project::test(fs.clone(), &mut cx);
4141 let worktree_id = project
4142 .update(&mut cx, |p, cx| {
4143 p.find_or_create_local_worktree("/the-dir", false, cx)
4144 })
4145 .await
4146 .unwrap()
4147 .0
4148 .read_with(&cx, |tree, _| tree.id());
4149
4150 // Spawn multiple tasks to open paths, repeating some paths.
4151 let (buffer_a_1, buffer_b, buffer_a_2) = project.update(&mut cx, |p, cx| {
4152 (
4153 p.open_buffer((worktree_id, "a.txt"), cx),
4154 p.open_buffer((worktree_id, "b.txt"), cx),
4155 p.open_buffer((worktree_id, "a.txt"), cx),
4156 )
4157 });
4158
4159 let buffer_a_1 = buffer_a_1.await.unwrap();
4160 let buffer_a_2 = buffer_a_2.await.unwrap();
4161 let buffer_b = buffer_b.await.unwrap();
4162 assert_eq!(buffer_a_1.read_with(&cx, |b, _| b.text()), "a-contents");
4163 assert_eq!(buffer_b.read_with(&cx, |b, _| b.text()), "b-contents");
4164
4165 // There is only one buffer per path.
4166 let buffer_a_id = buffer_a_1.id();
4167 assert_eq!(buffer_a_2.id(), buffer_a_id);
4168
4169 // Open the same path again while it is still open.
4170 drop(buffer_a_1);
4171 let buffer_a_3 = project
4172 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
4173 .await
4174 .unwrap();
4175
4176 // There's still only one buffer per path.
4177 assert_eq!(buffer_a_3.id(), buffer_a_id);
4178 }
4179
4180 #[gpui::test]
4181 async fn test_buffer_is_dirty(mut cx: gpui::TestAppContext) {
4182 use std::fs;
4183
4184 let dir = temp_tree(json!({
4185 "file1": "abc",
4186 "file2": "def",
4187 "file3": "ghi",
4188 }));
4189
4190 let project = Project::test(Arc::new(RealFs), &mut cx);
4191 let (worktree, _) = project
4192 .update(&mut cx, |p, cx| {
4193 p.find_or_create_local_worktree(dir.path(), false, cx)
4194 })
4195 .await
4196 .unwrap();
4197 let worktree_id = worktree.read_with(&cx, |worktree, _| worktree.id());
4198
4199 worktree.flush_fs_events(&cx).await;
4200 worktree
4201 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
4202 .await;
4203
4204 let buffer1 = project
4205 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
4206 .await
4207 .unwrap();
4208 let events = Rc::new(RefCell::new(Vec::new()));
4209
4210 // initially, the buffer isn't dirty.
4211 buffer1.update(&mut cx, |buffer, cx| {
4212 cx.subscribe(&buffer1, {
4213 let events = events.clone();
4214 move |_, _, event, _| events.borrow_mut().push(event.clone())
4215 })
4216 .detach();
4217
4218 assert!(!buffer.is_dirty());
4219 assert!(events.borrow().is_empty());
4220
4221 buffer.edit(vec![1..2], "", cx);
4222 });
4223
4224 // after the first edit, the buffer is dirty, and emits a dirtied event.
4225 buffer1.update(&mut cx, |buffer, cx| {
4226 assert!(buffer.text() == "ac");
4227 assert!(buffer.is_dirty());
4228 assert_eq!(
4229 *events.borrow(),
4230 &[language::Event::Edited, language::Event::Dirtied]
4231 );
4232 events.borrow_mut().clear();
4233 buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
4234 });
4235
4236 // after saving, the buffer is not dirty, and emits a saved event.
4237 buffer1.update(&mut cx, |buffer, cx| {
4238 assert!(!buffer.is_dirty());
4239 assert_eq!(*events.borrow(), &[language::Event::Saved]);
4240 events.borrow_mut().clear();
4241
4242 buffer.edit(vec![1..1], "B", cx);
4243 buffer.edit(vec![2..2], "D", cx);
4244 });
4245
4246 // after editing again, the buffer is dirty, and emits another dirty event.
4247 buffer1.update(&mut cx, |buffer, cx| {
4248 assert!(buffer.text() == "aBDc");
4249 assert!(buffer.is_dirty());
4250 assert_eq!(
4251 *events.borrow(),
4252 &[
4253 language::Event::Edited,
4254 language::Event::Dirtied,
4255 language::Event::Edited,
4256 ],
4257 );
4258 events.borrow_mut().clear();
4259
4260 // TODO - currently, after restoring the buffer to its
4261 // previously-saved state, the is still considered dirty.
4262 buffer.edit([1..3], "", cx);
4263 assert!(buffer.text() == "ac");
4264 assert!(buffer.is_dirty());
4265 });
4266
4267 assert_eq!(*events.borrow(), &[language::Event::Edited]);
4268
4269 // When a file is deleted, the buffer is considered dirty.
4270 let events = Rc::new(RefCell::new(Vec::new()));
4271 let buffer2 = project
4272 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
4273 .await
4274 .unwrap();
4275 buffer2.update(&mut cx, |_, cx| {
4276 cx.subscribe(&buffer2, {
4277 let events = events.clone();
4278 move |_, _, event, _| events.borrow_mut().push(event.clone())
4279 })
4280 .detach();
4281 });
4282
4283 fs::remove_file(dir.path().join("file2")).unwrap();
4284 buffer2.condition(&cx, |b, _| b.is_dirty()).await;
4285 assert_eq!(
4286 *events.borrow(),
4287 &[language::Event::Dirtied, language::Event::FileHandleChanged]
4288 );
4289
4290 // When a file is already dirty when deleted, we don't emit a Dirtied event.
4291 let events = Rc::new(RefCell::new(Vec::new()));
4292 let buffer3 = project
4293 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
4294 .await
4295 .unwrap();
4296 buffer3.update(&mut cx, |_, cx| {
4297 cx.subscribe(&buffer3, {
4298 let events = events.clone();
4299 move |_, _, event, _| events.borrow_mut().push(event.clone())
4300 })
4301 .detach();
4302 });
4303
4304 worktree.flush_fs_events(&cx).await;
4305 buffer3.update(&mut cx, |buffer, cx| {
4306 buffer.edit(Some(0..0), "x", cx);
4307 });
4308 events.borrow_mut().clear();
4309 fs::remove_file(dir.path().join("file3")).unwrap();
4310 buffer3
4311 .condition(&cx, |_, _| !events.borrow().is_empty())
4312 .await;
4313 assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
4314 cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
4315 }
4316
4317 #[gpui::test]
4318 async fn test_buffer_file_changes_on_disk(mut cx: gpui::TestAppContext) {
4319 use std::fs;
4320
4321 let initial_contents = "aaa\nbbbbb\nc\n";
4322 let dir = temp_tree(json!({ "the-file": initial_contents }));
4323
4324 let project = Project::test(Arc::new(RealFs), &mut cx);
4325 let (worktree, _) = project
4326 .update(&mut cx, |p, cx| {
4327 p.find_or_create_local_worktree(dir.path(), false, cx)
4328 })
4329 .await
4330 .unwrap();
4331 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
4332
4333 worktree
4334 .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
4335 .await;
4336
4337 let abs_path = dir.path().join("the-file");
4338 let buffer = project
4339 .update(&mut cx, |p, cx| {
4340 p.open_buffer((worktree_id, "the-file"), cx)
4341 })
4342 .await
4343 .unwrap();
4344
4345 // TODO
4346 // Add a cursor on each row.
4347 // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
4348 // assert!(!buffer.is_dirty());
4349 // buffer.add_selection_set(
4350 // &(0..3)
4351 // .map(|row| Selection {
4352 // id: row as usize,
4353 // start: Point::new(row, 1),
4354 // end: Point::new(row, 1),
4355 // reversed: false,
4356 // goal: SelectionGoal::None,
4357 // })
4358 // .collect::<Vec<_>>(),
4359 // cx,
4360 // )
4361 // });
4362
4363 // Change the file on disk, adding two new lines of text, and removing
4364 // one line.
4365 buffer.read_with(&cx, |buffer, _| {
4366 assert!(!buffer.is_dirty());
4367 assert!(!buffer.has_conflict());
4368 });
4369 let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
4370 fs::write(&abs_path, new_contents).unwrap();
4371
4372 // Because the buffer was not modified, it is reloaded from disk. Its
4373 // contents are edited according to the diff between the old and new
4374 // file contents.
4375 buffer
4376 .condition(&cx, |buffer, _| buffer.text() == new_contents)
4377 .await;
4378
4379 buffer.update(&mut cx, |buffer, _| {
4380 assert_eq!(buffer.text(), new_contents);
4381 assert!(!buffer.is_dirty());
4382 assert!(!buffer.has_conflict());
4383
4384 // TODO
4385 // let cursor_positions = buffer
4386 // .selection_set(selection_set_id)
4387 // .unwrap()
4388 // .selections::<Point>(&*buffer)
4389 // .map(|selection| {
4390 // assert_eq!(selection.start, selection.end);
4391 // selection.start
4392 // })
4393 // .collect::<Vec<_>>();
4394 // assert_eq!(
4395 // cursor_positions,
4396 // [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
4397 // );
4398 });
4399
4400 // Modify the buffer
4401 buffer.update(&mut cx, |buffer, cx| {
4402 buffer.edit(vec![0..0], " ", cx);
4403 assert!(buffer.is_dirty());
4404 assert!(!buffer.has_conflict());
4405 });
4406
4407 // Change the file on disk again, adding blank lines to the beginning.
4408 fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
4409
4410 // Because the buffer is modified, it doesn't reload from disk, but is
4411 // marked as having a conflict.
4412 buffer
4413 .condition(&cx, |buffer, _| buffer.has_conflict())
4414 .await;
4415 }
4416
4417 #[gpui::test]
4418 async fn test_grouped_diagnostics(mut cx: gpui::TestAppContext) {
4419 let fs = FakeFs::new(cx.background());
4420 fs.insert_tree(
4421 "/the-dir",
4422 json!({
4423 "a.rs": "
4424 fn foo(mut v: Vec<usize>) {
4425 for x in &v {
4426 v.push(1);
4427 }
4428 }
4429 "
4430 .unindent(),
4431 }),
4432 )
4433 .await;
4434
4435 let project = Project::test(fs.clone(), &mut cx);
4436 let (worktree, _) = project
4437 .update(&mut cx, |p, cx| {
4438 p.find_or_create_local_worktree("/the-dir", false, cx)
4439 })
4440 .await
4441 .unwrap();
4442 let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
4443
4444 let buffer = project
4445 .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
4446 .await
4447 .unwrap();
4448
4449 let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
4450 let message = lsp::PublishDiagnosticsParams {
4451 uri: buffer_uri.clone(),
4452 diagnostics: vec![
4453 lsp::Diagnostic {
4454 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
4455 severity: Some(DiagnosticSeverity::WARNING),
4456 message: "error 1".to_string(),
4457 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4458 location: lsp::Location {
4459 uri: buffer_uri.clone(),
4460 range: lsp::Range::new(
4461 lsp::Position::new(1, 8),
4462 lsp::Position::new(1, 9),
4463 ),
4464 },
4465 message: "error 1 hint 1".to_string(),
4466 }]),
4467 ..Default::default()
4468 },
4469 lsp::Diagnostic {
4470 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
4471 severity: Some(DiagnosticSeverity::HINT),
4472 message: "error 1 hint 1".to_string(),
4473 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4474 location: lsp::Location {
4475 uri: buffer_uri.clone(),
4476 range: lsp::Range::new(
4477 lsp::Position::new(1, 8),
4478 lsp::Position::new(1, 9),
4479 ),
4480 },
4481 message: "original diagnostic".to_string(),
4482 }]),
4483 ..Default::default()
4484 },
4485 lsp::Diagnostic {
4486 range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
4487 severity: Some(DiagnosticSeverity::ERROR),
4488 message: "error 2".to_string(),
4489 related_information: Some(vec![
4490 lsp::DiagnosticRelatedInformation {
4491 location: lsp::Location {
4492 uri: buffer_uri.clone(),
4493 range: lsp::Range::new(
4494 lsp::Position::new(1, 13),
4495 lsp::Position::new(1, 15),
4496 ),
4497 },
4498 message: "error 2 hint 1".to_string(),
4499 },
4500 lsp::DiagnosticRelatedInformation {
4501 location: lsp::Location {
4502 uri: buffer_uri.clone(),
4503 range: lsp::Range::new(
4504 lsp::Position::new(1, 13),
4505 lsp::Position::new(1, 15),
4506 ),
4507 },
4508 message: "error 2 hint 2".to_string(),
4509 },
4510 ]),
4511 ..Default::default()
4512 },
4513 lsp::Diagnostic {
4514 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
4515 severity: Some(DiagnosticSeverity::HINT),
4516 message: "error 2 hint 1".to_string(),
4517 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4518 location: lsp::Location {
4519 uri: buffer_uri.clone(),
4520 range: lsp::Range::new(
4521 lsp::Position::new(2, 8),
4522 lsp::Position::new(2, 17),
4523 ),
4524 },
4525 message: "original diagnostic".to_string(),
4526 }]),
4527 ..Default::default()
4528 },
4529 lsp::Diagnostic {
4530 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
4531 severity: Some(DiagnosticSeverity::HINT),
4532 message: "error 2 hint 2".to_string(),
4533 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
4534 location: lsp::Location {
4535 uri: buffer_uri.clone(),
4536 range: lsp::Range::new(
4537 lsp::Position::new(2, 8),
4538 lsp::Position::new(2, 17),
4539 ),
4540 },
4541 message: "original diagnostic".to_string(),
4542 }]),
4543 ..Default::default()
4544 },
4545 ],
4546 version: None,
4547 };
4548
4549 project
4550 .update(&mut cx, |p, cx| {
4551 p.update_diagnostics(message, &Default::default(), cx)
4552 })
4553 .unwrap();
4554 let buffer = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4555
4556 assert_eq!(
4557 buffer
4558 .diagnostics_in_range::<_, Point>(0..buffer.len())
4559 .collect::<Vec<_>>(),
4560 &[
4561 DiagnosticEntry {
4562 range: Point::new(1, 8)..Point::new(1, 9),
4563 diagnostic: Diagnostic {
4564 severity: DiagnosticSeverity::WARNING,
4565 message: "error 1".to_string(),
4566 group_id: 0,
4567 is_primary: true,
4568 ..Default::default()
4569 }
4570 },
4571 DiagnosticEntry {
4572 range: Point::new(1, 8)..Point::new(1, 9),
4573 diagnostic: Diagnostic {
4574 severity: DiagnosticSeverity::HINT,
4575 message: "error 1 hint 1".to_string(),
4576 group_id: 0,
4577 is_primary: false,
4578 ..Default::default()
4579 }
4580 },
4581 DiagnosticEntry {
4582 range: Point::new(1, 13)..Point::new(1, 15),
4583 diagnostic: Diagnostic {
4584 severity: DiagnosticSeverity::HINT,
4585 message: "error 2 hint 1".to_string(),
4586 group_id: 1,
4587 is_primary: false,
4588 ..Default::default()
4589 }
4590 },
4591 DiagnosticEntry {
4592 range: Point::new(1, 13)..Point::new(1, 15),
4593 diagnostic: Diagnostic {
4594 severity: DiagnosticSeverity::HINT,
4595 message: "error 2 hint 2".to_string(),
4596 group_id: 1,
4597 is_primary: false,
4598 ..Default::default()
4599 }
4600 },
4601 DiagnosticEntry {
4602 range: Point::new(2, 8)..Point::new(2, 17),
4603 diagnostic: Diagnostic {
4604 severity: DiagnosticSeverity::ERROR,
4605 message: "error 2".to_string(),
4606 group_id: 1,
4607 is_primary: true,
4608 ..Default::default()
4609 }
4610 }
4611 ]
4612 );
4613
4614 assert_eq!(
4615 buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
4616 &[
4617 DiagnosticEntry {
4618 range: Point::new(1, 8)..Point::new(1, 9),
4619 diagnostic: Diagnostic {
4620 severity: DiagnosticSeverity::WARNING,
4621 message: "error 1".to_string(),
4622 group_id: 0,
4623 is_primary: true,
4624 ..Default::default()
4625 }
4626 },
4627 DiagnosticEntry {
4628 range: Point::new(1, 8)..Point::new(1, 9),
4629 diagnostic: Diagnostic {
4630 severity: DiagnosticSeverity::HINT,
4631 message: "error 1 hint 1".to_string(),
4632 group_id: 0,
4633 is_primary: false,
4634 ..Default::default()
4635 }
4636 },
4637 ]
4638 );
4639 assert_eq!(
4640 buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
4641 &[
4642 DiagnosticEntry {
4643 range: Point::new(1, 13)..Point::new(1, 15),
4644 diagnostic: Diagnostic {
4645 severity: DiagnosticSeverity::HINT,
4646 message: "error 2 hint 1".to_string(),
4647 group_id: 1,
4648 is_primary: false,
4649 ..Default::default()
4650 }
4651 },
4652 DiagnosticEntry {
4653 range: Point::new(1, 13)..Point::new(1, 15),
4654 diagnostic: Diagnostic {
4655 severity: DiagnosticSeverity::HINT,
4656 message: "error 2 hint 2".to_string(),
4657 group_id: 1,
4658 is_primary: false,
4659 ..Default::default()
4660 }
4661 },
4662 DiagnosticEntry {
4663 range: Point::new(2, 8)..Point::new(2, 17),
4664 diagnostic: Diagnostic {
4665 severity: DiagnosticSeverity::ERROR,
4666 message: "error 2".to_string(),
4667 group_id: 1,
4668 is_primary: true,
4669 ..Default::default()
4670 }
4671 }
4672 ]
4673 );
4674 }
4675
4676 #[gpui::test]
4677 async fn test_rename(mut cx: gpui::TestAppContext) {
4678 let (language_server_config, mut fake_servers) = LanguageServerConfig::fake();
4679 let language = Arc::new(Language::new(
4680 LanguageConfig {
4681 name: "Rust".into(),
4682 path_suffixes: vec!["rs".to_string()],
4683 language_server: Some(language_server_config),
4684 ..Default::default()
4685 },
4686 Some(tree_sitter_rust::language()),
4687 ));
4688
4689 let fs = FakeFs::new(cx.background());
4690 fs.insert_tree(
4691 "/dir",
4692 json!({
4693 "one.rs": "const ONE: usize = 1;",
4694 "two.rs": "const TWO: usize = one::ONE + one::ONE;"
4695 }),
4696 )
4697 .await;
4698
4699 let project = Project::test(fs.clone(), &mut cx);
4700 project.update(&mut cx, |project, _| {
4701 Arc::get_mut(&mut project.languages).unwrap().add(language);
4702 });
4703
4704 let (tree, _) = project
4705 .update(&mut cx, |project, cx| {
4706 project.find_or_create_local_worktree("/dir", false, cx)
4707 })
4708 .await
4709 .unwrap();
4710 let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
4711 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4712 .await;
4713
4714 let buffer = project
4715 .update(&mut cx, |project, cx| {
4716 project.open_buffer((worktree_id, Path::new("one.rs")), cx)
4717 })
4718 .await
4719 .unwrap();
4720
4721 let mut fake_server = fake_servers.next().await.unwrap();
4722
4723 let response = project.update(&mut cx, |project, cx| {
4724 project.prepare_rename(buffer.clone(), 7, cx)
4725 });
4726 fake_server
4727 .handle_request::<lsp::request::PrepareRenameRequest, _>(|params, _| {
4728 assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
4729 assert_eq!(params.position, lsp::Position::new(0, 7));
4730 Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
4731 lsp::Position::new(0, 6),
4732 lsp::Position::new(0, 9),
4733 )))
4734 })
4735 .next()
4736 .await
4737 .unwrap();
4738 let range = response.await.unwrap().unwrap();
4739 let range = buffer.read_with(&cx, |buffer, _| range.to_offset(buffer));
4740 assert_eq!(range, 6..9);
4741
4742 let response = project.update(&mut cx, |project, cx| {
4743 project.perform_rename(buffer.clone(), 7, "THREE".to_string(), true, cx)
4744 });
4745 fake_server
4746 .handle_request::<lsp::request::Rename, _>(|params, _| {
4747 assert_eq!(
4748 params.text_document_position.text_document.uri.as_str(),
4749 "file:///dir/one.rs"
4750 );
4751 assert_eq!(
4752 params.text_document_position.position,
4753 lsp::Position::new(0, 7)
4754 );
4755 assert_eq!(params.new_name, "THREE");
4756 Some(lsp::WorkspaceEdit {
4757 changes: Some(
4758 [
4759 (
4760 lsp::Url::from_file_path("/dir/one.rs").unwrap(),
4761 vec![lsp::TextEdit::new(
4762 lsp::Range::new(
4763 lsp::Position::new(0, 6),
4764 lsp::Position::new(0, 9),
4765 ),
4766 "THREE".to_string(),
4767 )],
4768 ),
4769 (
4770 lsp::Url::from_file_path("/dir/two.rs").unwrap(),
4771 vec![
4772 lsp::TextEdit::new(
4773 lsp::Range::new(
4774 lsp::Position::new(0, 24),
4775 lsp::Position::new(0, 27),
4776 ),
4777 "THREE".to_string(),
4778 ),
4779 lsp::TextEdit::new(
4780 lsp::Range::new(
4781 lsp::Position::new(0, 35),
4782 lsp::Position::new(0, 38),
4783 ),
4784 "THREE".to_string(),
4785 ),
4786 ],
4787 ),
4788 ]
4789 .into_iter()
4790 .collect(),
4791 ),
4792 ..Default::default()
4793 })
4794 })
4795 .next()
4796 .await
4797 .unwrap();
4798 let mut transaction = response.await.unwrap().0;
4799 assert_eq!(transaction.len(), 2);
4800 assert_eq!(
4801 transaction
4802 .remove_entry(&buffer)
4803 .unwrap()
4804 .0
4805 .read_with(&cx, |buffer, _| buffer.text()),
4806 "const THREE: usize = 1;"
4807 );
4808 assert_eq!(
4809 transaction
4810 .into_keys()
4811 .next()
4812 .unwrap()
4813 .read_with(&cx, |buffer, _| buffer.text()),
4814 "const TWO: usize = one::THREE + one::THREE;"
4815 );
4816 }
4817}