1mod ignore;
2mod lsp_command;
3mod lsp_glob_set;
4pub mod search;
5pub mod terminals;
6pub mod worktree;
7
8#[cfg(test)]
9mod project_tests;
10
11use anyhow::{anyhow, Context, Result};
12use client::{proto, Client, TypedEnvelope, UserStore};
13use clock::ReplicaId;
14use collections::{hash_map, BTreeMap, HashMap, HashSet};
15use futures::{
16 channel::{mpsc, oneshot},
17 future::{try_join_all, Shared},
18 AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
19};
20use gpui::{
21 AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
22 MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
23};
24use language::{
25 point_to_lsp,
26 proto::{
27 deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version,
28 serialize_anchor, serialize_version,
29 },
30 range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CachedLspAdapter, CharKind, CodeAction,
31 CodeLabel, Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Event as BufferEvent,
32 File as _, Language, LanguageRegistry, LanguageServerName, LocalFile, OffsetRangeExt,
33 Operation, Patch, PointUtf16, RopeFingerprint, TextBufferSnapshot, ToOffset, ToPointUtf16,
34 Transaction, Unclipped,
35};
36use lsp::{
37 DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
38 DocumentHighlightKind, LanguageServer, LanguageString, MarkedString,
39};
40use lsp_command::*;
41use lsp_glob_set::LspGlobSet;
42use postage::watch;
43use rand::prelude::*;
44use search::SearchQuery;
45use serde::Serialize;
46use settings::{FormatOnSave, Formatter, Settings};
47use sha2::{Digest, Sha256};
48use similar::{ChangeTag, TextDiff};
49use std::{
50 cell::RefCell,
51 cmp::{self, Ordering},
52 convert::TryInto,
53 hash::Hash,
54 mem,
55 num::NonZeroU32,
56 ops::Range,
57 path::{Component, Path, PathBuf},
58 rc::Rc,
59 str,
60 sync::{
61 atomic::{AtomicUsize, Ordering::SeqCst},
62 Arc,
63 },
64 time::{Duration, Instant, SystemTime},
65};
66use terminals::Terminals;
67
68use util::{debug_panic, defer, merge_json_value_into, post_inc, ResultExt, TryFutureExt as _};
69
70pub use fs::*;
71pub use worktree::*;
72
73pub trait Item {
74 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
75 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
76}
77
78// Language server state is stored across 3 collections:
79// language_servers =>
80// a mapping from unique server id to LanguageServerState which can either be a task for a
81// server in the process of starting, or a running server with adapter and language server arcs
82// language_server_ids => a mapping from worktreeId and server name to the unique server id
83// language_server_statuses => a mapping from unique server id to the current server status
84//
85// Multiple worktrees can map to the same language server for example when you jump to the definition
86// of a file in the standard library. So language_server_ids is used to look up which server is active
87// for a given worktree and language server name
88//
89// When starting a language server, first the id map is checked to make sure a server isn't already available
90// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
91// the Starting variant of LanguageServerState is stored in the language_servers map.
92pub struct Project {
93 worktrees: Vec<WorktreeHandle>,
94 active_entry: Option<ProjectEntryId>,
95 languages: Arc<LanguageRegistry>,
96 language_servers: HashMap<usize, LanguageServerState>,
97 language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
98 language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
99 last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
100 next_language_server_id: usize,
101 client: Arc<client::Client>,
102 next_entry_id: Arc<AtomicUsize>,
103 join_project_response_message_id: u32,
104 next_diagnostic_group_id: usize,
105 user_store: ModelHandle<UserStore>,
106 fs: Arc<dyn Fs>,
107 client_state: Option<ProjectClientState>,
108 collaborators: HashMap<proto::PeerId, Collaborator>,
109 client_subscriptions: Vec<client::Subscription>,
110 _subscriptions: Vec<gpui::Subscription>,
111 opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
112 shared_buffers: HashMap<proto::PeerId, HashSet<u64>>,
113 #[allow(clippy::type_complexity)]
114 loading_buffers_by_path: HashMap<
115 ProjectPath,
116 postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
117 >,
118 #[allow(clippy::type_complexity)]
119 loading_local_worktrees:
120 HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
121 opened_buffers: HashMap<u64, OpenBuffer>,
122 /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
123 /// Used for re-issuing buffer requests when peers temporarily disconnect
124 incomplete_remote_buffers: HashMap<u64, Option<ModelHandle<Buffer>>>,
125 buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
126 buffers_being_formatted: HashSet<usize>,
127 nonce: u128,
128 _maintain_buffer_languages: Task<()>,
129 _maintain_workspace_config: Task<()>,
130 terminals: Terminals,
131}
132
133enum OpenBuffer {
134 Strong(ModelHandle<Buffer>),
135 Weak(WeakModelHandle<Buffer>),
136 Operations(Vec<Operation>),
137}
138
139enum WorktreeHandle {
140 Strong(ModelHandle<Worktree>),
141 Weak(WeakModelHandle<Worktree>),
142}
143
144enum ProjectClientState {
145 Local {
146 remote_id: u64,
147 metadata_changed: mpsc::UnboundedSender<oneshot::Sender<()>>,
148 _maintain_metadata: Task<()>,
149 },
150 Remote {
151 sharing_has_stopped: bool,
152 remote_id: u64,
153 replica_id: ReplicaId,
154 },
155}
156
157#[derive(Clone, Debug)]
158pub struct Collaborator {
159 pub peer_id: proto::PeerId,
160 pub replica_id: ReplicaId,
161}
162
163#[derive(Clone, Debug, PartialEq, Eq)]
164pub enum Event {
165 ActiveEntryChanged(Option<ProjectEntryId>),
166 WorktreeAdded,
167 WorktreeRemoved(WorktreeId),
168 DiskBasedDiagnosticsStarted {
169 language_server_id: usize,
170 },
171 DiskBasedDiagnosticsFinished {
172 language_server_id: usize,
173 },
174 DiagnosticsUpdated {
175 path: ProjectPath,
176 language_server_id: usize,
177 },
178 RemoteIdChanged(Option<u64>),
179 DisconnectedFromHost,
180 Closed,
181 CollaboratorUpdated {
182 old_peer_id: proto::PeerId,
183 new_peer_id: proto::PeerId,
184 },
185 CollaboratorLeft(proto::PeerId),
186}
187
188pub enum LanguageServerState {
189 Starting(Task<Option<Arc<LanguageServer>>>),
190 Running {
191 language: Arc<Language>,
192 adapter: Arc<CachedLspAdapter>,
193 server: Arc<LanguageServer>,
194 watched_paths: LspGlobSet,
195 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
196 },
197}
198
199#[derive(Serialize)]
200pub struct LanguageServerStatus {
201 pub name: String,
202 pub pending_work: BTreeMap<String, LanguageServerProgress>,
203 pub has_pending_diagnostic_updates: bool,
204 progress_tokens: HashSet<String>,
205}
206
207#[derive(Clone, Debug, Serialize)]
208pub struct LanguageServerProgress {
209 pub message: Option<String>,
210 pub percentage: Option<usize>,
211 #[serde(skip_serializing)]
212 pub last_update_at: Instant,
213}
214
215#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
216pub struct ProjectPath {
217 pub worktree_id: WorktreeId,
218 pub path: Arc<Path>,
219}
220
221#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
222pub struct DiagnosticSummary {
223 pub language_server_id: usize,
224 pub error_count: usize,
225 pub warning_count: usize,
226}
227
228#[derive(Debug, Clone)]
229pub struct Location {
230 pub buffer: ModelHandle<Buffer>,
231 pub range: Range<language::Anchor>,
232}
233
234#[derive(Debug, Clone)]
235pub struct LocationLink {
236 pub origin: Option<Location>,
237 pub target: Location,
238}
239
240#[derive(Debug)]
241pub struct DocumentHighlight {
242 pub range: Range<language::Anchor>,
243 pub kind: DocumentHighlightKind,
244}
245
246#[derive(Clone, Debug)]
247pub struct Symbol {
248 pub language_server_name: LanguageServerName,
249 pub source_worktree_id: WorktreeId,
250 pub path: ProjectPath,
251 pub label: CodeLabel,
252 pub name: String,
253 pub kind: lsp::SymbolKind,
254 pub range: Range<Unclipped<PointUtf16>>,
255 pub signature: [u8; 32],
256}
257
258#[derive(Clone, Debug, PartialEq)]
259pub struct HoverBlock {
260 pub text: String,
261 pub language: Option<String>,
262}
263
264impl HoverBlock {
265 fn try_new(marked_string: MarkedString) -> Option<Self> {
266 let result = match marked_string {
267 MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
268 text: value,
269 language: Some(language),
270 },
271 MarkedString::String(text) => HoverBlock {
272 text,
273 language: None,
274 },
275 };
276 if result.text.is_empty() {
277 None
278 } else {
279 Some(result)
280 }
281 }
282}
283
284#[derive(Debug)]
285pub struct Hover {
286 pub contents: Vec<HoverBlock>,
287 pub range: Option<Range<language::Anchor>>,
288}
289
290#[derive(Default)]
291pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
292
293impl DiagnosticSummary {
294 fn new<'a, T: 'a>(
295 language_server_id: usize,
296 diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
297 ) -> Self {
298 let mut this = Self {
299 language_server_id,
300 error_count: 0,
301 warning_count: 0,
302 };
303
304 for entry in diagnostics {
305 if entry.diagnostic.is_primary {
306 match entry.diagnostic.severity {
307 DiagnosticSeverity::ERROR => this.error_count += 1,
308 DiagnosticSeverity::WARNING => this.warning_count += 1,
309 _ => {}
310 }
311 }
312 }
313
314 this
315 }
316
317 pub fn is_empty(&self) -> bool {
318 self.error_count == 0 && self.warning_count == 0
319 }
320
321 pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
322 proto::DiagnosticSummary {
323 path: path.to_string_lossy().to_string(),
324 language_server_id: self.language_server_id as u64,
325 error_count: self.error_count as u32,
326 warning_count: self.warning_count as u32,
327 }
328 }
329}
330
331#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
332pub struct ProjectEntryId(usize);
333
334impl ProjectEntryId {
335 pub const MAX: Self = Self(usize::MAX);
336
337 pub fn new(counter: &AtomicUsize) -> Self {
338 Self(counter.fetch_add(1, SeqCst))
339 }
340
341 pub fn from_proto(id: u64) -> Self {
342 Self(id as usize)
343 }
344
345 pub fn to_proto(&self) -> u64 {
346 self.0 as u64
347 }
348
349 pub fn to_usize(&self) -> usize {
350 self.0
351 }
352}
353
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355pub enum FormatTrigger {
356 Save,
357 Manual,
358}
359
360impl FormatTrigger {
361 fn from_proto(value: i32) -> FormatTrigger {
362 match value {
363 0 => FormatTrigger::Save,
364 1 => FormatTrigger::Manual,
365 _ => FormatTrigger::Save,
366 }
367 }
368}
369
370impl Project {
371 pub fn init(client: &Arc<Client>) {
372 client.add_model_message_handler(Self::handle_add_collaborator);
373 client.add_model_message_handler(Self::handle_update_project_collaborator);
374 client.add_model_message_handler(Self::handle_remove_collaborator);
375 client.add_model_message_handler(Self::handle_buffer_reloaded);
376 client.add_model_message_handler(Self::handle_buffer_saved);
377 client.add_model_message_handler(Self::handle_start_language_server);
378 client.add_model_message_handler(Self::handle_update_language_server);
379 client.add_model_message_handler(Self::handle_update_project);
380 client.add_model_message_handler(Self::handle_unshare_project);
381 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
382 client.add_model_message_handler(Self::handle_update_buffer_file);
383 client.add_model_message_handler(Self::handle_update_buffer);
384 client.add_model_message_handler(Self::handle_update_diagnostic_summary);
385 client.add_model_message_handler(Self::handle_update_worktree);
386 client.add_model_request_handler(Self::handle_create_project_entry);
387 client.add_model_request_handler(Self::handle_rename_project_entry);
388 client.add_model_request_handler(Self::handle_copy_project_entry);
389 client.add_model_request_handler(Self::handle_delete_project_entry);
390 client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
391 client.add_model_request_handler(Self::handle_apply_code_action);
392 client.add_model_request_handler(Self::handle_reload_buffers);
393 client.add_model_request_handler(Self::handle_synchronize_buffers);
394 client.add_model_request_handler(Self::handle_format_buffers);
395 client.add_model_request_handler(Self::handle_get_code_actions);
396 client.add_model_request_handler(Self::handle_get_completions);
397 client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
398 client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
399 client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
400 client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
401 client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
402 client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
403 client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
404 client.add_model_request_handler(Self::handle_search_project);
405 client.add_model_request_handler(Self::handle_get_project_symbols);
406 client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
407 client.add_model_request_handler(Self::handle_open_buffer_by_id);
408 client.add_model_request_handler(Self::handle_open_buffer_by_path);
409 client.add_model_request_handler(Self::handle_save_buffer);
410 client.add_model_message_handler(Self::handle_update_diff_base);
411 }
412
413 pub fn local(
414 client: Arc<Client>,
415 user_store: ModelHandle<UserStore>,
416 languages: Arc<LanguageRegistry>,
417 fs: Arc<dyn Fs>,
418 cx: &mut MutableAppContext,
419 ) -> ModelHandle<Self> {
420 cx.add_model(|cx: &mut ModelContext<Self>| Self {
421 worktrees: Default::default(),
422 collaborators: Default::default(),
423 opened_buffers: Default::default(),
424 shared_buffers: Default::default(),
425 incomplete_remote_buffers: Default::default(),
426 loading_buffers_by_path: Default::default(),
427 loading_local_worktrees: Default::default(),
428 buffer_snapshots: Default::default(),
429 join_project_response_message_id: 0,
430 client_state: None,
431 opened_buffer: watch::channel(),
432 client_subscriptions: Vec::new(),
433 _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
434 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
435 _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
436 active_entry: None,
437 languages,
438 client,
439 user_store,
440 fs,
441 next_entry_id: Default::default(),
442 next_diagnostic_group_id: Default::default(),
443 language_servers: Default::default(),
444 language_server_ids: Default::default(),
445 language_server_statuses: Default::default(),
446 last_workspace_edits_by_language_server: Default::default(),
447 buffers_being_formatted: Default::default(),
448 next_language_server_id: 0,
449 nonce: StdRng::from_entropy().gen(),
450 terminals: Terminals {
451 local_handles: Vec::new(),
452 },
453 })
454 }
455
456 pub async fn remote(
457 remote_id: u64,
458 client: Arc<Client>,
459 user_store: ModelHandle<UserStore>,
460 languages: Arc<LanguageRegistry>,
461 fs: Arc<dyn Fs>,
462 mut cx: AsyncAppContext,
463 ) -> Result<ModelHandle<Self>> {
464 client.authenticate_and_connect(true, &cx).await?;
465
466 let subscription = client.subscribe_to_entity(remote_id)?;
467 let response = client
468 .request_envelope(proto::JoinProject {
469 project_id: remote_id,
470 })
471 .await?;
472 let this = cx.add_model(|cx| {
473 let replica_id = response.payload.replica_id as ReplicaId;
474
475 let mut worktrees = Vec::new();
476 for worktree in response.payload.worktrees {
477 let worktree = cx.update(|cx| {
478 Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
479 });
480 worktrees.push(worktree);
481 }
482
483 let mut this = Self {
484 worktrees: Vec::new(),
485 loading_buffers_by_path: Default::default(),
486 opened_buffer: watch::channel(),
487 shared_buffers: Default::default(),
488 incomplete_remote_buffers: Default::default(),
489 loading_local_worktrees: Default::default(),
490 active_entry: None,
491 collaborators: Default::default(),
492 join_project_response_message_id: response.message_id,
493 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
494 _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
495 languages,
496 user_store: user_store.clone(),
497 fs,
498 next_entry_id: Default::default(),
499 next_diagnostic_group_id: Default::default(),
500 client_subscriptions: Default::default(),
501 _subscriptions: Default::default(),
502 client: client.clone(),
503 client_state: Some(ProjectClientState::Remote {
504 sharing_has_stopped: false,
505 remote_id,
506 replica_id,
507 }),
508 language_servers: Default::default(),
509 language_server_ids: Default::default(),
510 language_server_statuses: response
511 .payload
512 .language_servers
513 .into_iter()
514 .map(|server| {
515 (
516 server.id as usize,
517 LanguageServerStatus {
518 name: server.name,
519 pending_work: Default::default(),
520 has_pending_diagnostic_updates: false,
521 progress_tokens: Default::default(),
522 },
523 )
524 })
525 .collect(),
526 last_workspace_edits_by_language_server: Default::default(),
527 next_language_server_id: 0,
528 opened_buffers: Default::default(),
529 buffers_being_formatted: Default::default(),
530 buffer_snapshots: Default::default(),
531 nonce: StdRng::from_entropy().gen(),
532 terminals: Terminals {
533 local_handles: Vec::new(),
534 },
535 };
536 for worktree in worktrees {
537 let _ = this.add_worktree(&worktree, cx);
538 }
539 this
540 });
541 let subscription = subscription.set_model(&this, &mut cx);
542
543 let user_ids = response
544 .payload
545 .collaborators
546 .iter()
547 .map(|peer| peer.user_id)
548 .collect();
549 user_store
550 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
551 .await?;
552
553 this.update(&mut cx, |this, cx| {
554 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
555 this.client_subscriptions.push(subscription);
556 anyhow::Ok(())
557 })?;
558
559 Ok(this)
560 }
561
562 #[cfg(any(test, feature = "test-support"))]
563 pub async fn test(
564 fs: Arc<dyn Fs>,
565 root_paths: impl IntoIterator<Item = &Path>,
566 cx: &mut gpui::TestAppContext,
567 ) -> ModelHandle<Project> {
568 if !cx.read(|cx| cx.has_global::<Settings>()) {
569 cx.update(|cx| {
570 cx.set_global(Settings::test(cx));
571 });
572 }
573
574 let mut languages = LanguageRegistry::test();
575 languages.set_executor(cx.background());
576 let http_client = util::http::FakeHttpClient::with_404_response();
577 let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
578 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
579 let project =
580 cx.update(|cx| Project::local(client, user_store, Arc::new(languages), fs, cx));
581 for path in root_paths {
582 let (tree, _) = project
583 .update(cx, |project, cx| {
584 project.find_or_create_local_worktree(path, true, cx)
585 })
586 .await
587 .unwrap();
588 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
589 .await;
590 }
591 project
592 }
593
594 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
595 let settings = cx.global::<Settings>();
596
597 let mut language_servers_to_start = Vec::new();
598 for buffer in self.opened_buffers.values() {
599 if let Some(buffer) = buffer.upgrade(cx) {
600 let buffer = buffer.read(cx);
601 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
602 {
603 if settings.enable_language_server(Some(&language.name())) {
604 let worktree = file.worktree.read(cx);
605 language_servers_to_start.push((
606 worktree.id(),
607 worktree.as_local().unwrap().abs_path().clone(),
608 language.clone(),
609 ));
610 }
611 }
612 }
613 }
614
615 let mut language_servers_to_stop = Vec::new();
616 for language in self.languages.to_vec() {
617 if let Some(lsp_adapter) = language.lsp_adapter() {
618 if !settings.enable_language_server(Some(&language.name())) {
619 let lsp_name = &lsp_adapter.name;
620 for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
621 if lsp_name == started_lsp_name {
622 language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
623 }
624 }
625 }
626 }
627 }
628
629 // Stop all newly-disabled language servers.
630 for (worktree_id, adapter_name) in language_servers_to_stop {
631 self.stop_language_server(worktree_id, adapter_name, cx)
632 .detach();
633 }
634
635 // Start all the newly-enabled language servers.
636 for (worktree_id, worktree_path, language) in language_servers_to_start {
637 self.start_language_server(worktree_id, worktree_path, language, cx);
638 }
639
640 cx.notify();
641 }
642
643 pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
644 self.opened_buffers
645 .get(&remote_id)
646 .and_then(|buffer| buffer.upgrade(cx))
647 }
648
649 pub fn languages(&self) -> &Arc<LanguageRegistry> {
650 &self.languages
651 }
652
653 pub fn client(&self) -> Arc<Client> {
654 self.client.clone()
655 }
656
657 pub fn user_store(&self) -> ModelHandle<UserStore> {
658 self.user_store.clone()
659 }
660
661 #[cfg(any(test, feature = "test-support"))]
662 pub fn opened_buffers(&self, cx: &AppContext) -> Vec<ModelHandle<Buffer>> {
663 self.opened_buffers
664 .values()
665 .filter_map(|b| b.upgrade(cx))
666 .collect()
667 }
668
669 #[cfg(any(test, feature = "test-support"))]
670 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
671 let path = path.into();
672 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
673 self.opened_buffers.iter().any(|(_, buffer)| {
674 if let Some(buffer) = buffer.upgrade(cx) {
675 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
676 if file.worktree == worktree && file.path() == &path.path {
677 return true;
678 }
679 }
680 }
681 false
682 })
683 } else {
684 false
685 }
686 }
687
688 pub fn fs(&self) -> &Arc<dyn Fs> {
689 &self.fs
690 }
691
692 pub fn remote_id(&self) -> Option<u64> {
693 match self.client_state.as_ref()? {
694 ProjectClientState::Local { remote_id, .. }
695 | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
696 }
697 }
698
699 pub fn replica_id(&self) -> ReplicaId {
700 match &self.client_state {
701 Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
702 _ => 0,
703 }
704 }
705
706 fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) -> impl Future<Output = ()> {
707 let (tx, rx) = oneshot::channel();
708 if let Some(ProjectClientState::Local {
709 metadata_changed, ..
710 }) = &mut self.client_state
711 {
712 let _ = metadata_changed.unbounded_send(tx);
713 }
714 cx.notify();
715
716 async move {
717 // If the project is shared, this will resolve when the `_maintain_metadata` task has
718 // a chance to update the metadata. Otherwise, it will resolve right away because `tx`
719 // will get dropped.
720 let _ = rx.await;
721 }
722 }
723
724 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
725 &self.collaborators
726 }
727
728 /// Collect all worktrees, including ones that don't appear in the project panel
729 pub fn worktrees<'a>(
730 &'a self,
731 cx: &'a AppContext,
732 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
733 self.worktrees
734 .iter()
735 .filter_map(move |worktree| worktree.upgrade(cx))
736 }
737
738 /// Collect all user-visible worktrees, the ones that appear in the project panel
739 pub fn visible_worktrees<'a>(
740 &'a self,
741 cx: &'a AppContext,
742 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
743 self.worktrees.iter().filter_map(|worktree| {
744 worktree.upgrade(cx).and_then(|worktree| {
745 if worktree.read(cx).is_visible() {
746 Some(worktree)
747 } else {
748 None
749 }
750 })
751 })
752 }
753
754 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
755 self.visible_worktrees(cx)
756 .map(|tree| tree.read(cx).root_name())
757 }
758
759 pub fn worktree_for_id(
760 &self,
761 id: WorktreeId,
762 cx: &AppContext,
763 ) -> Option<ModelHandle<Worktree>> {
764 self.worktrees(cx)
765 .find(|worktree| worktree.read(cx).id() == id)
766 }
767
768 pub fn worktree_for_entry(
769 &self,
770 entry_id: ProjectEntryId,
771 cx: &AppContext,
772 ) -> Option<ModelHandle<Worktree>> {
773 self.worktrees(cx)
774 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
775 }
776
777 pub fn worktree_id_for_entry(
778 &self,
779 entry_id: ProjectEntryId,
780 cx: &AppContext,
781 ) -> Option<WorktreeId> {
782 self.worktree_for_entry(entry_id, cx)
783 .map(|worktree| worktree.read(cx).id())
784 }
785
786 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
787 paths.iter().all(|path| self.contains_path(path, cx))
788 }
789
790 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
791 for worktree in self.worktrees(cx) {
792 let worktree = worktree.read(cx).as_local();
793 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
794 return true;
795 }
796 }
797 false
798 }
799
800 pub fn create_entry(
801 &mut self,
802 project_path: impl Into<ProjectPath>,
803 is_directory: bool,
804 cx: &mut ModelContext<Self>,
805 ) -> Option<Task<Result<Entry>>> {
806 let project_path = project_path.into();
807 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
808 if self.is_local() {
809 Some(worktree.update(cx, |worktree, cx| {
810 worktree
811 .as_local_mut()
812 .unwrap()
813 .create_entry(project_path.path, is_directory, cx)
814 }))
815 } else {
816 let client = self.client.clone();
817 let project_id = self.remote_id().unwrap();
818 Some(cx.spawn_weak(|_, mut cx| async move {
819 let response = client
820 .request(proto::CreateProjectEntry {
821 worktree_id: project_path.worktree_id.to_proto(),
822 project_id,
823 path: project_path.path.to_string_lossy().into(),
824 is_directory,
825 })
826 .await?;
827 let entry = response
828 .entry
829 .ok_or_else(|| anyhow!("missing entry in response"))?;
830 worktree
831 .update(&mut cx, |worktree, cx| {
832 worktree.as_remote_mut().unwrap().insert_entry(
833 entry,
834 response.worktree_scan_id as usize,
835 cx,
836 )
837 })
838 .await
839 }))
840 }
841 }
842
843 pub fn copy_entry(
844 &mut self,
845 entry_id: ProjectEntryId,
846 new_path: impl Into<Arc<Path>>,
847 cx: &mut ModelContext<Self>,
848 ) -> Option<Task<Result<Entry>>> {
849 let worktree = self.worktree_for_entry(entry_id, cx)?;
850 let new_path = new_path.into();
851 if self.is_local() {
852 worktree.update(cx, |worktree, cx| {
853 worktree
854 .as_local_mut()
855 .unwrap()
856 .copy_entry(entry_id, new_path, cx)
857 })
858 } else {
859 let client = self.client.clone();
860 let project_id = self.remote_id().unwrap();
861
862 Some(cx.spawn_weak(|_, mut cx| async move {
863 let response = client
864 .request(proto::CopyProjectEntry {
865 project_id,
866 entry_id: entry_id.to_proto(),
867 new_path: new_path.to_string_lossy().into(),
868 })
869 .await?;
870 let entry = response
871 .entry
872 .ok_or_else(|| anyhow!("missing entry in response"))?;
873 worktree
874 .update(&mut cx, |worktree, cx| {
875 worktree.as_remote_mut().unwrap().insert_entry(
876 entry,
877 response.worktree_scan_id as usize,
878 cx,
879 )
880 })
881 .await
882 }))
883 }
884 }
885
886 pub fn rename_entry(
887 &mut self,
888 entry_id: ProjectEntryId,
889 new_path: impl Into<Arc<Path>>,
890 cx: &mut ModelContext<Self>,
891 ) -> Option<Task<Result<Entry>>> {
892 let worktree = self.worktree_for_entry(entry_id, cx)?;
893 let new_path = new_path.into();
894 if self.is_local() {
895 worktree.update(cx, |worktree, cx| {
896 worktree
897 .as_local_mut()
898 .unwrap()
899 .rename_entry(entry_id, new_path, cx)
900 })
901 } else {
902 let client = self.client.clone();
903 let project_id = self.remote_id().unwrap();
904
905 Some(cx.spawn_weak(|_, mut cx| async move {
906 let response = client
907 .request(proto::RenameProjectEntry {
908 project_id,
909 entry_id: entry_id.to_proto(),
910 new_path: new_path.to_string_lossy().into(),
911 })
912 .await?;
913 let entry = response
914 .entry
915 .ok_or_else(|| anyhow!("missing entry in response"))?;
916 worktree
917 .update(&mut cx, |worktree, cx| {
918 worktree.as_remote_mut().unwrap().insert_entry(
919 entry,
920 response.worktree_scan_id as usize,
921 cx,
922 )
923 })
924 .await
925 }))
926 }
927 }
928
929 pub fn delete_entry(
930 &mut self,
931 entry_id: ProjectEntryId,
932 cx: &mut ModelContext<Self>,
933 ) -> Option<Task<Result<()>>> {
934 let worktree = self.worktree_for_entry(entry_id, cx)?;
935 if self.is_local() {
936 worktree.update(cx, |worktree, cx| {
937 worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
938 })
939 } else {
940 let client = self.client.clone();
941 let project_id = self.remote_id().unwrap();
942 Some(cx.spawn_weak(|_, mut cx| async move {
943 let response = client
944 .request(proto::DeleteProjectEntry {
945 project_id,
946 entry_id: entry_id.to_proto(),
947 })
948 .await?;
949 worktree
950 .update(&mut cx, move |worktree, cx| {
951 worktree.as_remote_mut().unwrap().delete_entry(
952 entry_id,
953 response.worktree_scan_id as usize,
954 cx,
955 )
956 })
957 .await
958 }))
959 }
960 }
961
962 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
963 if self.client_state.is_some() {
964 return Err(anyhow!("project was already shared"));
965 }
966 self.client_subscriptions.push(
967 self.client
968 .subscribe_to_entity(project_id)?
969 .set_model(&cx.handle(), &mut cx.to_async()),
970 );
971
972 for open_buffer in self.opened_buffers.values_mut() {
973 match open_buffer {
974 OpenBuffer::Strong(_) => {}
975 OpenBuffer::Weak(buffer) => {
976 if let Some(buffer) = buffer.upgrade(cx) {
977 *open_buffer = OpenBuffer::Strong(buffer);
978 }
979 }
980 OpenBuffer::Operations(_) => unreachable!(),
981 }
982 }
983
984 for worktree_handle in self.worktrees.iter_mut() {
985 match worktree_handle {
986 WorktreeHandle::Strong(_) => {}
987 WorktreeHandle::Weak(worktree) => {
988 if let Some(worktree) = worktree.upgrade(cx) {
989 *worktree_handle = WorktreeHandle::Strong(worktree);
990 }
991 }
992 }
993 }
994
995 for (server_id, status) in &self.language_server_statuses {
996 self.client
997 .send(proto::StartLanguageServer {
998 project_id,
999 server: Some(proto::LanguageServer {
1000 id: *server_id as u64,
1001 name: status.name.clone(),
1002 }),
1003 })
1004 .log_err();
1005 }
1006
1007 let (metadata_changed_tx, mut metadata_changed_rx) = mpsc::unbounded();
1008 self.client_state = Some(ProjectClientState::Local {
1009 remote_id: project_id,
1010 metadata_changed: metadata_changed_tx,
1011 _maintain_metadata: cx.spawn_weak(move |this, mut cx| async move {
1012 let mut txs = Vec::new();
1013 while let Some(tx) = metadata_changed_rx.next().await {
1014 txs.push(tx);
1015 while let Ok(Some(next_tx)) = metadata_changed_rx.try_next() {
1016 txs.push(next_tx);
1017 }
1018
1019 let Some(this) = this.upgrade(&cx) else { break };
1020 let worktrees =
1021 this.read_with(&cx, |this, cx| this.worktrees(cx).collect::<Vec<_>>());
1022 let update_project = this
1023 .read_with(&cx, |this, cx| {
1024 this.client.request(proto::UpdateProject {
1025 project_id,
1026 worktrees: this.worktree_metadata_protos(cx),
1027 })
1028 })
1029 .await;
1030 if update_project.is_ok() {
1031 for worktree in worktrees {
1032 worktree.update(&mut cx, |worktree, cx| {
1033 let worktree = worktree.as_local_mut().unwrap();
1034 worktree.share(project_id, cx).detach_and_log_err(cx)
1035 });
1036 }
1037 }
1038
1039 for tx in txs.drain(..) {
1040 let _ = tx.send(());
1041 }
1042 }
1043 }),
1044 });
1045
1046 let _ = self.metadata_changed(cx);
1047 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1048 cx.notify();
1049 Ok(())
1050 }
1051
1052 pub fn reshared(
1053 &mut self,
1054 message: proto::ResharedProject,
1055 cx: &mut ModelContext<Self>,
1056 ) -> Result<()> {
1057 self.shared_buffers.clear();
1058 self.set_collaborators_from_proto(message.collaborators, cx)?;
1059 let _ = self.metadata_changed(cx);
1060 Ok(())
1061 }
1062
1063 pub fn rejoined(
1064 &mut self,
1065 message: proto::RejoinedProject,
1066 message_id: u32,
1067 cx: &mut ModelContext<Self>,
1068 ) -> Result<()> {
1069 self.join_project_response_message_id = message_id;
1070 self.set_worktrees_from_proto(message.worktrees, cx)?;
1071 self.set_collaborators_from_proto(message.collaborators, cx)?;
1072 self.language_server_statuses = message
1073 .language_servers
1074 .into_iter()
1075 .map(|server| {
1076 (
1077 server.id as usize,
1078 LanguageServerStatus {
1079 name: server.name,
1080 pending_work: Default::default(),
1081 has_pending_diagnostic_updates: false,
1082 progress_tokens: Default::default(),
1083 },
1084 )
1085 })
1086 .collect();
1087 self.synchronize_remote_buffers(cx).detach_and_log_err(cx);
1088
1089 cx.notify();
1090 Ok(())
1091 }
1092
1093 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1094 if self.is_remote() {
1095 return Err(anyhow!("attempted to unshare a remote project"));
1096 }
1097
1098 if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1099 self.collaborators.clear();
1100 self.shared_buffers.clear();
1101 self.client_subscriptions.clear();
1102
1103 for worktree_handle in self.worktrees.iter_mut() {
1104 if let WorktreeHandle::Strong(worktree) = worktree_handle {
1105 let is_visible = worktree.update(cx, |worktree, _| {
1106 worktree.as_local_mut().unwrap().unshare();
1107 worktree.is_visible()
1108 });
1109 if !is_visible {
1110 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1111 }
1112 }
1113 }
1114
1115 for open_buffer in self.opened_buffers.values_mut() {
1116 if let OpenBuffer::Strong(buffer) = open_buffer {
1117 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1118 }
1119 }
1120
1121 let _ = self.metadata_changed(cx);
1122 cx.notify();
1123 self.client.send(proto::UnshareProject {
1124 project_id: remote_id,
1125 })?;
1126
1127 Ok(())
1128 } else {
1129 Err(anyhow!("attempted to unshare an unshared project"))
1130 }
1131 }
1132
1133 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1134 if let Some(ProjectClientState::Remote {
1135 sharing_has_stopped,
1136 ..
1137 }) = &mut self.client_state
1138 {
1139 *sharing_has_stopped = true;
1140 self.collaborators.clear();
1141 for worktree in &self.worktrees {
1142 if let Some(worktree) = worktree.upgrade(cx) {
1143 worktree.update(cx, |worktree, _| {
1144 if let Some(worktree) = worktree.as_remote_mut() {
1145 worktree.disconnected_from_host();
1146 }
1147 });
1148 }
1149 }
1150 cx.emit(Event::DisconnectedFromHost);
1151 cx.notify();
1152
1153 // Wake up all futures currently waiting on a buffer to get opened,
1154 // to give them a chance to fail now that we've disconnected.
1155 *self.opened_buffer.0.borrow_mut() = ();
1156 }
1157 }
1158
1159 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1160 cx.emit(Event::Closed);
1161 }
1162
1163 pub fn is_read_only(&self) -> bool {
1164 match &self.client_state {
1165 Some(ProjectClientState::Remote {
1166 sharing_has_stopped,
1167 ..
1168 }) => *sharing_has_stopped,
1169 _ => false,
1170 }
1171 }
1172
1173 pub fn is_local(&self) -> bool {
1174 match &self.client_state {
1175 Some(ProjectClientState::Remote { .. }) => false,
1176 _ => true,
1177 }
1178 }
1179
1180 pub fn is_remote(&self) -> bool {
1181 !self.is_local()
1182 }
1183
1184 pub fn create_buffer(
1185 &mut self,
1186 text: &str,
1187 language: Option<Arc<Language>>,
1188 cx: &mut ModelContext<Self>,
1189 ) -> Result<ModelHandle<Buffer>> {
1190 if self.is_remote() {
1191 return Err(anyhow!("creating buffers as a guest is not supported yet"));
1192 }
1193
1194 let buffer = cx.add_model(|cx| {
1195 Buffer::new(self.replica_id(), text, cx)
1196 .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1197 });
1198 self.register_buffer(&buffer, cx)?;
1199 Ok(buffer)
1200 }
1201
1202 pub fn open_path(
1203 &mut self,
1204 path: impl Into<ProjectPath>,
1205 cx: &mut ModelContext<Self>,
1206 ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1207 let task = self.open_buffer(path, cx);
1208 cx.spawn_weak(|_, cx| async move {
1209 let buffer = task.await?;
1210 let project_entry_id = buffer
1211 .read_with(&cx, |buffer, cx| {
1212 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1213 })
1214 .ok_or_else(|| anyhow!("no project entry"))?;
1215
1216 let buffer: &AnyModelHandle = &buffer;
1217 Ok((project_entry_id, buffer.clone()))
1218 })
1219 }
1220
1221 pub fn open_local_buffer(
1222 &mut self,
1223 abs_path: impl AsRef<Path>,
1224 cx: &mut ModelContext<Self>,
1225 ) -> Task<Result<ModelHandle<Buffer>>> {
1226 if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1227 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1228 } else {
1229 Task::ready(Err(anyhow!("no such path")))
1230 }
1231 }
1232
1233 pub fn open_buffer(
1234 &mut self,
1235 path: impl Into<ProjectPath>,
1236 cx: &mut ModelContext<Self>,
1237 ) -> Task<Result<ModelHandle<Buffer>>> {
1238 let project_path = path.into();
1239 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1240 worktree
1241 } else {
1242 return Task::ready(Err(anyhow!("no such worktree")));
1243 };
1244
1245 // If there is already a buffer for the given path, then return it.
1246 let existing_buffer = self.get_open_buffer(&project_path, cx);
1247 if let Some(existing_buffer) = existing_buffer {
1248 return Task::ready(Ok(existing_buffer));
1249 }
1250
1251 let mut loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1252 // If the given path is already being loaded, then wait for that existing
1253 // task to complete and return the same buffer.
1254 hash_map::Entry::Occupied(e) => e.get().clone(),
1255
1256 // Otherwise, record the fact that this path is now being loaded.
1257 hash_map::Entry::Vacant(entry) => {
1258 let (mut tx, rx) = postage::watch::channel();
1259 entry.insert(rx.clone());
1260
1261 let load_buffer = if worktree.read(cx).is_local() {
1262 self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1263 } else {
1264 self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1265 };
1266
1267 cx.spawn(move |this, mut cx| async move {
1268 let load_result = load_buffer.await;
1269 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1270 // Record the fact that the buffer is no longer loading.
1271 this.loading_buffers_by_path.remove(&project_path);
1272 let buffer = load_result.map_err(Arc::new)?;
1273 Ok(buffer)
1274 }));
1275 })
1276 .detach();
1277 rx
1278 }
1279 };
1280
1281 cx.foreground().spawn(async move {
1282 loop {
1283 if let Some(result) = loading_watch.borrow().as_ref() {
1284 match result {
1285 Ok(buffer) => return Ok(buffer.clone()),
1286 Err(error) => return Err(anyhow!("{}", error)),
1287 }
1288 }
1289 loading_watch.next().await;
1290 }
1291 })
1292 }
1293
1294 fn open_local_buffer_internal(
1295 &mut self,
1296 path: &Arc<Path>,
1297 worktree: &ModelHandle<Worktree>,
1298 cx: &mut ModelContext<Self>,
1299 ) -> Task<Result<ModelHandle<Buffer>>> {
1300 let load_buffer = worktree.update(cx, |worktree, cx| {
1301 let worktree = worktree.as_local_mut().unwrap();
1302 worktree.load_buffer(path, cx)
1303 });
1304 cx.spawn(|this, mut cx| async move {
1305 let buffer = load_buffer.await?;
1306 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1307 Ok(buffer)
1308 })
1309 }
1310
1311 fn open_remote_buffer_internal(
1312 &mut self,
1313 path: &Arc<Path>,
1314 worktree: &ModelHandle<Worktree>,
1315 cx: &mut ModelContext<Self>,
1316 ) -> Task<Result<ModelHandle<Buffer>>> {
1317 let rpc = self.client.clone();
1318 let project_id = self.remote_id().unwrap();
1319 let remote_worktree_id = worktree.read(cx).id();
1320 let path = path.clone();
1321 let path_string = path.to_string_lossy().to_string();
1322 cx.spawn(|this, mut cx| async move {
1323 let response = rpc
1324 .request(proto::OpenBufferByPath {
1325 project_id,
1326 worktree_id: remote_worktree_id.to_proto(),
1327 path: path_string,
1328 })
1329 .await?;
1330 this.update(&mut cx, |this, cx| {
1331 this.wait_for_remote_buffer(response.buffer_id, cx)
1332 })
1333 .await
1334 })
1335 }
1336
1337 /// LanguageServerName is owned, because it is inserted into a map
1338 fn open_local_buffer_via_lsp(
1339 &mut self,
1340 abs_path: lsp::Url,
1341 language_server_id: usize,
1342 language_server_name: LanguageServerName,
1343 cx: &mut ModelContext<Self>,
1344 ) -> Task<Result<ModelHandle<Buffer>>> {
1345 cx.spawn(|this, mut cx| async move {
1346 let abs_path = abs_path
1347 .to_file_path()
1348 .map_err(|_| anyhow!("can't convert URI to path"))?;
1349 let (worktree, relative_path) = if let Some(result) =
1350 this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1351 {
1352 result
1353 } else {
1354 let worktree = this
1355 .update(&mut cx, |this, cx| {
1356 this.create_local_worktree(&abs_path, false, cx)
1357 })
1358 .await?;
1359 this.update(&mut cx, |this, cx| {
1360 this.language_server_ids.insert(
1361 (worktree.read(cx).id(), language_server_name),
1362 language_server_id,
1363 );
1364 });
1365 (worktree, PathBuf::new())
1366 };
1367
1368 let project_path = ProjectPath {
1369 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1370 path: relative_path.into(),
1371 };
1372 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1373 .await
1374 })
1375 }
1376
1377 pub fn open_buffer_by_id(
1378 &mut self,
1379 id: u64,
1380 cx: &mut ModelContext<Self>,
1381 ) -> Task<Result<ModelHandle<Buffer>>> {
1382 if let Some(buffer) = self.buffer_for_id(id, cx) {
1383 Task::ready(Ok(buffer))
1384 } else if self.is_local() {
1385 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1386 } else if let Some(project_id) = self.remote_id() {
1387 let request = self
1388 .client
1389 .request(proto::OpenBufferById { project_id, id });
1390 cx.spawn(|this, mut cx| async move {
1391 let buffer_id = request.await?.buffer_id;
1392 this.update(&mut cx, |this, cx| {
1393 this.wait_for_remote_buffer(buffer_id, cx)
1394 })
1395 .await
1396 })
1397 } else {
1398 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1399 }
1400 }
1401
1402 pub fn save_buffers(
1403 &self,
1404 buffers: HashSet<ModelHandle<Buffer>>,
1405 cx: &mut ModelContext<Self>,
1406 ) -> Task<Result<()>> {
1407 cx.spawn(|this, mut cx| async move {
1408 let save_tasks = buffers
1409 .into_iter()
1410 .map(|buffer| this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx)));
1411 try_join_all(save_tasks).await?;
1412 Ok(())
1413 })
1414 }
1415
1416 pub fn save_buffer(
1417 &self,
1418 buffer: ModelHandle<Buffer>,
1419 cx: &mut ModelContext<Self>,
1420 ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1421 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1422 return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1423 };
1424 let worktree = file.worktree.clone();
1425 let path = file.path.clone();
1426 worktree.update(cx, |worktree, cx| match worktree {
1427 Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1428 Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1429 })
1430 }
1431
1432 pub fn save_buffer_as(
1433 &mut self,
1434 buffer: ModelHandle<Buffer>,
1435 abs_path: PathBuf,
1436 cx: &mut ModelContext<Self>,
1437 ) -> Task<Result<()>> {
1438 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1439 let old_path =
1440 File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1441 cx.spawn(|this, mut cx| async move {
1442 if let Some(old_path) = old_path {
1443 this.update(&mut cx, |this, cx| {
1444 this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1445 });
1446 }
1447 let (worktree, path) = worktree_task.await?;
1448 worktree
1449 .update(&mut cx, |worktree, cx| match worktree {
1450 Worktree::Local(worktree) => {
1451 worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1452 }
1453 Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1454 })
1455 .await?;
1456 this.update(&mut cx, |this, cx| {
1457 this.detect_language_for_buffer(&buffer, cx);
1458 this.register_buffer_with_language_server(&buffer, cx);
1459 });
1460 Ok(())
1461 })
1462 }
1463
1464 pub fn get_open_buffer(
1465 &mut self,
1466 path: &ProjectPath,
1467 cx: &mut ModelContext<Self>,
1468 ) -> Option<ModelHandle<Buffer>> {
1469 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1470 self.opened_buffers.values().find_map(|buffer| {
1471 let buffer = buffer.upgrade(cx)?;
1472 let file = File::from_dyn(buffer.read(cx).file())?;
1473 if file.worktree == worktree && file.path() == &path.path {
1474 Some(buffer)
1475 } else {
1476 None
1477 }
1478 })
1479 }
1480
1481 fn register_buffer(
1482 &mut self,
1483 buffer: &ModelHandle<Buffer>,
1484 cx: &mut ModelContext<Self>,
1485 ) -> Result<()> {
1486 buffer.update(cx, |buffer, _| {
1487 buffer.set_language_registry(self.languages.clone())
1488 });
1489
1490 let remote_id = buffer.read(cx).remote_id();
1491 let is_remote = self.is_remote();
1492 let open_buffer = if is_remote || self.is_shared() {
1493 OpenBuffer::Strong(buffer.clone())
1494 } else {
1495 OpenBuffer::Weak(buffer.downgrade())
1496 };
1497
1498 match self.opened_buffers.entry(remote_id) {
1499 hash_map::Entry::Vacant(entry) => {
1500 entry.insert(open_buffer);
1501 }
1502 hash_map::Entry::Occupied(mut entry) => {
1503 if let OpenBuffer::Operations(operations) = entry.get_mut() {
1504 buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
1505 } else if entry.get().upgrade(cx).is_some() {
1506 if is_remote {
1507 return Ok(());
1508 } else {
1509 debug_panic!("buffer {} was already registered", remote_id);
1510 Err(anyhow!("buffer {} was already registered", remote_id))?;
1511 }
1512 }
1513 entry.insert(open_buffer);
1514 }
1515 }
1516 cx.subscribe(buffer, |this, buffer, event, cx| {
1517 this.on_buffer_event(buffer, event, cx);
1518 })
1519 .detach();
1520
1521 self.detect_language_for_buffer(buffer, cx);
1522 self.register_buffer_with_language_server(buffer, cx);
1523 cx.observe_release(buffer, |this, buffer, cx| {
1524 if let Some(file) = File::from_dyn(buffer.file()) {
1525 if file.is_local() {
1526 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1527 if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1528 server
1529 .notify::<lsp::notification::DidCloseTextDocument>(
1530 lsp::DidCloseTextDocumentParams {
1531 text_document: lsp::TextDocumentIdentifier::new(uri),
1532 },
1533 )
1534 .log_err();
1535 }
1536 }
1537 }
1538 })
1539 .detach();
1540
1541 *self.opened_buffer.0.borrow_mut() = ();
1542 Ok(())
1543 }
1544
1545 fn register_buffer_with_language_server(
1546 &mut self,
1547 buffer_handle: &ModelHandle<Buffer>,
1548 cx: &mut ModelContext<Self>,
1549 ) {
1550 let buffer = buffer_handle.read(cx);
1551 let buffer_id = buffer.remote_id();
1552 if let Some(file) = File::from_dyn(buffer.file()) {
1553 if file.is_local() {
1554 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1555 let initial_snapshot = buffer.text_snapshot();
1556
1557 let mut language_server = None;
1558 let mut language_id = None;
1559 if let Some(language) = buffer.language() {
1560 let worktree_id = file.worktree_id(cx);
1561 if let Some(adapter) = language.lsp_adapter() {
1562 language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1563 language_server = self
1564 .language_server_ids
1565 .get(&(worktree_id, adapter.name.clone()))
1566 .and_then(|id| self.language_servers.get(id))
1567 .and_then(|server_state| {
1568 if let LanguageServerState::Running { server, .. } = server_state {
1569 Some(server.clone())
1570 } else {
1571 None
1572 }
1573 });
1574 }
1575 }
1576
1577 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1578 if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1579 self.update_buffer_diagnostics(buffer_handle, diagnostics, None, cx)
1580 .log_err();
1581 }
1582 }
1583
1584 if let Some(server) = language_server {
1585 server
1586 .notify::<lsp::notification::DidOpenTextDocument>(
1587 lsp::DidOpenTextDocumentParams {
1588 text_document: lsp::TextDocumentItem::new(
1589 uri,
1590 language_id.unwrap_or_default(),
1591 0,
1592 initial_snapshot.text(),
1593 ),
1594 },
1595 )
1596 .log_err();
1597 buffer_handle.update(cx, |buffer, cx| {
1598 buffer.set_completion_triggers(
1599 server
1600 .capabilities()
1601 .completion_provider
1602 .as_ref()
1603 .and_then(|provider| provider.trigger_characters.clone())
1604 .unwrap_or_default(),
1605 cx,
1606 )
1607 });
1608 self.buffer_snapshots
1609 .insert(buffer_id, vec![(0, initial_snapshot)]);
1610 }
1611 }
1612 }
1613 }
1614
1615 fn unregister_buffer_from_language_server(
1616 &mut self,
1617 buffer: &ModelHandle<Buffer>,
1618 old_path: PathBuf,
1619 cx: &mut ModelContext<Self>,
1620 ) {
1621 buffer.update(cx, |buffer, cx| {
1622 buffer.update_diagnostics(Default::default(), cx);
1623 self.buffer_snapshots.remove(&buffer.remote_id());
1624 if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1625 language_server
1626 .notify::<lsp::notification::DidCloseTextDocument>(
1627 lsp::DidCloseTextDocumentParams {
1628 text_document: lsp::TextDocumentIdentifier::new(
1629 lsp::Url::from_file_path(old_path).unwrap(),
1630 ),
1631 },
1632 )
1633 .log_err();
1634 }
1635 });
1636 }
1637
1638 fn on_buffer_event(
1639 &mut self,
1640 buffer: ModelHandle<Buffer>,
1641 event: &BufferEvent,
1642 cx: &mut ModelContext<Self>,
1643 ) -> Option<()> {
1644 match event {
1645 BufferEvent::Operation(operation) => {
1646 if let Some(project_id) = self.remote_id() {
1647 let request = self.client.request(proto::UpdateBuffer {
1648 project_id,
1649 buffer_id: buffer.read(cx).remote_id(),
1650 operations: vec![language::proto::serialize_operation(operation)],
1651 });
1652 cx.background().spawn(request).detach_and_log_err(cx);
1653 }
1654 }
1655 BufferEvent::Edited { .. } => {
1656 let language_server = self
1657 .language_server_for_buffer(buffer.read(cx), cx)
1658 .map(|(_, server)| server.clone())?;
1659 let buffer = buffer.read(cx);
1660 let file = File::from_dyn(buffer.file())?;
1661 let abs_path = file.as_local()?.abs_path(cx);
1662 let uri = lsp::Url::from_file_path(abs_path).unwrap();
1663 let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1664 let (version, prev_snapshot) = buffer_snapshots.last()?;
1665 let next_snapshot = buffer.text_snapshot();
1666 let next_version = version + 1;
1667
1668 let content_changes = buffer
1669 .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1670 .map(|edit| {
1671 let edit_start = edit.new.start.0;
1672 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1673 let new_text = next_snapshot
1674 .text_for_range(edit.new.start.1..edit.new.end.1)
1675 .collect();
1676 lsp::TextDocumentContentChangeEvent {
1677 range: Some(lsp::Range::new(
1678 point_to_lsp(edit_start),
1679 point_to_lsp(edit_end),
1680 )),
1681 range_length: None,
1682 text: new_text,
1683 }
1684 })
1685 .collect();
1686
1687 buffer_snapshots.push((next_version, next_snapshot));
1688
1689 language_server
1690 .notify::<lsp::notification::DidChangeTextDocument>(
1691 lsp::DidChangeTextDocumentParams {
1692 text_document: lsp::VersionedTextDocumentIdentifier::new(
1693 uri,
1694 next_version,
1695 ),
1696 content_changes,
1697 },
1698 )
1699 .log_err();
1700 }
1701 BufferEvent::Saved => {
1702 let file = File::from_dyn(buffer.read(cx).file())?;
1703 let worktree_id = file.worktree_id(cx);
1704 let abs_path = file.as_local()?.abs_path(cx);
1705 let text_document = lsp::TextDocumentIdentifier {
1706 uri: lsp::Url::from_file_path(abs_path).unwrap(),
1707 };
1708
1709 for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1710 server
1711 .notify::<lsp::notification::DidSaveTextDocument>(
1712 lsp::DidSaveTextDocumentParams {
1713 text_document: text_document.clone(),
1714 text: None,
1715 },
1716 )
1717 .log_err();
1718 }
1719
1720 let language_server_id = self.language_server_id_for_buffer(buffer.read(cx), cx)?;
1721 if let Some(LanguageServerState::Running {
1722 adapter,
1723 simulate_disk_based_diagnostics_completion,
1724 ..
1725 }) = self.language_servers.get_mut(&language_server_id)
1726 {
1727 // After saving a buffer using a language server that doesn't provide
1728 // a disk-based progress token, kick off a timer that will reset every
1729 // time the buffer is saved. If the timer eventually fires, simulate
1730 // disk-based diagnostics being finished so that other pieces of UI
1731 // (e.g., project diagnostics view, diagnostic status bar) can update.
1732 // We don't emit an event right away because the language server might take
1733 // some time to publish diagnostics.
1734 if adapter.disk_based_diagnostics_progress_token.is_none() {
1735 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
1736
1737 let task = cx.spawn_weak(|this, mut cx| async move {
1738 cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
1739 if let Some(this) = this.upgrade(&cx) {
1740 this.update(&mut cx, |this, cx | {
1741 this.disk_based_diagnostics_finished(language_server_id, cx);
1742 this.broadcast_language_server_update(
1743 language_server_id,
1744 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1745 proto::LspDiskBasedDiagnosticsUpdated {},
1746 ),
1747 );
1748 });
1749 }
1750 });
1751 *simulate_disk_based_diagnostics_completion = Some(task);
1752 }
1753 }
1754 }
1755 _ => {}
1756 }
1757
1758 None
1759 }
1760
1761 fn language_servers_for_worktree(
1762 &self,
1763 worktree_id: WorktreeId,
1764 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
1765 self.language_server_ids
1766 .iter()
1767 .filter_map(move |((language_server_worktree_id, _), id)| {
1768 if *language_server_worktree_id == worktree_id {
1769 if let Some(LanguageServerState::Running {
1770 adapter,
1771 language,
1772 server,
1773 ..
1774 }) = self.language_servers.get(id)
1775 {
1776 return Some((adapter, language, server));
1777 }
1778 }
1779 None
1780 })
1781 }
1782
1783 fn maintain_buffer_languages(
1784 languages: &LanguageRegistry,
1785 cx: &mut ModelContext<Project>,
1786 ) -> Task<()> {
1787 let mut subscription = languages.subscribe();
1788 cx.spawn_weak(|project, mut cx| async move {
1789 while let Some(()) = subscription.next().await {
1790 if let Some(project) = project.upgrade(&cx) {
1791 project.update(&mut cx, |project, cx| {
1792 let mut plain_text_buffers = Vec::new();
1793 let mut buffers_with_unknown_injections = Vec::new();
1794 for buffer in project.opened_buffers.values() {
1795 if let Some(handle) = buffer.upgrade(cx) {
1796 let buffer = &handle.read(cx);
1797 if buffer.language().is_none()
1798 || buffer.language() == Some(&*language::PLAIN_TEXT)
1799 {
1800 plain_text_buffers.push(handle);
1801 } else if buffer.contains_unknown_injections() {
1802 buffers_with_unknown_injections.push(handle);
1803 }
1804 }
1805 }
1806
1807 for buffer in plain_text_buffers {
1808 project.detect_language_for_buffer(&buffer, cx);
1809 project.register_buffer_with_language_server(&buffer, cx);
1810 }
1811
1812 for buffer in buffers_with_unknown_injections {
1813 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
1814 }
1815 });
1816 }
1817 }
1818 })
1819 }
1820
1821 fn maintain_workspace_config(
1822 languages: Arc<LanguageRegistry>,
1823 cx: &mut ModelContext<Project>,
1824 ) -> Task<()> {
1825 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
1826 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
1827
1828 let settings_observation = cx.observe_global::<Settings, _>(move |_, _| {
1829 *settings_changed_tx.borrow_mut() = ();
1830 });
1831 cx.spawn_weak(|this, mut cx| async move {
1832 while let Some(_) = settings_changed_rx.next().await {
1833 let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
1834 if let Some(this) = this.upgrade(&cx) {
1835 this.read_with(&cx, |this, _| {
1836 for server_state in this.language_servers.values() {
1837 if let LanguageServerState::Running { server, .. } = server_state {
1838 server
1839 .notify::<lsp::notification::DidChangeConfiguration>(
1840 lsp::DidChangeConfigurationParams {
1841 settings: workspace_config.clone(),
1842 },
1843 )
1844 .ok();
1845 }
1846 }
1847 })
1848 } else {
1849 break;
1850 }
1851 }
1852
1853 drop(settings_observation);
1854 })
1855 }
1856
1857 fn detect_language_for_buffer(
1858 &mut self,
1859 buffer: &ModelHandle<Buffer>,
1860 cx: &mut ModelContext<Self>,
1861 ) -> Option<()> {
1862 // If the buffer has a language, set it and start the language server if we haven't already.
1863 let full_path = buffer.read(cx).file()?.full_path(cx);
1864 let new_language = self
1865 .languages
1866 .language_for_path(&full_path)
1867 .now_or_never()?
1868 .ok()?;
1869 self.set_language_for_buffer(buffer, new_language, cx);
1870 None
1871 }
1872
1873 pub fn set_language_for_buffer(
1874 &mut self,
1875 buffer: &ModelHandle<Buffer>,
1876 new_language: Arc<Language>,
1877 cx: &mut ModelContext<Self>,
1878 ) {
1879 buffer.update(cx, |buffer, cx| {
1880 if buffer.language().map_or(true, |old_language| {
1881 !Arc::ptr_eq(old_language, &new_language)
1882 }) {
1883 buffer.set_language(Some(new_language.clone()), cx);
1884 }
1885 });
1886
1887 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1888 if let Some(worktree) = file.worktree.read(cx).as_local() {
1889 let worktree_id = worktree.id();
1890 let worktree_abs_path = worktree.abs_path().clone();
1891 self.start_language_server(worktree_id, worktree_abs_path, new_language, cx);
1892 }
1893 }
1894 }
1895
1896 fn start_language_server(
1897 &mut self,
1898 worktree_id: WorktreeId,
1899 worktree_path: Arc<Path>,
1900 language: Arc<Language>,
1901 cx: &mut ModelContext<Self>,
1902 ) {
1903 if !cx
1904 .global::<Settings>()
1905 .enable_language_server(Some(&language.name()))
1906 {
1907 return;
1908 }
1909
1910 let adapter = if let Some(adapter) = language.lsp_adapter() {
1911 adapter
1912 } else {
1913 return;
1914 };
1915 let key = (worktree_id, adapter.name.clone());
1916
1917 let mut initialization_options = adapter.initialization_options.clone();
1918
1919 let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
1920 let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
1921 match (&mut initialization_options, override_options) {
1922 (Some(initialization_options), Some(override_options)) => {
1923 merge_json_value_into(override_options, initialization_options);
1924 }
1925 (None, override_options) => initialization_options = override_options,
1926 _ => {}
1927 }
1928
1929 self.language_server_ids
1930 .entry(key.clone())
1931 .or_insert_with(|| {
1932 let languages = self.languages.clone();
1933 let server_id = post_inc(&mut self.next_language_server_id);
1934 let language_server = self.languages.start_language_server(
1935 server_id,
1936 language.clone(),
1937 worktree_path,
1938 self.client.http_client(),
1939 cx,
1940 );
1941 self.language_servers.insert(
1942 server_id,
1943 LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
1944 let workspace_config =
1945 cx.update(|cx| languages.workspace_configuration(cx)).await;
1946 let language_server = language_server?.await.log_err()?;
1947 let language_server = language_server
1948 .initialize(initialization_options)
1949 .await
1950 .log_err()?;
1951 let this = this.upgrade(&cx)?;
1952
1953 language_server
1954 .on_notification::<lsp::notification::PublishDiagnostics, _>({
1955 let this = this.downgrade();
1956 let adapter = adapter.clone();
1957 move |mut params, cx| {
1958 let this = this;
1959 let adapter = adapter.clone();
1960 cx.spawn(|mut cx| async move {
1961 adapter.process_diagnostics(&mut params).await;
1962 if let Some(this) = this.upgrade(&cx) {
1963 this.update(&mut cx, |this, cx| {
1964 this.update_diagnostics(
1965 server_id,
1966 params,
1967 &adapter.disk_based_diagnostic_sources,
1968 cx,
1969 )
1970 .log_err();
1971 });
1972 }
1973 })
1974 .detach();
1975 }
1976 })
1977 .detach();
1978
1979 language_server
1980 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
1981 let languages = languages.clone();
1982 move |params, mut cx| {
1983 let languages = languages.clone();
1984 async move {
1985 let workspace_config = cx
1986 .update(|cx| languages.workspace_configuration(cx))
1987 .await;
1988 Ok(params
1989 .items
1990 .into_iter()
1991 .map(|item| {
1992 if let Some(section) = &item.section {
1993 workspace_config
1994 .get(section)
1995 .cloned()
1996 .unwrap_or(serde_json::Value::Null)
1997 } else {
1998 workspace_config.clone()
1999 }
2000 })
2001 .collect())
2002 }
2003 }
2004 })
2005 .detach();
2006
2007 // Even though we don't have handling for these requests, respond to them to
2008 // avoid stalling any language server like `gopls` which waits for a response
2009 // to these requests when initializing.
2010 language_server
2011 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2012 let this = this.downgrade();
2013 move |params, mut cx| async move {
2014 if let Some(this) = this.upgrade(&cx) {
2015 this.update(&mut cx, |this, _| {
2016 if let Some(status) =
2017 this.language_server_statuses.get_mut(&server_id)
2018 {
2019 if let lsp::NumberOrString::String(token) =
2020 params.token
2021 {
2022 status.progress_tokens.insert(token);
2023 }
2024 }
2025 });
2026 }
2027 Ok(())
2028 }
2029 })
2030 .detach();
2031 language_server
2032 .on_request::<lsp::request::RegisterCapability, _, _>({
2033 let this = this.downgrade();
2034 move |params, mut cx| async move {
2035 let this = this
2036 .upgrade(&cx)
2037 .ok_or_else(|| anyhow!("project dropped"))?;
2038 for reg in params.registrations {
2039 if reg.method == "workspace/didChangeWatchedFiles" {
2040 if let Some(options) = reg.register_options {
2041 let options = serde_json::from_value(options)?;
2042 this.update(&mut cx, |this, cx| {
2043 this.on_lsp_did_change_watched_files(
2044 server_id, options, cx,
2045 );
2046 });
2047 }
2048 }
2049 }
2050 Ok(())
2051 }
2052 })
2053 .detach();
2054
2055 language_server
2056 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2057 let this = this.downgrade();
2058 let adapter = adapter.clone();
2059 let language_server = language_server.clone();
2060 move |params, cx| {
2061 Self::on_lsp_workspace_edit(
2062 this,
2063 params,
2064 server_id,
2065 adapter.clone(),
2066 language_server.clone(),
2067 cx,
2068 )
2069 }
2070 })
2071 .detach();
2072
2073 let disk_based_diagnostics_progress_token =
2074 adapter.disk_based_diagnostics_progress_token.clone();
2075
2076 language_server
2077 .on_notification::<lsp::notification::Progress, _>({
2078 let this = this.downgrade();
2079 move |params, mut cx| {
2080 if let Some(this) = this.upgrade(&cx) {
2081 this.update(&mut cx, |this, cx| {
2082 this.on_lsp_progress(
2083 params,
2084 server_id,
2085 disk_based_diagnostics_progress_token.clone(),
2086 cx,
2087 );
2088 });
2089 }
2090 }
2091 })
2092 .detach();
2093
2094 language_server
2095 .notify::<lsp::notification::DidChangeConfiguration>(
2096 lsp::DidChangeConfigurationParams {
2097 settings: workspace_config,
2098 },
2099 )
2100 .ok();
2101
2102 this.update(&mut cx, |this, cx| {
2103 // If the language server for this key doesn't match the server id, don't store the
2104 // server. Which will cause it to be dropped, killing the process
2105 if this
2106 .language_server_ids
2107 .get(&key)
2108 .map(|id| id != &server_id)
2109 .unwrap_or(false)
2110 {
2111 return None;
2112 }
2113
2114 // Update language_servers collection with Running variant of LanguageServerState
2115 // indicating that the server is up and running and ready
2116 this.language_servers.insert(
2117 server_id,
2118 LanguageServerState::Running {
2119 adapter: adapter.clone(),
2120 language,
2121 watched_paths: Default::default(),
2122 server: language_server.clone(),
2123 simulate_disk_based_diagnostics_completion: None,
2124 },
2125 );
2126 this.language_server_statuses.insert(
2127 server_id,
2128 LanguageServerStatus {
2129 name: language_server.name().to_string(),
2130 pending_work: Default::default(),
2131 has_pending_diagnostic_updates: false,
2132 progress_tokens: Default::default(),
2133 },
2134 );
2135
2136 if let Some(project_id) = this.remote_id() {
2137 this.client
2138 .send(proto::StartLanguageServer {
2139 project_id,
2140 server: Some(proto::LanguageServer {
2141 id: server_id as u64,
2142 name: language_server.name().to_string(),
2143 }),
2144 })
2145 .log_err();
2146 }
2147
2148 // Tell the language server about every open buffer in the worktree that matches the language.
2149 for buffer in this.opened_buffers.values() {
2150 if let Some(buffer_handle) = buffer.upgrade(cx) {
2151 let buffer = buffer_handle.read(cx);
2152 let file = if let Some(file) = File::from_dyn(buffer.file()) {
2153 file
2154 } else {
2155 continue;
2156 };
2157 let language = if let Some(language) = buffer.language() {
2158 language
2159 } else {
2160 continue;
2161 };
2162 if file.worktree.read(cx).id() != key.0
2163 || language.lsp_adapter().map(|a| a.name.clone())
2164 != Some(key.1.clone())
2165 {
2166 continue;
2167 }
2168
2169 let file = file.as_local()?;
2170 let versions = this
2171 .buffer_snapshots
2172 .entry(buffer.remote_id())
2173 .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2174
2175 let (version, initial_snapshot) = versions.last().unwrap();
2176 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2177 language_server
2178 .notify::<lsp::notification::DidOpenTextDocument>(
2179 lsp::DidOpenTextDocumentParams {
2180 text_document: lsp::TextDocumentItem::new(
2181 uri,
2182 adapter
2183 .language_ids
2184 .get(language.name().as_ref())
2185 .cloned()
2186 .unwrap_or_default(),
2187 *version,
2188 initial_snapshot.text(),
2189 ),
2190 },
2191 )
2192 .log_err()?;
2193 buffer_handle.update(cx, |buffer, cx| {
2194 buffer.set_completion_triggers(
2195 language_server
2196 .capabilities()
2197 .completion_provider
2198 .as_ref()
2199 .and_then(|provider| {
2200 provider.trigger_characters.clone()
2201 })
2202 .unwrap_or_default(),
2203 cx,
2204 )
2205 });
2206 }
2207 }
2208
2209 cx.notify();
2210 Some(language_server)
2211 })
2212 })),
2213 );
2214
2215 server_id
2216 });
2217 }
2218
2219 // Returns a list of all of the worktrees which no longer have a language server and the root path
2220 // for the stopped server
2221 fn stop_language_server(
2222 &mut self,
2223 worktree_id: WorktreeId,
2224 adapter_name: LanguageServerName,
2225 cx: &mut ModelContext<Self>,
2226 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2227 let key = (worktree_id, adapter_name);
2228 if let Some(server_id) = self.language_server_ids.remove(&key) {
2229 // Remove other entries for this language server as well
2230 let mut orphaned_worktrees = vec![worktree_id];
2231 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2232 for other_key in other_keys {
2233 if self.language_server_ids.get(&other_key) == Some(&server_id) {
2234 self.language_server_ids.remove(&other_key);
2235 orphaned_worktrees.push(other_key.0);
2236 }
2237 }
2238
2239 self.language_server_statuses.remove(&server_id);
2240 cx.notify();
2241
2242 let server_state = self.language_servers.remove(&server_id);
2243 cx.spawn_weak(|this, mut cx| async move {
2244 let mut root_path = None;
2245
2246 let server = match server_state {
2247 Some(LanguageServerState::Starting(started_language_server)) => {
2248 started_language_server.await
2249 }
2250 Some(LanguageServerState::Running { server, .. }) => Some(server),
2251 None => None,
2252 };
2253
2254 if let Some(server) = server {
2255 root_path = Some(server.root_path().clone());
2256 if let Some(shutdown) = server.shutdown() {
2257 shutdown.await;
2258 }
2259 }
2260
2261 if let Some(this) = this.upgrade(&cx) {
2262 this.update(&mut cx, |this, cx| {
2263 this.language_server_statuses.remove(&server_id);
2264 cx.notify();
2265 });
2266 }
2267
2268 (root_path, orphaned_worktrees)
2269 })
2270 } else {
2271 Task::ready((None, Vec::new()))
2272 }
2273 }
2274
2275 pub fn restart_language_servers_for_buffers(
2276 &mut self,
2277 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2278 cx: &mut ModelContext<Self>,
2279 ) -> Option<()> {
2280 let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2281 .into_iter()
2282 .filter_map(|buffer| {
2283 let file = File::from_dyn(buffer.read(cx).file())?;
2284 let worktree = file.worktree.read(cx).as_local()?;
2285 let worktree_id = worktree.id();
2286 let worktree_abs_path = worktree.abs_path().clone();
2287 let full_path = file.full_path(cx);
2288 Some((worktree_id, worktree_abs_path, full_path))
2289 })
2290 .collect();
2291 for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2292 if let Some(language) = self
2293 .languages
2294 .language_for_path(&full_path)
2295 .now_or_never()
2296 .and_then(|language| language.ok())
2297 {
2298 self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2299 }
2300 }
2301
2302 None
2303 }
2304
2305 fn restart_language_server(
2306 &mut self,
2307 worktree_id: WorktreeId,
2308 fallback_path: Arc<Path>,
2309 language: Arc<Language>,
2310 cx: &mut ModelContext<Self>,
2311 ) {
2312 let adapter = if let Some(adapter) = language.lsp_adapter() {
2313 adapter
2314 } else {
2315 return;
2316 };
2317
2318 let server_name = adapter.name.clone();
2319 let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2320 cx.spawn_weak(|this, mut cx| async move {
2321 let (original_root_path, orphaned_worktrees) = stop.await;
2322 if let Some(this) = this.upgrade(&cx) {
2323 this.update(&mut cx, |this, cx| {
2324 // Attempt to restart using original server path. Fallback to passed in
2325 // path if we could not retrieve the root path
2326 let root_path = original_root_path
2327 .map(|path_buf| Arc::from(path_buf.as_path()))
2328 .unwrap_or(fallback_path);
2329
2330 this.start_language_server(worktree_id, root_path, language, cx);
2331
2332 // Lookup new server id and set it for each of the orphaned worktrees
2333 if let Some(new_server_id) = this
2334 .language_server_ids
2335 .get(&(worktree_id, server_name.clone()))
2336 .cloned()
2337 {
2338 for orphaned_worktree in orphaned_worktrees {
2339 this.language_server_ids
2340 .insert((orphaned_worktree, server_name.clone()), new_server_id);
2341 }
2342 }
2343 });
2344 }
2345 })
2346 .detach();
2347 }
2348
2349 fn on_lsp_progress(
2350 &mut self,
2351 progress: lsp::ProgressParams,
2352 server_id: usize,
2353 disk_based_diagnostics_progress_token: Option<String>,
2354 cx: &mut ModelContext<Self>,
2355 ) {
2356 let token = match progress.token {
2357 lsp::NumberOrString::String(token) => token,
2358 lsp::NumberOrString::Number(token) => {
2359 log::info!("skipping numeric progress token {}", token);
2360 return;
2361 }
2362 };
2363 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2364 let language_server_status =
2365 if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2366 status
2367 } else {
2368 return;
2369 };
2370
2371 if !language_server_status.progress_tokens.contains(&token) {
2372 return;
2373 }
2374
2375 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
2376 .as_ref()
2377 .map_or(false, |disk_based_token| {
2378 token.starts_with(disk_based_token)
2379 });
2380
2381 match progress {
2382 lsp::WorkDoneProgress::Begin(report) => {
2383 if is_disk_based_diagnostics_progress {
2384 language_server_status.has_pending_diagnostic_updates = true;
2385 self.disk_based_diagnostics_started(server_id, cx);
2386 self.broadcast_language_server_update(
2387 server_id,
2388 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2389 proto::LspDiskBasedDiagnosticsUpdating {},
2390 ),
2391 );
2392 } else {
2393 self.on_lsp_work_start(
2394 server_id,
2395 token.clone(),
2396 LanguageServerProgress {
2397 message: report.message.clone(),
2398 percentage: report.percentage.map(|p| p as usize),
2399 last_update_at: Instant::now(),
2400 },
2401 cx,
2402 );
2403 self.broadcast_language_server_update(
2404 server_id,
2405 proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2406 token,
2407 message: report.message,
2408 percentage: report.percentage.map(|p| p as u32),
2409 }),
2410 );
2411 }
2412 }
2413 lsp::WorkDoneProgress::Report(report) => {
2414 if !is_disk_based_diagnostics_progress {
2415 self.on_lsp_work_progress(
2416 server_id,
2417 token.clone(),
2418 LanguageServerProgress {
2419 message: report.message.clone(),
2420 percentage: report.percentage.map(|p| p as usize),
2421 last_update_at: Instant::now(),
2422 },
2423 cx,
2424 );
2425 self.broadcast_language_server_update(
2426 server_id,
2427 proto::update_language_server::Variant::WorkProgress(
2428 proto::LspWorkProgress {
2429 token,
2430 message: report.message,
2431 percentage: report.percentage.map(|p| p as u32),
2432 },
2433 ),
2434 );
2435 }
2436 }
2437 lsp::WorkDoneProgress::End(_) => {
2438 language_server_status.progress_tokens.remove(&token);
2439
2440 if is_disk_based_diagnostics_progress {
2441 language_server_status.has_pending_diagnostic_updates = false;
2442 self.disk_based_diagnostics_finished(server_id, cx);
2443 self.broadcast_language_server_update(
2444 server_id,
2445 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2446 proto::LspDiskBasedDiagnosticsUpdated {},
2447 ),
2448 );
2449 } else {
2450 self.on_lsp_work_end(server_id, token.clone(), cx);
2451 self.broadcast_language_server_update(
2452 server_id,
2453 proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2454 token,
2455 }),
2456 );
2457 }
2458 }
2459 }
2460 }
2461
2462 fn on_lsp_work_start(
2463 &mut self,
2464 language_server_id: usize,
2465 token: String,
2466 progress: LanguageServerProgress,
2467 cx: &mut ModelContext<Self>,
2468 ) {
2469 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2470 status.pending_work.insert(token, progress);
2471 cx.notify();
2472 }
2473 }
2474
2475 fn on_lsp_work_progress(
2476 &mut self,
2477 language_server_id: usize,
2478 token: String,
2479 progress: LanguageServerProgress,
2480 cx: &mut ModelContext<Self>,
2481 ) {
2482 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2483 let entry = status
2484 .pending_work
2485 .entry(token)
2486 .or_insert(LanguageServerProgress {
2487 message: Default::default(),
2488 percentage: Default::default(),
2489 last_update_at: progress.last_update_at,
2490 });
2491 if progress.message.is_some() {
2492 entry.message = progress.message;
2493 }
2494 if progress.percentage.is_some() {
2495 entry.percentage = progress.percentage;
2496 }
2497 entry.last_update_at = progress.last_update_at;
2498 cx.notify();
2499 }
2500 }
2501
2502 fn on_lsp_work_end(
2503 &mut self,
2504 language_server_id: usize,
2505 token: String,
2506 cx: &mut ModelContext<Self>,
2507 ) {
2508 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2509 status.pending_work.remove(&token);
2510 cx.notify();
2511 }
2512 }
2513
2514 fn on_lsp_did_change_watched_files(
2515 &mut self,
2516 language_server_id: usize,
2517 params: DidChangeWatchedFilesRegistrationOptions,
2518 cx: &mut ModelContext<Self>,
2519 ) {
2520 if let Some(LanguageServerState::Running { watched_paths, .. }) =
2521 self.language_servers.get_mut(&language_server_id)
2522 {
2523 watched_paths.clear();
2524 for watcher in params.watchers {
2525 watched_paths.add_pattern(&watcher.glob_pattern).log_err();
2526 }
2527 cx.notify();
2528 }
2529 }
2530
2531 async fn on_lsp_workspace_edit(
2532 this: WeakModelHandle<Self>,
2533 params: lsp::ApplyWorkspaceEditParams,
2534 server_id: usize,
2535 adapter: Arc<CachedLspAdapter>,
2536 language_server: Arc<LanguageServer>,
2537 mut cx: AsyncAppContext,
2538 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2539 let this = this
2540 .upgrade(&cx)
2541 .ok_or_else(|| anyhow!("project project closed"))?;
2542 let transaction = Self::deserialize_workspace_edit(
2543 this.clone(),
2544 params.edit,
2545 true,
2546 adapter.clone(),
2547 language_server.clone(),
2548 &mut cx,
2549 )
2550 .await
2551 .log_err();
2552 this.update(&mut cx, |this, _| {
2553 if let Some(transaction) = transaction {
2554 this.last_workspace_edits_by_language_server
2555 .insert(server_id, transaction);
2556 }
2557 });
2558 Ok(lsp::ApplyWorkspaceEditResponse {
2559 applied: true,
2560 failed_change: None,
2561 failure_reason: None,
2562 })
2563 }
2564
2565 fn broadcast_language_server_update(
2566 &self,
2567 language_server_id: usize,
2568 event: proto::update_language_server::Variant,
2569 ) {
2570 if let Some(project_id) = self.remote_id() {
2571 self.client
2572 .send(proto::UpdateLanguageServer {
2573 project_id,
2574 language_server_id: language_server_id as u64,
2575 variant: Some(event),
2576 })
2577 .log_err();
2578 }
2579 }
2580
2581 pub fn language_server_statuses(
2582 &self,
2583 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2584 self.language_server_statuses.values()
2585 }
2586
2587 pub fn update_diagnostics(
2588 &mut self,
2589 language_server_id: usize,
2590 mut params: lsp::PublishDiagnosticsParams,
2591 disk_based_sources: &[String],
2592 cx: &mut ModelContext<Self>,
2593 ) -> Result<()> {
2594 let abs_path = params
2595 .uri
2596 .to_file_path()
2597 .map_err(|_| anyhow!("URI is not a file"))?;
2598 let mut diagnostics = Vec::default();
2599 let mut primary_diagnostic_group_ids = HashMap::default();
2600 let mut sources_by_group_id = HashMap::default();
2601 let mut supporting_diagnostics = HashMap::default();
2602
2603 // Ensure that primary diagnostics are always the most severe
2604 params.diagnostics.sort_by_key(|item| item.severity);
2605
2606 for diagnostic in ¶ms.diagnostics {
2607 let source = diagnostic.source.as_ref();
2608 let code = diagnostic.code.as_ref().map(|code| match code {
2609 lsp::NumberOrString::Number(code) => code.to_string(),
2610 lsp::NumberOrString::String(code) => code.clone(),
2611 });
2612 let range = range_from_lsp(diagnostic.range);
2613 let is_supporting = diagnostic
2614 .related_information
2615 .as_ref()
2616 .map_or(false, |infos| {
2617 infos.iter().any(|info| {
2618 primary_diagnostic_group_ids.contains_key(&(
2619 source,
2620 code.clone(),
2621 range_from_lsp(info.location.range),
2622 ))
2623 })
2624 });
2625
2626 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2627 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2628 });
2629
2630 if is_supporting {
2631 supporting_diagnostics.insert(
2632 (source, code.clone(), range),
2633 (diagnostic.severity, is_unnecessary),
2634 );
2635 } else {
2636 let group_id = post_inc(&mut self.next_diagnostic_group_id);
2637 let is_disk_based =
2638 source.map_or(false, |source| disk_based_sources.contains(source));
2639
2640 sources_by_group_id.insert(group_id, source);
2641 primary_diagnostic_group_ids
2642 .insert((source, code.clone(), range.clone()), group_id);
2643
2644 diagnostics.push(DiagnosticEntry {
2645 range,
2646 diagnostic: Diagnostic {
2647 code: code.clone(),
2648 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2649 message: diagnostic.message.clone(),
2650 group_id,
2651 is_primary: true,
2652 is_valid: true,
2653 is_disk_based,
2654 is_unnecessary,
2655 },
2656 });
2657 if let Some(infos) = &diagnostic.related_information {
2658 for info in infos {
2659 if info.location.uri == params.uri && !info.message.is_empty() {
2660 let range = range_from_lsp(info.location.range);
2661 diagnostics.push(DiagnosticEntry {
2662 range,
2663 diagnostic: Diagnostic {
2664 code: code.clone(),
2665 severity: DiagnosticSeverity::INFORMATION,
2666 message: info.message.clone(),
2667 group_id,
2668 is_primary: false,
2669 is_valid: true,
2670 is_disk_based,
2671 is_unnecessary: false,
2672 },
2673 });
2674 }
2675 }
2676 }
2677 }
2678 }
2679
2680 for entry in &mut diagnostics {
2681 let diagnostic = &mut entry.diagnostic;
2682 if !diagnostic.is_primary {
2683 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2684 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2685 source,
2686 diagnostic.code.clone(),
2687 entry.range.clone(),
2688 )) {
2689 if let Some(severity) = severity {
2690 diagnostic.severity = severity;
2691 }
2692 diagnostic.is_unnecessary = is_unnecessary;
2693 }
2694 }
2695 }
2696
2697 self.update_diagnostic_entries(
2698 language_server_id,
2699 abs_path,
2700 params.version,
2701 diagnostics,
2702 cx,
2703 )?;
2704 Ok(())
2705 }
2706
2707 pub fn update_diagnostic_entries(
2708 &mut self,
2709 language_server_id: usize,
2710 abs_path: PathBuf,
2711 version: Option<i32>,
2712 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2713 cx: &mut ModelContext<Project>,
2714 ) -> Result<(), anyhow::Error> {
2715 let (worktree, relative_path) = self
2716 .find_local_worktree(&abs_path, cx)
2717 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2718
2719 let project_path = ProjectPath {
2720 worktree_id: worktree.read(cx).id(),
2721 path: relative_path.into(),
2722 };
2723
2724 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2725 self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2726 }
2727
2728 let updated = worktree.update(cx, |worktree, cx| {
2729 worktree
2730 .as_local_mut()
2731 .ok_or_else(|| anyhow!("not a local worktree"))?
2732 .update_diagnostics(
2733 language_server_id,
2734 project_path.path.clone(),
2735 diagnostics,
2736 cx,
2737 )
2738 })?;
2739 if updated {
2740 cx.emit(Event::DiagnosticsUpdated {
2741 language_server_id,
2742 path: project_path,
2743 });
2744 }
2745 Ok(())
2746 }
2747
2748 fn update_buffer_diagnostics(
2749 &mut self,
2750 buffer: &ModelHandle<Buffer>,
2751 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2752 version: Option<i32>,
2753 cx: &mut ModelContext<Self>,
2754 ) -> Result<()> {
2755 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2756 Ordering::Equal
2757 .then_with(|| b.is_primary.cmp(&a.is_primary))
2758 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2759 .then_with(|| a.severity.cmp(&b.severity))
2760 .then_with(|| a.message.cmp(&b.message))
2761 }
2762
2763 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2764
2765 diagnostics.sort_unstable_by(|a, b| {
2766 Ordering::Equal
2767 .then_with(|| a.range.start.cmp(&b.range.start))
2768 .then_with(|| b.range.end.cmp(&a.range.end))
2769 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2770 });
2771
2772 let mut sanitized_diagnostics = Vec::new();
2773 let edits_since_save = Patch::new(
2774 snapshot
2775 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
2776 .collect(),
2777 );
2778 for entry in diagnostics {
2779 let start;
2780 let end;
2781 if entry.diagnostic.is_disk_based {
2782 // Some diagnostics are based on files on disk instead of buffers'
2783 // current contents. Adjust these diagnostics' ranges to reflect
2784 // any unsaved edits.
2785 start = edits_since_save.old_to_new(entry.range.start);
2786 end = edits_since_save.old_to_new(entry.range.end);
2787 } else {
2788 start = entry.range.start;
2789 end = entry.range.end;
2790 }
2791
2792 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2793 ..snapshot.clip_point_utf16(end, Bias::Right);
2794
2795 // Expand empty ranges by one codepoint
2796 if range.start == range.end {
2797 // This will be go to the next boundary when being clipped
2798 range.end.column += 1;
2799 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
2800 if range.start == range.end && range.end.column > 0 {
2801 range.start.column -= 1;
2802 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
2803 }
2804 }
2805
2806 sanitized_diagnostics.push(DiagnosticEntry {
2807 range,
2808 diagnostic: entry.diagnostic,
2809 });
2810 }
2811 drop(edits_since_save);
2812
2813 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2814 buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2815 Ok(())
2816 }
2817
2818 pub fn reload_buffers(
2819 &self,
2820 buffers: HashSet<ModelHandle<Buffer>>,
2821 push_to_history: bool,
2822 cx: &mut ModelContext<Self>,
2823 ) -> Task<Result<ProjectTransaction>> {
2824 let mut local_buffers = Vec::new();
2825 let mut remote_buffers = None;
2826 for buffer_handle in buffers {
2827 let buffer = buffer_handle.read(cx);
2828 if buffer.is_dirty() {
2829 if let Some(file) = File::from_dyn(buffer.file()) {
2830 if file.is_local() {
2831 local_buffers.push(buffer_handle);
2832 } else {
2833 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2834 }
2835 }
2836 }
2837 }
2838
2839 let remote_buffers = self.remote_id().zip(remote_buffers);
2840 let client = self.client.clone();
2841
2842 cx.spawn(|this, mut cx| async move {
2843 let mut project_transaction = ProjectTransaction::default();
2844
2845 if let Some((project_id, remote_buffers)) = remote_buffers {
2846 let response = client
2847 .request(proto::ReloadBuffers {
2848 project_id,
2849 buffer_ids: remote_buffers
2850 .iter()
2851 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2852 .collect(),
2853 })
2854 .await?
2855 .transaction
2856 .ok_or_else(|| anyhow!("missing transaction"))?;
2857 project_transaction = this
2858 .update(&mut cx, |this, cx| {
2859 this.deserialize_project_transaction(response, push_to_history, cx)
2860 })
2861 .await?;
2862 }
2863
2864 for buffer in local_buffers {
2865 let transaction = buffer
2866 .update(&mut cx, |buffer, cx| buffer.reload(cx))
2867 .await?;
2868 buffer.update(&mut cx, |buffer, cx| {
2869 if let Some(transaction) = transaction {
2870 if !push_to_history {
2871 buffer.forget_transaction(transaction.id);
2872 }
2873 project_transaction.0.insert(cx.handle(), transaction);
2874 }
2875 });
2876 }
2877
2878 Ok(project_transaction)
2879 })
2880 }
2881
2882 pub fn format(
2883 &self,
2884 buffers: HashSet<ModelHandle<Buffer>>,
2885 push_to_history: bool,
2886 trigger: FormatTrigger,
2887 cx: &mut ModelContext<Project>,
2888 ) -> Task<Result<ProjectTransaction>> {
2889 if self.is_local() {
2890 let mut buffers_with_paths_and_servers = buffers
2891 .into_iter()
2892 .filter_map(|buffer_handle| {
2893 let buffer = buffer_handle.read(cx);
2894 let file = File::from_dyn(buffer.file())?;
2895 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
2896 let server = self
2897 .language_server_for_buffer(buffer, cx)
2898 .map(|s| s.1.clone());
2899 Some((buffer_handle, buffer_abs_path, server))
2900 })
2901 .collect::<Vec<_>>();
2902
2903 cx.spawn(|this, mut cx| async move {
2904 // Do not allow multiple concurrent formatting requests for the
2905 // same buffer.
2906 this.update(&mut cx, |this, _| {
2907 buffers_with_paths_and_servers
2908 .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
2909 });
2910
2911 let _cleanup = defer({
2912 let this = this.clone();
2913 let mut cx = cx.clone();
2914 let buffers = &buffers_with_paths_and_servers;
2915 move || {
2916 this.update(&mut cx, |this, _| {
2917 for (buffer, _, _) in buffers {
2918 this.buffers_being_formatted.remove(&buffer.id());
2919 }
2920 });
2921 }
2922 });
2923
2924 let mut project_transaction = ProjectTransaction::default();
2925 for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
2926 let (
2927 format_on_save,
2928 remove_trailing_whitespace,
2929 ensure_final_newline,
2930 formatter,
2931 tab_size,
2932 ) = buffer.read_with(&cx, |buffer, cx| {
2933 let settings = cx.global::<Settings>();
2934 let language_name = buffer.language().map(|language| language.name());
2935 (
2936 settings.format_on_save(language_name.as_deref()),
2937 settings.remove_trailing_whitespace_on_save(language_name.as_deref()),
2938 settings.ensure_final_newline_on_save(language_name.as_deref()),
2939 settings.formatter(language_name.as_deref()),
2940 settings.tab_size(language_name.as_deref()),
2941 )
2942 });
2943
2944 // First, format buffer's whitespace according to the settings.
2945 let trailing_whitespace_diff = if remove_trailing_whitespace {
2946 Some(
2947 buffer
2948 .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
2949 .await,
2950 )
2951 } else {
2952 None
2953 };
2954 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
2955 buffer.finalize_last_transaction();
2956 buffer.start_transaction();
2957 if let Some(diff) = trailing_whitespace_diff {
2958 buffer.apply_diff(diff, cx);
2959 }
2960 if ensure_final_newline {
2961 buffer.ensure_final_newline(cx);
2962 }
2963 buffer.end_transaction(cx)
2964 });
2965
2966 // Currently, formatting operations are represented differently depending on
2967 // whether they come from a language server or an external command.
2968 enum FormatOperation {
2969 Lsp(Vec<(Range<Anchor>, String)>),
2970 External(Diff),
2971 }
2972
2973 // Apply language-specific formatting using either a language server
2974 // or external command.
2975 let mut format_operation = None;
2976 match (formatter, format_on_save) {
2977 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
2978
2979 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
2980 | (_, FormatOnSave::LanguageServer) => {
2981 if let Some((language_server, buffer_abs_path)) =
2982 language_server.as_ref().zip(buffer_abs_path.as_ref())
2983 {
2984 format_operation = Some(FormatOperation::Lsp(
2985 Self::format_via_lsp(
2986 &this,
2987 &buffer,
2988 buffer_abs_path,
2989 &language_server,
2990 tab_size,
2991 &mut cx,
2992 )
2993 .await
2994 .context("failed to format via language server")?,
2995 ));
2996 }
2997 }
2998
2999 (
3000 Formatter::External { command, arguments },
3001 FormatOnSave::On | FormatOnSave::Off,
3002 )
3003 | (_, FormatOnSave::External { command, arguments }) => {
3004 if let Some(buffer_abs_path) = buffer_abs_path {
3005 format_operation = Self::format_via_external_command(
3006 &buffer,
3007 &buffer_abs_path,
3008 &command,
3009 &arguments,
3010 &mut cx,
3011 )
3012 .await
3013 .context(format!(
3014 "failed to format via external command {:?}",
3015 command
3016 ))?
3017 .map(FormatOperation::External);
3018 }
3019 }
3020 };
3021
3022 buffer.update(&mut cx, |b, cx| {
3023 // If the buffer had its whitespace formatted and was edited while the language-specific
3024 // formatting was being computed, avoid applying the language-specific formatting, because
3025 // it can't be grouped with the whitespace formatting in the undo history.
3026 if let Some(transaction_id) = whitespace_transaction_id {
3027 if b.peek_undo_stack()
3028 .map_or(true, |e| e.transaction_id() != transaction_id)
3029 {
3030 format_operation.take();
3031 }
3032 }
3033
3034 // Apply any language-specific formatting, and group the two formatting operations
3035 // in the buffer's undo history.
3036 if let Some(operation) = format_operation {
3037 match operation {
3038 FormatOperation::Lsp(edits) => {
3039 b.edit(edits, None, cx);
3040 }
3041 FormatOperation::External(diff) => {
3042 b.apply_diff(diff, cx);
3043 }
3044 }
3045
3046 if let Some(transaction_id) = whitespace_transaction_id {
3047 b.group_until_transaction(transaction_id);
3048 }
3049 }
3050
3051 if let Some(transaction) = b.finalize_last_transaction().cloned() {
3052 if !push_to_history {
3053 b.forget_transaction(transaction.id);
3054 }
3055 project_transaction.0.insert(buffer.clone(), transaction);
3056 }
3057 });
3058 }
3059
3060 Ok(project_transaction)
3061 })
3062 } else {
3063 let remote_id = self.remote_id();
3064 let client = self.client.clone();
3065 cx.spawn(|this, mut cx| async move {
3066 let mut project_transaction = ProjectTransaction::default();
3067 if let Some(project_id) = remote_id {
3068 let response = client
3069 .request(proto::FormatBuffers {
3070 project_id,
3071 trigger: trigger as i32,
3072 buffer_ids: buffers
3073 .iter()
3074 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3075 .collect(),
3076 })
3077 .await?
3078 .transaction
3079 .ok_or_else(|| anyhow!("missing transaction"))?;
3080 project_transaction = this
3081 .update(&mut cx, |this, cx| {
3082 this.deserialize_project_transaction(response, push_to_history, cx)
3083 })
3084 .await?;
3085 }
3086 Ok(project_transaction)
3087 })
3088 }
3089 }
3090
3091 async fn format_via_lsp(
3092 this: &ModelHandle<Self>,
3093 buffer: &ModelHandle<Buffer>,
3094 abs_path: &Path,
3095 language_server: &Arc<LanguageServer>,
3096 tab_size: NonZeroU32,
3097 cx: &mut AsyncAppContext,
3098 ) -> Result<Vec<(Range<Anchor>, String)>> {
3099 let text_document =
3100 lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3101 let capabilities = &language_server.capabilities();
3102 let lsp_edits = if capabilities
3103 .document_formatting_provider
3104 .as_ref()
3105 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3106 {
3107 language_server
3108 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3109 text_document,
3110 options: lsp::FormattingOptions {
3111 tab_size: tab_size.into(),
3112 insert_spaces: true,
3113 insert_final_newline: Some(true),
3114 ..Default::default()
3115 },
3116 work_done_progress_params: Default::default(),
3117 })
3118 .await?
3119 } else if capabilities
3120 .document_range_formatting_provider
3121 .as_ref()
3122 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3123 {
3124 let buffer_start = lsp::Position::new(0, 0);
3125 let buffer_end =
3126 buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3127 language_server
3128 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3129 text_document,
3130 range: lsp::Range::new(buffer_start, buffer_end),
3131 options: lsp::FormattingOptions {
3132 tab_size: tab_size.into(),
3133 insert_spaces: true,
3134 insert_final_newline: Some(true),
3135 ..Default::default()
3136 },
3137 work_done_progress_params: Default::default(),
3138 })
3139 .await?
3140 } else {
3141 None
3142 };
3143
3144 if let Some(lsp_edits) = lsp_edits {
3145 this.update(cx, |this, cx| {
3146 this.edits_from_lsp(buffer, lsp_edits, None, cx)
3147 })
3148 .await
3149 } else {
3150 Ok(Default::default())
3151 }
3152 }
3153
3154 async fn format_via_external_command(
3155 buffer: &ModelHandle<Buffer>,
3156 buffer_abs_path: &Path,
3157 command: &str,
3158 arguments: &[String],
3159 cx: &mut AsyncAppContext,
3160 ) -> Result<Option<Diff>> {
3161 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3162 let file = File::from_dyn(buffer.file())?;
3163 let worktree = file.worktree.read(cx).as_local()?;
3164 let mut worktree_path = worktree.abs_path().to_path_buf();
3165 if worktree.root_entry()?.is_file() {
3166 worktree_path.pop();
3167 }
3168 Some(worktree_path)
3169 });
3170
3171 if let Some(working_dir_path) = working_dir_path {
3172 let mut child =
3173 smol::process::Command::new(command)
3174 .args(arguments.iter().map(|arg| {
3175 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3176 }))
3177 .current_dir(&working_dir_path)
3178 .stdin(smol::process::Stdio::piped())
3179 .stdout(smol::process::Stdio::piped())
3180 .stderr(smol::process::Stdio::piped())
3181 .spawn()?;
3182 let stdin = child
3183 .stdin
3184 .as_mut()
3185 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3186 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3187 for chunk in text.chunks() {
3188 stdin.write_all(chunk.as_bytes()).await?;
3189 }
3190 stdin.flush().await?;
3191
3192 let output = child.output().await?;
3193 if !output.status.success() {
3194 return Err(anyhow!(
3195 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3196 output.status.code(),
3197 String::from_utf8_lossy(&output.stdout),
3198 String::from_utf8_lossy(&output.stderr),
3199 ));
3200 }
3201
3202 let stdout = String::from_utf8(output.stdout)?;
3203 Ok(Some(
3204 buffer
3205 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3206 .await,
3207 ))
3208 } else {
3209 Ok(None)
3210 }
3211 }
3212
3213 pub fn definition<T: ToPointUtf16>(
3214 &self,
3215 buffer: &ModelHandle<Buffer>,
3216 position: T,
3217 cx: &mut ModelContext<Self>,
3218 ) -> Task<Result<Vec<LocationLink>>> {
3219 let position = position.to_point_utf16(buffer.read(cx));
3220 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3221 }
3222
3223 pub fn type_definition<T: ToPointUtf16>(
3224 &self,
3225 buffer: &ModelHandle<Buffer>,
3226 position: T,
3227 cx: &mut ModelContext<Self>,
3228 ) -> Task<Result<Vec<LocationLink>>> {
3229 let position = position.to_point_utf16(buffer.read(cx));
3230 self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3231 }
3232
3233 pub fn references<T: ToPointUtf16>(
3234 &self,
3235 buffer: &ModelHandle<Buffer>,
3236 position: T,
3237 cx: &mut ModelContext<Self>,
3238 ) -> Task<Result<Vec<Location>>> {
3239 let position = position.to_point_utf16(buffer.read(cx));
3240 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3241 }
3242
3243 pub fn document_highlights<T: ToPointUtf16>(
3244 &self,
3245 buffer: &ModelHandle<Buffer>,
3246 position: T,
3247 cx: &mut ModelContext<Self>,
3248 ) -> Task<Result<Vec<DocumentHighlight>>> {
3249 let position = position.to_point_utf16(buffer.read(cx));
3250 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3251 }
3252
3253 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3254 if self.is_local() {
3255 let mut requests = Vec::new();
3256 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3257 let worktree_id = *worktree_id;
3258 if let Some(worktree) = self
3259 .worktree_for_id(worktree_id, cx)
3260 .and_then(|worktree| worktree.read(cx).as_local())
3261 {
3262 if let Some(LanguageServerState::Running {
3263 adapter,
3264 language,
3265 server,
3266 ..
3267 }) = self.language_servers.get(server_id)
3268 {
3269 let adapter = adapter.clone();
3270 let language = language.clone();
3271 let worktree_abs_path = worktree.abs_path().clone();
3272 requests.push(
3273 server
3274 .request::<lsp::request::WorkspaceSymbol>(
3275 lsp::WorkspaceSymbolParams {
3276 query: query.to_string(),
3277 ..Default::default()
3278 },
3279 )
3280 .log_err()
3281 .map(move |response| {
3282 (
3283 adapter,
3284 language,
3285 worktree_id,
3286 worktree_abs_path,
3287 response.unwrap_or_default(),
3288 )
3289 }),
3290 );
3291 }
3292 }
3293 }
3294
3295 cx.spawn_weak(|this, cx| async move {
3296 let responses = futures::future::join_all(requests).await;
3297 let this = if let Some(this) = this.upgrade(&cx) {
3298 this
3299 } else {
3300 return Ok(Default::default());
3301 };
3302 let symbols = this.read_with(&cx, |this, cx| {
3303 let mut symbols = Vec::new();
3304 for (
3305 adapter,
3306 adapter_language,
3307 source_worktree_id,
3308 worktree_abs_path,
3309 response,
3310 ) in responses
3311 {
3312 symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3313 let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3314 let mut worktree_id = source_worktree_id;
3315 let path;
3316 if let Some((worktree, rel_path)) =
3317 this.find_local_worktree(&abs_path, cx)
3318 {
3319 worktree_id = worktree.read(cx).id();
3320 path = rel_path;
3321 } else {
3322 path = relativize_path(&worktree_abs_path, &abs_path);
3323 }
3324
3325 let project_path = ProjectPath {
3326 worktree_id,
3327 path: path.into(),
3328 };
3329 let signature = this.symbol_signature(&project_path);
3330 let adapter_language = adapter_language.clone();
3331 let language = this
3332 .languages
3333 .language_for_path(&project_path.path)
3334 .unwrap_or_else(move |_| adapter_language);
3335 let language_server_name = adapter.name.clone();
3336 Some(async move {
3337 let language = language.await;
3338 let label = language
3339 .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3340 .await;
3341
3342 Symbol {
3343 language_server_name,
3344 source_worktree_id,
3345 path: project_path,
3346 label: label.unwrap_or_else(|| {
3347 CodeLabel::plain(lsp_symbol.name.clone(), None)
3348 }),
3349 kind: lsp_symbol.kind,
3350 name: lsp_symbol.name,
3351 range: range_from_lsp(lsp_symbol.location.range),
3352 signature,
3353 }
3354 })
3355 }));
3356 }
3357 symbols
3358 });
3359 Ok(futures::future::join_all(symbols).await)
3360 })
3361 } else if let Some(project_id) = self.remote_id() {
3362 let request = self.client.request(proto::GetProjectSymbols {
3363 project_id,
3364 query: query.to_string(),
3365 });
3366 cx.spawn_weak(|this, cx| async move {
3367 let response = request.await?;
3368 let mut symbols = Vec::new();
3369 if let Some(this) = this.upgrade(&cx) {
3370 let new_symbols = this.read_with(&cx, |this, _| {
3371 response
3372 .symbols
3373 .into_iter()
3374 .map(|symbol| this.deserialize_symbol(symbol))
3375 .collect::<Vec<_>>()
3376 });
3377 symbols = futures::future::join_all(new_symbols)
3378 .await
3379 .into_iter()
3380 .filter_map(|symbol| symbol.log_err())
3381 .collect::<Vec<_>>();
3382 }
3383 Ok(symbols)
3384 })
3385 } else {
3386 Task::ready(Ok(Default::default()))
3387 }
3388 }
3389
3390 pub fn open_buffer_for_symbol(
3391 &mut self,
3392 symbol: &Symbol,
3393 cx: &mut ModelContext<Self>,
3394 ) -> Task<Result<ModelHandle<Buffer>>> {
3395 if self.is_local() {
3396 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3397 symbol.source_worktree_id,
3398 symbol.language_server_name.clone(),
3399 )) {
3400 *id
3401 } else {
3402 return Task::ready(Err(anyhow!(
3403 "language server for worktree and language not found"
3404 )));
3405 };
3406
3407 let worktree_abs_path = if let Some(worktree_abs_path) = self
3408 .worktree_for_id(symbol.path.worktree_id, cx)
3409 .and_then(|worktree| worktree.read(cx).as_local())
3410 .map(|local_worktree| local_worktree.abs_path())
3411 {
3412 worktree_abs_path
3413 } else {
3414 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3415 };
3416 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3417 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3418 uri
3419 } else {
3420 return Task::ready(Err(anyhow!("invalid symbol path")));
3421 };
3422
3423 self.open_local_buffer_via_lsp(
3424 symbol_uri,
3425 language_server_id,
3426 symbol.language_server_name.clone(),
3427 cx,
3428 )
3429 } else if let Some(project_id) = self.remote_id() {
3430 let request = self.client.request(proto::OpenBufferForSymbol {
3431 project_id,
3432 symbol: Some(serialize_symbol(symbol)),
3433 });
3434 cx.spawn(|this, mut cx| async move {
3435 let response = request.await?;
3436 this.update(&mut cx, |this, cx| {
3437 this.wait_for_remote_buffer(response.buffer_id, cx)
3438 })
3439 .await
3440 })
3441 } else {
3442 Task::ready(Err(anyhow!("project does not have a remote id")))
3443 }
3444 }
3445
3446 pub fn hover<T: ToPointUtf16>(
3447 &self,
3448 buffer: &ModelHandle<Buffer>,
3449 position: T,
3450 cx: &mut ModelContext<Self>,
3451 ) -> Task<Result<Option<Hover>>> {
3452 let position = position.to_point_utf16(buffer.read(cx));
3453 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3454 }
3455
3456 pub fn completions<T: ToPointUtf16>(
3457 &self,
3458 source_buffer_handle: &ModelHandle<Buffer>,
3459 position: T,
3460 cx: &mut ModelContext<Self>,
3461 ) -> Task<Result<Vec<Completion>>> {
3462 let source_buffer_handle = source_buffer_handle.clone();
3463 let source_buffer = source_buffer_handle.read(cx);
3464 let buffer_id = source_buffer.remote_id();
3465 let language = source_buffer.language().cloned();
3466 let worktree;
3467 let buffer_abs_path;
3468 if let Some(file) = File::from_dyn(source_buffer.file()) {
3469 worktree = file.worktree.clone();
3470 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3471 } else {
3472 return Task::ready(Ok(Default::default()));
3473 };
3474
3475 let position = Unclipped(position.to_point_utf16(source_buffer));
3476 let anchor = source_buffer.anchor_after(position);
3477
3478 if worktree.read(cx).as_local().is_some() {
3479 let buffer_abs_path = buffer_abs_path.unwrap();
3480 let lang_server =
3481 if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3482 server.clone()
3483 } else {
3484 return Task::ready(Ok(Default::default()));
3485 };
3486
3487 cx.spawn(|_, cx| async move {
3488 let completions = lang_server
3489 .request::<lsp::request::Completion>(lsp::CompletionParams {
3490 text_document_position: lsp::TextDocumentPositionParams::new(
3491 lsp::TextDocumentIdentifier::new(
3492 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3493 ),
3494 point_to_lsp(position.0),
3495 ),
3496 context: Default::default(),
3497 work_done_progress_params: Default::default(),
3498 partial_result_params: Default::default(),
3499 })
3500 .await
3501 .context("lsp completion request failed")?;
3502
3503 let completions = if let Some(completions) = completions {
3504 match completions {
3505 lsp::CompletionResponse::Array(completions) => completions,
3506 lsp::CompletionResponse::List(list) => list.items,
3507 }
3508 } else {
3509 Default::default()
3510 };
3511
3512 let completions = source_buffer_handle.read_with(&cx, |this, _| {
3513 let snapshot = this.snapshot();
3514 let clipped_position = this.clip_point_utf16(position, Bias::Left);
3515 let mut range_for_token = None;
3516 completions
3517 .into_iter()
3518 .filter_map(move |mut lsp_completion| {
3519 // For now, we can only handle additional edits if they are returned
3520 // when resolving the completion, not if they are present initially.
3521 if lsp_completion
3522 .additional_text_edits
3523 .as_ref()
3524 .map_or(false, |edits| !edits.is_empty())
3525 {
3526 return None;
3527 }
3528
3529 let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref()
3530 {
3531 // If the language server provides a range to overwrite, then
3532 // check that the range is valid.
3533 Some(lsp::CompletionTextEdit::Edit(edit)) => {
3534 let range = range_from_lsp(edit.range);
3535 let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3536 let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3537 if start != range.start.0 || end != range.end.0 {
3538 log::info!("completion out of expected range");
3539 return None;
3540 }
3541 (
3542 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3543 edit.new_text.clone(),
3544 )
3545 }
3546 // If the language server does not provide a range, then infer
3547 // the range based on the syntax tree.
3548 None => {
3549 if position.0 != clipped_position {
3550 log::info!("completion out of expected range");
3551 return None;
3552 }
3553 let Range { start, end } = range_for_token
3554 .get_or_insert_with(|| {
3555 let offset = position.to_offset(&snapshot);
3556 let (range, kind) = snapshot.surrounding_word(offset);
3557 if kind == Some(CharKind::Word) {
3558 range
3559 } else {
3560 offset..offset
3561 }
3562 })
3563 .clone();
3564 let text = lsp_completion
3565 .insert_text
3566 .as_ref()
3567 .unwrap_or(&lsp_completion.label)
3568 .clone();
3569 (
3570 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3571 text,
3572 )
3573 }
3574 Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3575 log::info!("unsupported insert/replace completion");
3576 return None;
3577 }
3578 };
3579
3580 LineEnding::normalize(&mut new_text);
3581 let language = language.clone();
3582 Some(async move {
3583 let mut label = None;
3584 if let Some(language) = language {
3585 language.process_completion(&mut lsp_completion).await;
3586 label = language.label_for_completion(&lsp_completion).await;
3587 }
3588 Completion {
3589 old_range,
3590 new_text,
3591 label: label.unwrap_or_else(|| {
3592 CodeLabel::plain(
3593 lsp_completion.label.clone(),
3594 lsp_completion.filter_text.as_deref(),
3595 )
3596 }),
3597 lsp_completion,
3598 }
3599 })
3600 })
3601 });
3602
3603 Ok(futures::future::join_all(completions).await)
3604 })
3605 } else if let Some(project_id) = self.remote_id() {
3606 let rpc = self.client.clone();
3607 let message = proto::GetCompletions {
3608 project_id,
3609 buffer_id,
3610 position: Some(language::proto::serialize_anchor(&anchor)),
3611 version: serialize_version(&source_buffer.version()),
3612 };
3613 cx.spawn_weak(|this, mut cx| async move {
3614 let response = rpc.request(message).await?;
3615
3616 if this
3617 .upgrade(&cx)
3618 .ok_or_else(|| anyhow!("project was dropped"))?
3619 .read_with(&cx, |this, _| this.is_read_only())
3620 {
3621 return Err(anyhow!(
3622 "failed to get completions: project was disconnected"
3623 ));
3624 } else {
3625 source_buffer_handle
3626 .update(&mut cx, |buffer, _| {
3627 buffer.wait_for_version(deserialize_version(response.version))
3628 })
3629 .await;
3630
3631 let completions = response.completions.into_iter().map(|completion| {
3632 language::proto::deserialize_completion(completion, language.clone())
3633 });
3634 futures::future::try_join_all(completions).await
3635 }
3636 })
3637 } else {
3638 Task::ready(Ok(Default::default()))
3639 }
3640 }
3641
3642 pub fn apply_additional_edits_for_completion(
3643 &self,
3644 buffer_handle: ModelHandle<Buffer>,
3645 completion: Completion,
3646 push_to_history: bool,
3647 cx: &mut ModelContext<Self>,
3648 ) -> Task<Result<Option<Transaction>>> {
3649 let buffer = buffer_handle.read(cx);
3650 let buffer_id = buffer.remote_id();
3651
3652 if self.is_local() {
3653 let lang_server = match self.language_server_for_buffer(buffer, cx) {
3654 Some((_, server)) => server.clone(),
3655 _ => return Task::ready(Ok(Default::default())),
3656 };
3657
3658 cx.spawn(|this, mut cx| async move {
3659 let resolved_completion = lang_server
3660 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3661 .await?;
3662
3663 if let Some(edits) = resolved_completion.additional_text_edits {
3664 let edits = this
3665 .update(&mut cx, |this, cx| {
3666 this.edits_from_lsp(&buffer_handle, edits, None, cx)
3667 })
3668 .await?;
3669
3670 buffer_handle.update(&mut cx, |buffer, cx| {
3671 buffer.finalize_last_transaction();
3672 buffer.start_transaction();
3673
3674 for (range, text) in edits {
3675 let primary = &completion.old_range;
3676 let start_within = primary.start.cmp(&range.start, buffer).is_le()
3677 && primary.end.cmp(&range.start, buffer).is_ge();
3678 let end_within = range.start.cmp(&primary.end, buffer).is_le()
3679 && range.end.cmp(&primary.end, buffer).is_ge();
3680
3681 //Skip addtional edits which overlap with the primary completion edit
3682 //https://github.com/zed-industries/zed/pull/1871
3683 if !start_within && !end_within {
3684 buffer.edit([(range, text)], None, cx);
3685 }
3686 }
3687
3688 let transaction = if buffer.end_transaction(cx).is_some() {
3689 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3690 if !push_to_history {
3691 buffer.forget_transaction(transaction.id);
3692 }
3693 Some(transaction)
3694 } else {
3695 None
3696 };
3697 Ok(transaction)
3698 })
3699 } else {
3700 Ok(None)
3701 }
3702 })
3703 } else if let Some(project_id) = self.remote_id() {
3704 let client = self.client.clone();
3705 cx.spawn(|_, mut cx| async move {
3706 let response = client
3707 .request(proto::ApplyCompletionAdditionalEdits {
3708 project_id,
3709 buffer_id,
3710 completion: Some(language::proto::serialize_completion(&completion)),
3711 })
3712 .await?;
3713
3714 if let Some(transaction) = response.transaction {
3715 let transaction = language::proto::deserialize_transaction(transaction)?;
3716 buffer_handle
3717 .update(&mut cx, |buffer, _| {
3718 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3719 })
3720 .await;
3721 if push_to_history {
3722 buffer_handle.update(&mut cx, |buffer, _| {
3723 buffer.push_transaction(transaction.clone(), Instant::now());
3724 });
3725 }
3726 Ok(Some(transaction))
3727 } else {
3728 Ok(None)
3729 }
3730 })
3731 } else {
3732 Task::ready(Err(anyhow!("project does not have a remote id")))
3733 }
3734 }
3735
3736 pub fn code_actions<T: Clone + ToOffset>(
3737 &self,
3738 buffer_handle: &ModelHandle<Buffer>,
3739 range: Range<T>,
3740 cx: &mut ModelContext<Self>,
3741 ) -> Task<Result<Vec<CodeAction>>> {
3742 let buffer_handle = buffer_handle.clone();
3743 let buffer = buffer_handle.read(cx);
3744 let snapshot = buffer.snapshot();
3745 let relevant_diagnostics = snapshot
3746 .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3747 .map(|entry| entry.to_lsp_diagnostic_stub())
3748 .collect();
3749 let buffer_id = buffer.remote_id();
3750 let worktree;
3751 let buffer_abs_path;
3752 if let Some(file) = File::from_dyn(buffer.file()) {
3753 worktree = file.worktree.clone();
3754 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3755 } else {
3756 return Task::ready(Ok(Vec::new()));
3757 };
3758 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3759
3760 if worktree.read(cx).as_local().is_some() {
3761 let buffer_abs_path = buffer_abs_path.unwrap();
3762 let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3763 {
3764 server.clone()
3765 } else {
3766 return Task::ready(Ok(Vec::new()));
3767 };
3768
3769 let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3770 cx.foreground().spawn(async move {
3771 if lang_server.capabilities().code_action_provider.is_none() {
3772 return Ok(Vec::new());
3773 }
3774
3775 Ok(lang_server
3776 .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3777 text_document: lsp::TextDocumentIdentifier::new(
3778 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3779 ),
3780 range: lsp_range,
3781 work_done_progress_params: Default::default(),
3782 partial_result_params: Default::default(),
3783 context: lsp::CodeActionContext {
3784 diagnostics: relevant_diagnostics,
3785 only: lang_server.code_action_kinds(),
3786 },
3787 })
3788 .await?
3789 .unwrap_or_default()
3790 .into_iter()
3791 .filter_map(|entry| {
3792 if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3793 Some(CodeAction {
3794 range: range.clone(),
3795 lsp_action,
3796 })
3797 } else {
3798 None
3799 }
3800 })
3801 .collect())
3802 })
3803 } else if let Some(project_id) = self.remote_id() {
3804 let rpc = self.client.clone();
3805 let version = buffer.version();
3806 cx.spawn_weak(|this, mut cx| async move {
3807 let response = rpc
3808 .request(proto::GetCodeActions {
3809 project_id,
3810 buffer_id,
3811 start: Some(language::proto::serialize_anchor(&range.start)),
3812 end: Some(language::proto::serialize_anchor(&range.end)),
3813 version: serialize_version(&version),
3814 })
3815 .await?;
3816
3817 if this
3818 .upgrade(&cx)
3819 .ok_or_else(|| anyhow!("project was dropped"))?
3820 .read_with(&cx, |this, _| this.is_read_only())
3821 {
3822 return Err(anyhow!(
3823 "failed to get code actions: project was disconnected"
3824 ));
3825 } else {
3826 buffer_handle
3827 .update(&mut cx, |buffer, _| {
3828 buffer.wait_for_version(deserialize_version(response.version))
3829 })
3830 .await;
3831
3832 response
3833 .actions
3834 .into_iter()
3835 .map(language::proto::deserialize_code_action)
3836 .collect()
3837 }
3838 })
3839 } else {
3840 Task::ready(Ok(Default::default()))
3841 }
3842 }
3843
3844 pub fn apply_code_action(
3845 &self,
3846 buffer_handle: ModelHandle<Buffer>,
3847 mut action: CodeAction,
3848 push_to_history: bool,
3849 cx: &mut ModelContext<Self>,
3850 ) -> Task<Result<ProjectTransaction>> {
3851 if self.is_local() {
3852 let buffer = buffer_handle.read(cx);
3853 let (lsp_adapter, lang_server) =
3854 if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3855 (adapter.clone(), server.clone())
3856 } else {
3857 return Task::ready(Ok(Default::default()));
3858 };
3859 let range = action.range.to_point_utf16(buffer);
3860
3861 cx.spawn(|this, mut cx| async move {
3862 if let Some(lsp_range) = action
3863 .lsp_action
3864 .data
3865 .as_mut()
3866 .and_then(|d| d.get_mut("codeActionParams"))
3867 .and_then(|d| d.get_mut("range"))
3868 {
3869 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3870 action.lsp_action = lang_server
3871 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3872 .await?;
3873 } else {
3874 let actions = this
3875 .update(&mut cx, |this, cx| {
3876 this.code_actions(&buffer_handle, action.range, cx)
3877 })
3878 .await?;
3879 action.lsp_action = actions
3880 .into_iter()
3881 .find(|a| a.lsp_action.title == action.lsp_action.title)
3882 .ok_or_else(|| anyhow!("code action is outdated"))?
3883 .lsp_action;
3884 }
3885
3886 if let Some(edit) = action.lsp_action.edit {
3887 if edit.changes.is_some() || edit.document_changes.is_some() {
3888 return Self::deserialize_workspace_edit(
3889 this,
3890 edit,
3891 push_to_history,
3892 lsp_adapter.clone(),
3893 lang_server.clone(),
3894 &mut cx,
3895 )
3896 .await;
3897 }
3898 }
3899
3900 if let Some(command) = action.lsp_action.command {
3901 this.update(&mut cx, |this, _| {
3902 this.last_workspace_edits_by_language_server
3903 .remove(&lang_server.server_id());
3904 });
3905 lang_server
3906 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3907 command: command.command,
3908 arguments: command.arguments.unwrap_or_default(),
3909 ..Default::default()
3910 })
3911 .await?;
3912 return Ok(this.update(&mut cx, |this, _| {
3913 this.last_workspace_edits_by_language_server
3914 .remove(&lang_server.server_id())
3915 .unwrap_or_default()
3916 }));
3917 }
3918
3919 Ok(ProjectTransaction::default())
3920 })
3921 } else if let Some(project_id) = self.remote_id() {
3922 let client = self.client.clone();
3923 let request = proto::ApplyCodeAction {
3924 project_id,
3925 buffer_id: buffer_handle.read(cx).remote_id(),
3926 action: Some(language::proto::serialize_code_action(&action)),
3927 };
3928 cx.spawn(|this, mut cx| async move {
3929 let response = client
3930 .request(request)
3931 .await?
3932 .transaction
3933 .ok_or_else(|| anyhow!("missing transaction"))?;
3934 this.update(&mut cx, |this, cx| {
3935 this.deserialize_project_transaction(response, push_to_history, cx)
3936 })
3937 .await
3938 })
3939 } else {
3940 Task::ready(Err(anyhow!("project does not have a remote id")))
3941 }
3942 }
3943
3944 async fn deserialize_workspace_edit(
3945 this: ModelHandle<Self>,
3946 edit: lsp::WorkspaceEdit,
3947 push_to_history: bool,
3948 lsp_adapter: Arc<CachedLspAdapter>,
3949 language_server: Arc<LanguageServer>,
3950 cx: &mut AsyncAppContext,
3951 ) -> Result<ProjectTransaction> {
3952 let fs = this.read_with(cx, |this, _| this.fs.clone());
3953 let mut operations = Vec::new();
3954 if let Some(document_changes) = edit.document_changes {
3955 match document_changes {
3956 lsp::DocumentChanges::Edits(edits) => {
3957 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3958 }
3959 lsp::DocumentChanges::Operations(ops) => operations = ops,
3960 }
3961 } else if let Some(changes) = edit.changes {
3962 operations.extend(changes.into_iter().map(|(uri, edits)| {
3963 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3964 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3965 uri,
3966 version: None,
3967 },
3968 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3969 })
3970 }));
3971 }
3972
3973 let mut project_transaction = ProjectTransaction::default();
3974 for operation in operations {
3975 match operation {
3976 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3977 let abs_path = op
3978 .uri
3979 .to_file_path()
3980 .map_err(|_| anyhow!("can't convert URI to path"))?;
3981
3982 if let Some(parent_path) = abs_path.parent() {
3983 fs.create_dir(parent_path).await?;
3984 }
3985 if abs_path.ends_with("/") {
3986 fs.create_dir(&abs_path).await?;
3987 } else {
3988 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3989 .await?;
3990 }
3991 }
3992 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3993 let source_abs_path = op
3994 .old_uri
3995 .to_file_path()
3996 .map_err(|_| anyhow!("can't convert URI to path"))?;
3997 let target_abs_path = op
3998 .new_uri
3999 .to_file_path()
4000 .map_err(|_| anyhow!("can't convert URI to path"))?;
4001 fs.rename(
4002 &source_abs_path,
4003 &target_abs_path,
4004 op.options.map(Into::into).unwrap_or_default(),
4005 )
4006 .await?;
4007 }
4008 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4009 let abs_path = op
4010 .uri
4011 .to_file_path()
4012 .map_err(|_| anyhow!("can't convert URI to path"))?;
4013 let options = op.options.map(Into::into).unwrap_or_default();
4014 if abs_path.ends_with("/") {
4015 fs.remove_dir(&abs_path, options).await?;
4016 } else {
4017 fs.remove_file(&abs_path, options).await?;
4018 }
4019 }
4020 lsp::DocumentChangeOperation::Edit(op) => {
4021 let buffer_to_edit = this
4022 .update(cx, |this, cx| {
4023 this.open_local_buffer_via_lsp(
4024 op.text_document.uri,
4025 language_server.server_id(),
4026 lsp_adapter.name.clone(),
4027 cx,
4028 )
4029 })
4030 .await?;
4031
4032 let edits = this
4033 .update(cx, |this, cx| {
4034 let edits = op.edits.into_iter().map(|edit| match edit {
4035 lsp::OneOf::Left(edit) => edit,
4036 lsp::OneOf::Right(edit) => edit.text_edit,
4037 });
4038 this.edits_from_lsp(
4039 &buffer_to_edit,
4040 edits,
4041 op.text_document.version,
4042 cx,
4043 )
4044 })
4045 .await?;
4046
4047 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4048 buffer.finalize_last_transaction();
4049 buffer.start_transaction();
4050 for (range, text) in edits {
4051 buffer.edit([(range, text)], None, cx);
4052 }
4053 let transaction = if buffer.end_transaction(cx).is_some() {
4054 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4055 if !push_to_history {
4056 buffer.forget_transaction(transaction.id);
4057 }
4058 Some(transaction)
4059 } else {
4060 None
4061 };
4062
4063 transaction
4064 });
4065 if let Some(transaction) = transaction {
4066 project_transaction.0.insert(buffer_to_edit, transaction);
4067 }
4068 }
4069 }
4070 }
4071
4072 Ok(project_transaction)
4073 }
4074
4075 pub fn prepare_rename<T: ToPointUtf16>(
4076 &self,
4077 buffer: ModelHandle<Buffer>,
4078 position: T,
4079 cx: &mut ModelContext<Self>,
4080 ) -> Task<Result<Option<Range<Anchor>>>> {
4081 let position = position.to_point_utf16(buffer.read(cx));
4082 self.request_lsp(buffer, PrepareRename { position }, cx)
4083 }
4084
4085 pub fn perform_rename<T: ToPointUtf16>(
4086 &self,
4087 buffer: ModelHandle<Buffer>,
4088 position: T,
4089 new_name: String,
4090 push_to_history: bool,
4091 cx: &mut ModelContext<Self>,
4092 ) -> Task<Result<ProjectTransaction>> {
4093 let position = position.to_point_utf16(buffer.read(cx));
4094 self.request_lsp(
4095 buffer,
4096 PerformRename {
4097 position,
4098 new_name,
4099 push_to_history,
4100 },
4101 cx,
4102 )
4103 }
4104
4105 #[allow(clippy::type_complexity)]
4106 pub fn search(
4107 &self,
4108 query: SearchQuery,
4109 cx: &mut ModelContext<Self>,
4110 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4111 if self.is_local() {
4112 let snapshots = self
4113 .visible_worktrees(cx)
4114 .filter_map(|tree| {
4115 let tree = tree.read(cx).as_local()?;
4116 Some(tree.snapshot())
4117 })
4118 .collect::<Vec<_>>();
4119
4120 let background = cx.background().clone();
4121 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4122 if path_count == 0 {
4123 return Task::ready(Ok(Default::default()));
4124 }
4125 let workers = background.num_cpus().min(path_count);
4126 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4127 cx.background()
4128 .spawn({
4129 let fs = self.fs.clone();
4130 let background = cx.background().clone();
4131 let query = query.clone();
4132 async move {
4133 let fs = &fs;
4134 let query = &query;
4135 let matching_paths_tx = &matching_paths_tx;
4136 let paths_per_worker = (path_count + workers - 1) / workers;
4137 let snapshots = &snapshots;
4138 background
4139 .scoped(|scope| {
4140 for worker_ix in 0..workers {
4141 let worker_start_ix = worker_ix * paths_per_worker;
4142 let worker_end_ix = worker_start_ix + paths_per_worker;
4143 scope.spawn(async move {
4144 let mut snapshot_start_ix = 0;
4145 let mut abs_path = PathBuf::new();
4146 for snapshot in snapshots {
4147 let snapshot_end_ix =
4148 snapshot_start_ix + snapshot.visible_file_count();
4149 if worker_end_ix <= snapshot_start_ix {
4150 break;
4151 } else if worker_start_ix > snapshot_end_ix {
4152 snapshot_start_ix = snapshot_end_ix;
4153 continue;
4154 } else {
4155 let start_in_snapshot = worker_start_ix
4156 .saturating_sub(snapshot_start_ix);
4157 let end_in_snapshot =
4158 cmp::min(worker_end_ix, snapshot_end_ix)
4159 - snapshot_start_ix;
4160
4161 for entry in snapshot
4162 .files(false, start_in_snapshot)
4163 .take(end_in_snapshot - start_in_snapshot)
4164 {
4165 if matching_paths_tx.is_closed() {
4166 break;
4167 }
4168
4169 abs_path.clear();
4170 abs_path.push(&snapshot.abs_path());
4171 abs_path.push(&entry.path);
4172 let matches = if let Some(file) =
4173 fs.open_sync(&abs_path).await.log_err()
4174 {
4175 query.detect(file).unwrap_or(false)
4176 } else {
4177 false
4178 };
4179
4180 if matches {
4181 let project_path =
4182 (snapshot.id(), entry.path.clone());
4183 if matching_paths_tx
4184 .send(project_path)
4185 .await
4186 .is_err()
4187 {
4188 break;
4189 }
4190 }
4191 }
4192
4193 snapshot_start_ix = snapshot_end_ix;
4194 }
4195 }
4196 });
4197 }
4198 })
4199 .await;
4200 }
4201 })
4202 .detach();
4203
4204 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4205 let open_buffers = self
4206 .opened_buffers
4207 .values()
4208 .filter_map(|b| b.upgrade(cx))
4209 .collect::<HashSet<_>>();
4210 cx.spawn(|this, cx| async move {
4211 for buffer in &open_buffers {
4212 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4213 buffers_tx.send((buffer.clone(), snapshot)).await?;
4214 }
4215
4216 let open_buffers = Rc::new(RefCell::new(open_buffers));
4217 while let Some(project_path) = matching_paths_rx.next().await {
4218 if buffers_tx.is_closed() {
4219 break;
4220 }
4221
4222 let this = this.clone();
4223 let open_buffers = open_buffers.clone();
4224 let buffers_tx = buffers_tx.clone();
4225 cx.spawn(|mut cx| async move {
4226 if let Some(buffer) = this
4227 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4228 .await
4229 .log_err()
4230 {
4231 if open_buffers.borrow_mut().insert(buffer.clone()) {
4232 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4233 buffers_tx.send((buffer, snapshot)).await?;
4234 }
4235 }
4236
4237 Ok::<_, anyhow::Error>(())
4238 })
4239 .detach();
4240 }
4241
4242 Ok::<_, anyhow::Error>(())
4243 })
4244 .detach_and_log_err(cx);
4245
4246 let background = cx.background().clone();
4247 cx.background().spawn(async move {
4248 let query = &query;
4249 let mut matched_buffers = Vec::new();
4250 for _ in 0..workers {
4251 matched_buffers.push(HashMap::default());
4252 }
4253 background
4254 .scoped(|scope| {
4255 for worker_matched_buffers in matched_buffers.iter_mut() {
4256 let mut buffers_rx = buffers_rx.clone();
4257 scope.spawn(async move {
4258 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4259 let buffer_matches = query
4260 .search(snapshot.as_rope())
4261 .await
4262 .iter()
4263 .map(|range| {
4264 snapshot.anchor_before(range.start)
4265 ..snapshot.anchor_after(range.end)
4266 })
4267 .collect::<Vec<_>>();
4268 if !buffer_matches.is_empty() {
4269 worker_matched_buffers
4270 .insert(buffer.clone(), buffer_matches);
4271 }
4272 }
4273 });
4274 }
4275 })
4276 .await;
4277 Ok(matched_buffers.into_iter().flatten().collect())
4278 })
4279 } else if let Some(project_id) = self.remote_id() {
4280 let request = self.client.request(query.to_proto(project_id));
4281 cx.spawn(|this, mut cx| async move {
4282 let response = request.await?;
4283 let mut result = HashMap::default();
4284 for location in response.locations {
4285 let target_buffer = this
4286 .update(&mut cx, |this, cx| {
4287 this.wait_for_remote_buffer(location.buffer_id, cx)
4288 })
4289 .await?;
4290 let start = location
4291 .start
4292 .and_then(deserialize_anchor)
4293 .ok_or_else(|| anyhow!("missing target start"))?;
4294 let end = location
4295 .end
4296 .and_then(deserialize_anchor)
4297 .ok_or_else(|| anyhow!("missing target end"))?;
4298 result
4299 .entry(target_buffer)
4300 .or_insert(Vec::new())
4301 .push(start..end)
4302 }
4303 Ok(result)
4304 })
4305 } else {
4306 Task::ready(Ok(Default::default()))
4307 }
4308 }
4309
4310 fn request_lsp<R: LspCommand>(
4311 &self,
4312 buffer_handle: ModelHandle<Buffer>,
4313 request: R,
4314 cx: &mut ModelContext<Self>,
4315 ) -> Task<Result<R::Response>>
4316 where
4317 <R::LspRequest as lsp::request::Request>::Result: Send,
4318 {
4319 let buffer = buffer_handle.read(cx);
4320 if self.is_local() {
4321 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4322 if let Some((file, language_server)) = file.zip(
4323 self.language_server_for_buffer(buffer, cx)
4324 .map(|(_, server)| server.clone()),
4325 ) {
4326 let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4327 return cx.spawn(|this, cx| async move {
4328 if !request.check_capabilities(language_server.capabilities()) {
4329 return Ok(Default::default());
4330 }
4331
4332 let response = language_server
4333 .request::<R::LspRequest>(lsp_params)
4334 .await
4335 .context("lsp request failed")?;
4336 request
4337 .response_from_lsp(response, this, buffer_handle, cx)
4338 .await
4339 });
4340 }
4341 } else if let Some(project_id) = self.remote_id() {
4342 let rpc = self.client.clone();
4343 let message = request.to_proto(project_id, buffer);
4344 return cx.spawn_weak(|this, cx| async move {
4345 let response = rpc.request(message).await?;
4346 let this = this
4347 .upgrade(&cx)
4348 .ok_or_else(|| anyhow!("project dropped"))?;
4349 if this.read_with(&cx, |this, _| this.is_read_only()) {
4350 Err(anyhow!("disconnected before completing request"))
4351 } else {
4352 request
4353 .response_from_proto(response, this, buffer_handle, cx)
4354 .await
4355 }
4356 });
4357 }
4358 Task::ready(Ok(Default::default()))
4359 }
4360
4361 pub fn find_or_create_local_worktree(
4362 &mut self,
4363 abs_path: impl AsRef<Path>,
4364 visible: bool,
4365 cx: &mut ModelContext<Self>,
4366 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4367 let abs_path = abs_path.as_ref();
4368 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4369 Task::ready(Ok((tree, relative_path)))
4370 } else {
4371 let worktree = self.create_local_worktree(abs_path, visible, cx);
4372 cx.foreground()
4373 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4374 }
4375 }
4376
4377 pub fn find_local_worktree(
4378 &self,
4379 abs_path: &Path,
4380 cx: &AppContext,
4381 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4382 for tree in &self.worktrees {
4383 if let Some(tree) = tree.upgrade(cx) {
4384 if let Some(relative_path) = tree
4385 .read(cx)
4386 .as_local()
4387 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4388 {
4389 return Some((tree.clone(), relative_path.into()));
4390 }
4391 }
4392 }
4393 None
4394 }
4395
4396 pub fn is_shared(&self) -> bool {
4397 match &self.client_state {
4398 Some(ProjectClientState::Local { .. }) => true,
4399 _ => false,
4400 }
4401 }
4402
4403 fn create_local_worktree(
4404 &mut self,
4405 abs_path: impl AsRef<Path>,
4406 visible: bool,
4407 cx: &mut ModelContext<Self>,
4408 ) -> Task<Result<ModelHandle<Worktree>>> {
4409 let fs = self.fs.clone();
4410 let client = self.client.clone();
4411 let next_entry_id = self.next_entry_id.clone();
4412 let path: Arc<Path> = abs_path.as_ref().into();
4413 let task = self
4414 .loading_local_worktrees
4415 .entry(path.clone())
4416 .or_insert_with(|| {
4417 cx.spawn(|project, mut cx| {
4418 async move {
4419 let worktree = Worktree::local(
4420 client.clone(),
4421 path.clone(),
4422 visible,
4423 fs,
4424 next_entry_id,
4425 &mut cx,
4426 )
4427 .await;
4428 project.update(&mut cx, |project, _| {
4429 project.loading_local_worktrees.remove(&path);
4430 });
4431 let worktree = worktree?;
4432
4433 project
4434 .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))
4435 .await;
4436
4437 Ok(worktree)
4438 }
4439 .map_err(Arc::new)
4440 })
4441 .shared()
4442 })
4443 .clone();
4444 cx.foreground().spawn(async move {
4445 match task.await {
4446 Ok(worktree) => Ok(worktree),
4447 Err(err) => Err(anyhow!("{}", err)),
4448 }
4449 })
4450 }
4451
4452 pub fn remove_worktree(
4453 &mut self,
4454 id_to_remove: WorktreeId,
4455 cx: &mut ModelContext<Self>,
4456 ) -> impl Future<Output = ()> {
4457 self.worktrees.retain(|worktree| {
4458 if let Some(worktree) = worktree.upgrade(cx) {
4459 let id = worktree.read(cx).id();
4460 if id == id_to_remove {
4461 cx.emit(Event::WorktreeRemoved(id));
4462 false
4463 } else {
4464 true
4465 }
4466 } else {
4467 false
4468 }
4469 });
4470 self.metadata_changed(cx)
4471 }
4472
4473 fn add_worktree(
4474 &mut self,
4475 worktree: &ModelHandle<Worktree>,
4476 cx: &mut ModelContext<Self>,
4477 ) -> impl Future<Output = ()> {
4478 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4479 if worktree.read(cx).is_local() {
4480 cx.subscribe(worktree, |this, worktree, event, cx| match event {
4481 worktree::Event::UpdatedEntries(changes) => {
4482 this.update_local_worktree_buffers(&worktree, cx);
4483 this.update_local_worktree_language_servers(&worktree, changes, cx);
4484 }
4485 worktree::Event::UpdatedGitRepositories(updated_repos) => {
4486 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4487 }
4488 })
4489 .detach();
4490 }
4491
4492 let push_strong_handle = {
4493 let worktree = worktree.read(cx);
4494 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4495 };
4496 if push_strong_handle {
4497 self.worktrees
4498 .push(WorktreeHandle::Strong(worktree.clone()));
4499 } else {
4500 self.worktrees
4501 .push(WorktreeHandle::Weak(worktree.downgrade()));
4502 }
4503
4504 cx.observe_release(worktree, |this, worktree, cx| {
4505 let _ = this.remove_worktree(worktree.id(), cx);
4506 })
4507 .detach();
4508
4509 cx.emit(Event::WorktreeAdded);
4510 self.metadata_changed(cx)
4511 }
4512
4513 fn update_local_worktree_buffers(
4514 &mut self,
4515 worktree_handle: &ModelHandle<Worktree>,
4516 cx: &mut ModelContext<Self>,
4517 ) {
4518 let snapshot = worktree_handle.read(cx).snapshot();
4519 let mut buffers_to_delete = Vec::new();
4520 let mut renamed_buffers = Vec::new();
4521 for (buffer_id, buffer) in &self.opened_buffers {
4522 if let Some(buffer) = buffer.upgrade(cx) {
4523 buffer.update(cx, |buffer, cx| {
4524 if let Some(old_file) = File::from_dyn(buffer.file()) {
4525 if old_file.worktree != *worktree_handle {
4526 return;
4527 }
4528
4529 let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id)
4530 {
4531 File {
4532 is_local: true,
4533 entry_id: entry.id,
4534 mtime: entry.mtime,
4535 path: entry.path.clone(),
4536 worktree: worktree_handle.clone(),
4537 is_deleted: false,
4538 }
4539 } else if let Some(entry) =
4540 snapshot.entry_for_path(old_file.path().as_ref())
4541 {
4542 File {
4543 is_local: true,
4544 entry_id: entry.id,
4545 mtime: entry.mtime,
4546 path: entry.path.clone(),
4547 worktree: worktree_handle.clone(),
4548 is_deleted: false,
4549 }
4550 } else {
4551 File {
4552 is_local: true,
4553 entry_id: old_file.entry_id,
4554 path: old_file.path().clone(),
4555 mtime: old_file.mtime(),
4556 worktree: worktree_handle.clone(),
4557 is_deleted: true,
4558 }
4559 };
4560
4561 let old_path = old_file.abs_path(cx);
4562 if new_file.abs_path(cx) != old_path {
4563 renamed_buffers.push((cx.handle(), old_path));
4564 }
4565
4566 if new_file != *old_file {
4567 if let Some(project_id) = self.remote_id() {
4568 self.client
4569 .send(proto::UpdateBufferFile {
4570 project_id,
4571 buffer_id: *buffer_id as u64,
4572 file: Some(new_file.to_proto()),
4573 })
4574 .log_err();
4575 }
4576
4577 buffer.file_updated(Arc::new(new_file), cx).detach();
4578 }
4579 }
4580 });
4581 } else {
4582 buffers_to_delete.push(*buffer_id);
4583 }
4584 }
4585
4586 for buffer_id in buffers_to_delete {
4587 self.opened_buffers.remove(&buffer_id);
4588 }
4589
4590 for (buffer, old_path) in renamed_buffers {
4591 self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4592 self.detect_language_for_buffer(&buffer, cx);
4593 self.register_buffer_with_language_server(&buffer, cx);
4594 }
4595 }
4596
4597 fn update_local_worktree_language_servers(
4598 &mut self,
4599 worktree_handle: &ModelHandle<Worktree>,
4600 changes: &HashMap<Arc<Path>, PathChange>,
4601 cx: &mut ModelContext<Self>,
4602 ) {
4603 let worktree_id = worktree_handle.read(cx).id();
4604 let abs_path = worktree_handle.read(cx).abs_path();
4605 for ((server_worktree_id, _), server_id) in &self.language_server_ids {
4606 if *server_worktree_id == worktree_id {
4607 if let Some(server) = self.language_servers.get(server_id) {
4608 if let LanguageServerState::Running {
4609 server,
4610 watched_paths,
4611 ..
4612 } = server
4613 {
4614 let params = lsp::DidChangeWatchedFilesParams {
4615 changes: changes
4616 .iter()
4617 .filter_map(|(path, change)| {
4618 let path = abs_path.join(path);
4619 if watched_paths.matches(&path) {
4620 Some(lsp::FileEvent {
4621 uri: lsp::Url::from_file_path(path).unwrap(),
4622 typ: match change {
4623 PathChange::Added => lsp::FileChangeType::CREATED,
4624 PathChange::Removed => lsp::FileChangeType::DELETED,
4625 PathChange::Updated
4626 | PathChange::AddedOrUpdated => {
4627 lsp::FileChangeType::CHANGED
4628 }
4629 },
4630 })
4631 } else {
4632 None
4633 }
4634 })
4635 .collect(),
4636 };
4637
4638 if !params.changes.is_empty() {
4639 server
4640 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
4641 .log_err();
4642 }
4643 }
4644 }
4645 }
4646 }
4647 }
4648
4649 fn update_local_worktree_buffers_git_repos(
4650 &mut self,
4651 worktree: ModelHandle<Worktree>,
4652 repos: &[GitRepositoryEntry],
4653 cx: &mut ModelContext<Self>,
4654 ) {
4655 for (_, buffer) in &self.opened_buffers {
4656 if let Some(buffer) = buffer.upgrade(cx) {
4657 let file = match File::from_dyn(buffer.read(cx).file()) {
4658 Some(file) => file,
4659 None => continue,
4660 };
4661 if file.worktree != worktree {
4662 continue;
4663 }
4664
4665 let path = file.path().clone();
4666
4667 let repo = match repos.iter().find(|repo| repo.manages(&path)) {
4668 Some(repo) => repo.clone(),
4669 None => return,
4670 };
4671
4672 let relative_repo = match path.strip_prefix(repo.content_path) {
4673 Ok(relative_repo) => relative_repo.to_owned(),
4674 Err(_) => return,
4675 };
4676
4677 let remote_id = self.remote_id();
4678 let client = self.client.clone();
4679
4680 cx.spawn(|_, mut cx| async move {
4681 let diff_base = cx
4682 .background()
4683 .spawn(async move { repo.repo.lock().load_index_text(&relative_repo) })
4684 .await;
4685
4686 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4687 buffer.set_diff_base(diff_base.clone(), cx);
4688 buffer.remote_id()
4689 });
4690
4691 if let Some(project_id) = remote_id {
4692 client
4693 .send(proto::UpdateDiffBase {
4694 project_id,
4695 buffer_id: buffer_id as u64,
4696 diff_base,
4697 })
4698 .log_err();
4699 }
4700 })
4701 .detach();
4702 }
4703 }
4704 }
4705
4706 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4707 let new_active_entry = entry.and_then(|project_path| {
4708 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4709 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4710 Some(entry.id)
4711 });
4712 if new_active_entry != self.active_entry {
4713 self.active_entry = new_active_entry;
4714 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4715 }
4716 }
4717
4718 pub fn language_servers_running_disk_based_diagnostics(
4719 &self,
4720 ) -> impl Iterator<Item = usize> + '_ {
4721 self.language_server_statuses
4722 .iter()
4723 .filter_map(|(id, status)| {
4724 if status.has_pending_diagnostic_updates {
4725 Some(*id)
4726 } else {
4727 None
4728 }
4729 })
4730 }
4731
4732 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4733 let mut summary = DiagnosticSummary::default();
4734 for (_, path_summary) in self.diagnostic_summaries(cx) {
4735 summary.error_count += path_summary.error_count;
4736 summary.warning_count += path_summary.warning_count;
4737 }
4738 summary
4739 }
4740
4741 pub fn diagnostic_summaries<'a>(
4742 &'a self,
4743 cx: &'a AppContext,
4744 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4745 self.visible_worktrees(cx).flat_map(move |worktree| {
4746 let worktree = worktree.read(cx);
4747 let worktree_id = worktree.id();
4748 worktree
4749 .diagnostic_summaries()
4750 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4751 })
4752 }
4753
4754 pub fn disk_based_diagnostics_started(
4755 &mut self,
4756 language_server_id: usize,
4757 cx: &mut ModelContext<Self>,
4758 ) {
4759 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4760 }
4761
4762 pub fn disk_based_diagnostics_finished(
4763 &mut self,
4764 language_server_id: usize,
4765 cx: &mut ModelContext<Self>,
4766 ) {
4767 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4768 }
4769
4770 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4771 self.active_entry
4772 }
4773
4774 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4775 self.worktree_for_id(path.worktree_id, cx)?
4776 .read(cx)
4777 .entry_for_path(&path.path)
4778 .cloned()
4779 }
4780
4781 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4782 let worktree = self.worktree_for_entry(entry_id, cx)?;
4783 let worktree = worktree.read(cx);
4784 let worktree_id = worktree.id();
4785 let path = worktree.entry_for_id(entry_id)?.path.clone();
4786 Some(ProjectPath { worktree_id, path })
4787 }
4788
4789 // RPC message handlers
4790
4791 async fn handle_unshare_project(
4792 this: ModelHandle<Self>,
4793 _: TypedEnvelope<proto::UnshareProject>,
4794 _: Arc<Client>,
4795 mut cx: AsyncAppContext,
4796 ) -> Result<()> {
4797 this.update(&mut cx, |this, cx| {
4798 if this.is_local() {
4799 this.unshare(cx)?;
4800 } else {
4801 this.disconnected_from_host(cx);
4802 }
4803 Ok(())
4804 })
4805 }
4806
4807 async fn handle_add_collaborator(
4808 this: ModelHandle<Self>,
4809 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4810 _: Arc<Client>,
4811 mut cx: AsyncAppContext,
4812 ) -> Result<()> {
4813 let collaborator = envelope
4814 .payload
4815 .collaborator
4816 .take()
4817 .ok_or_else(|| anyhow!("empty collaborator"))?;
4818
4819 let collaborator = Collaborator::from_proto(collaborator)?;
4820 this.update(&mut cx, |this, cx| {
4821 this.shared_buffers.remove(&collaborator.peer_id);
4822 this.collaborators
4823 .insert(collaborator.peer_id, collaborator);
4824 cx.notify();
4825 });
4826
4827 Ok(())
4828 }
4829
4830 async fn handle_update_project_collaborator(
4831 this: ModelHandle<Self>,
4832 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4833 _: Arc<Client>,
4834 mut cx: AsyncAppContext,
4835 ) -> Result<()> {
4836 let old_peer_id = envelope
4837 .payload
4838 .old_peer_id
4839 .ok_or_else(|| anyhow!("missing old peer id"))?;
4840 let new_peer_id = envelope
4841 .payload
4842 .new_peer_id
4843 .ok_or_else(|| anyhow!("missing new peer id"))?;
4844 this.update(&mut cx, |this, cx| {
4845 let collaborator = this
4846 .collaborators
4847 .remove(&old_peer_id)
4848 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4849 let is_host = collaborator.replica_id == 0;
4850 this.collaborators.insert(new_peer_id, collaborator);
4851
4852 let buffers = this.shared_buffers.remove(&old_peer_id);
4853 log::info!(
4854 "peer {} became {}. moving buffers {:?}",
4855 old_peer_id,
4856 new_peer_id,
4857 &buffers
4858 );
4859 if let Some(buffers) = buffers {
4860 this.shared_buffers.insert(new_peer_id, buffers);
4861 }
4862
4863 if is_host {
4864 this.synchronize_remote_buffers(cx).detach_and_log_err(cx);
4865 }
4866
4867 cx.emit(Event::CollaboratorUpdated {
4868 old_peer_id,
4869 new_peer_id,
4870 });
4871 cx.notify();
4872 Ok(())
4873 })
4874 }
4875
4876 async fn handle_remove_collaborator(
4877 this: ModelHandle<Self>,
4878 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4879 _: Arc<Client>,
4880 mut cx: AsyncAppContext,
4881 ) -> Result<()> {
4882 this.update(&mut cx, |this, cx| {
4883 let peer_id = envelope
4884 .payload
4885 .peer_id
4886 .ok_or_else(|| anyhow!("invalid peer id"))?;
4887 let replica_id = this
4888 .collaborators
4889 .remove(&peer_id)
4890 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4891 .replica_id;
4892 for buffer in this.opened_buffers.values() {
4893 if let Some(buffer) = buffer.upgrade(cx) {
4894 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4895 }
4896 }
4897 this.shared_buffers.remove(&peer_id);
4898
4899 cx.emit(Event::CollaboratorLeft(peer_id));
4900 cx.notify();
4901 Ok(())
4902 })
4903 }
4904
4905 async fn handle_update_project(
4906 this: ModelHandle<Self>,
4907 envelope: TypedEnvelope<proto::UpdateProject>,
4908 _: Arc<Client>,
4909 mut cx: AsyncAppContext,
4910 ) -> Result<()> {
4911 this.update(&mut cx, |this, cx| {
4912 // Don't handle messages that were sent before the response to us joining the project
4913 if envelope.message_id > this.join_project_response_message_id {
4914 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4915 }
4916 Ok(())
4917 })
4918 }
4919
4920 async fn handle_update_worktree(
4921 this: ModelHandle<Self>,
4922 envelope: TypedEnvelope<proto::UpdateWorktree>,
4923 _: Arc<Client>,
4924 mut cx: AsyncAppContext,
4925 ) -> Result<()> {
4926 this.update(&mut cx, |this, cx| {
4927 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4928 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4929 worktree.update(cx, |worktree, _| {
4930 let worktree = worktree.as_remote_mut().unwrap();
4931 worktree.update_from_remote(envelope.payload);
4932 });
4933 }
4934 Ok(())
4935 })
4936 }
4937
4938 async fn handle_create_project_entry(
4939 this: ModelHandle<Self>,
4940 envelope: TypedEnvelope<proto::CreateProjectEntry>,
4941 _: Arc<Client>,
4942 mut cx: AsyncAppContext,
4943 ) -> Result<proto::ProjectEntryResponse> {
4944 let worktree = this.update(&mut cx, |this, cx| {
4945 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4946 this.worktree_for_id(worktree_id, cx)
4947 .ok_or_else(|| anyhow!("worktree not found"))
4948 })?;
4949 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4950 let entry = worktree
4951 .update(&mut cx, |worktree, cx| {
4952 let worktree = worktree.as_local_mut().unwrap();
4953 let path = PathBuf::from(envelope.payload.path);
4954 worktree.create_entry(path, envelope.payload.is_directory, cx)
4955 })
4956 .await?;
4957 Ok(proto::ProjectEntryResponse {
4958 entry: Some((&entry).into()),
4959 worktree_scan_id: worktree_scan_id as u64,
4960 })
4961 }
4962
4963 async fn handle_rename_project_entry(
4964 this: ModelHandle<Self>,
4965 envelope: TypedEnvelope<proto::RenameProjectEntry>,
4966 _: Arc<Client>,
4967 mut cx: AsyncAppContext,
4968 ) -> Result<proto::ProjectEntryResponse> {
4969 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4970 let worktree = this.read_with(&cx, |this, cx| {
4971 this.worktree_for_entry(entry_id, cx)
4972 .ok_or_else(|| anyhow!("worktree not found"))
4973 })?;
4974 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4975 let entry = worktree
4976 .update(&mut cx, |worktree, cx| {
4977 let new_path = PathBuf::from(envelope.payload.new_path);
4978 worktree
4979 .as_local_mut()
4980 .unwrap()
4981 .rename_entry(entry_id, new_path, cx)
4982 .ok_or_else(|| anyhow!("invalid entry"))
4983 })?
4984 .await?;
4985 Ok(proto::ProjectEntryResponse {
4986 entry: Some((&entry).into()),
4987 worktree_scan_id: worktree_scan_id as u64,
4988 })
4989 }
4990
4991 async fn handle_copy_project_entry(
4992 this: ModelHandle<Self>,
4993 envelope: TypedEnvelope<proto::CopyProjectEntry>,
4994 _: Arc<Client>,
4995 mut cx: AsyncAppContext,
4996 ) -> Result<proto::ProjectEntryResponse> {
4997 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4998 let worktree = this.read_with(&cx, |this, cx| {
4999 this.worktree_for_entry(entry_id, cx)
5000 .ok_or_else(|| anyhow!("worktree not found"))
5001 })?;
5002 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5003 let entry = worktree
5004 .update(&mut cx, |worktree, cx| {
5005 let new_path = PathBuf::from(envelope.payload.new_path);
5006 worktree
5007 .as_local_mut()
5008 .unwrap()
5009 .copy_entry(entry_id, new_path, cx)
5010 .ok_or_else(|| anyhow!("invalid entry"))
5011 })?
5012 .await?;
5013 Ok(proto::ProjectEntryResponse {
5014 entry: Some((&entry).into()),
5015 worktree_scan_id: worktree_scan_id as u64,
5016 })
5017 }
5018
5019 async fn handle_delete_project_entry(
5020 this: ModelHandle<Self>,
5021 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
5022 _: Arc<Client>,
5023 mut cx: AsyncAppContext,
5024 ) -> Result<proto::ProjectEntryResponse> {
5025 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5026 let worktree = this.read_with(&cx, |this, cx| {
5027 this.worktree_for_entry(entry_id, cx)
5028 .ok_or_else(|| anyhow!("worktree not found"))
5029 })?;
5030 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5031 worktree
5032 .update(&mut cx, |worktree, cx| {
5033 worktree
5034 .as_local_mut()
5035 .unwrap()
5036 .delete_entry(entry_id, cx)
5037 .ok_or_else(|| anyhow!("invalid entry"))
5038 })?
5039 .await?;
5040 Ok(proto::ProjectEntryResponse {
5041 entry: None,
5042 worktree_scan_id: worktree_scan_id as u64,
5043 })
5044 }
5045
5046 async fn handle_update_diagnostic_summary(
5047 this: ModelHandle<Self>,
5048 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5049 _: Arc<Client>,
5050 mut cx: AsyncAppContext,
5051 ) -> Result<()> {
5052 this.update(&mut cx, |this, cx| {
5053 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5054 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5055 if let Some(summary) = envelope.payload.summary {
5056 let project_path = ProjectPath {
5057 worktree_id,
5058 path: Path::new(&summary.path).into(),
5059 };
5060 worktree.update(cx, |worktree, _| {
5061 worktree
5062 .as_remote_mut()
5063 .unwrap()
5064 .update_diagnostic_summary(project_path.path.clone(), &summary);
5065 });
5066 cx.emit(Event::DiagnosticsUpdated {
5067 language_server_id: summary.language_server_id as usize,
5068 path: project_path,
5069 });
5070 }
5071 }
5072 Ok(())
5073 })
5074 }
5075
5076 async fn handle_start_language_server(
5077 this: ModelHandle<Self>,
5078 envelope: TypedEnvelope<proto::StartLanguageServer>,
5079 _: Arc<Client>,
5080 mut cx: AsyncAppContext,
5081 ) -> Result<()> {
5082 let server = envelope
5083 .payload
5084 .server
5085 .ok_or_else(|| anyhow!("invalid server"))?;
5086 this.update(&mut cx, |this, cx| {
5087 this.language_server_statuses.insert(
5088 server.id as usize,
5089 LanguageServerStatus {
5090 name: server.name,
5091 pending_work: Default::default(),
5092 has_pending_diagnostic_updates: false,
5093 progress_tokens: Default::default(),
5094 },
5095 );
5096 cx.notify();
5097 });
5098 Ok(())
5099 }
5100
5101 async fn handle_update_language_server(
5102 this: ModelHandle<Self>,
5103 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5104 _: Arc<Client>,
5105 mut cx: AsyncAppContext,
5106 ) -> Result<()> {
5107 this.update(&mut cx, |this, cx| {
5108 let language_server_id = envelope.payload.language_server_id as usize;
5109
5110 match envelope
5111 .payload
5112 .variant
5113 .ok_or_else(|| anyhow!("invalid variant"))?
5114 {
5115 proto::update_language_server::Variant::WorkStart(payload) => {
5116 this.on_lsp_work_start(
5117 language_server_id,
5118 payload.token,
5119 LanguageServerProgress {
5120 message: payload.message,
5121 percentage: payload.percentage.map(|p| p as usize),
5122 last_update_at: Instant::now(),
5123 },
5124 cx,
5125 );
5126 }
5127
5128 proto::update_language_server::Variant::WorkProgress(payload) => {
5129 this.on_lsp_work_progress(
5130 language_server_id,
5131 payload.token,
5132 LanguageServerProgress {
5133 message: payload.message,
5134 percentage: payload.percentage.map(|p| p as usize),
5135 last_update_at: Instant::now(),
5136 },
5137 cx,
5138 );
5139 }
5140
5141 proto::update_language_server::Variant::WorkEnd(payload) => {
5142 this.on_lsp_work_end(language_server_id, payload.token, cx);
5143 }
5144
5145 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5146 this.disk_based_diagnostics_started(language_server_id, cx);
5147 }
5148
5149 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5150 this.disk_based_diagnostics_finished(language_server_id, cx)
5151 }
5152 }
5153
5154 Ok(())
5155 })
5156 }
5157
5158 async fn handle_update_buffer(
5159 this: ModelHandle<Self>,
5160 envelope: TypedEnvelope<proto::UpdateBuffer>,
5161 _: Arc<Client>,
5162 mut cx: AsyncAppContext,
5163 ) -> Result<()> {
5164 this.update(&mut cx, |this, cx| {
5165 let payload = envelope.payload.clone();
5166 let buffer_id = payload.buffer_id;
5167 let ops = payload
5168 .operations
5169 .into_iter()
5170 .map(language::proto::deserialize_operation)
5171 .collect::<Result<Vec<_>, _>>()?;
5172 let is_remote = this.is_remote();
5173 match this.opened_buffers.entry(buffer_id) {
5174 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5175 OpenBuffer::Strong(buffer) => {
5176 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5177 }
5178 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5179 OpenBuffer::Weak(_) => {}
5180 },
5181 hash_map::Entry::Vacant(e) => {
5182 assert!(
5183 is_remote,
5184 "received buffer update from {:?}",
5185 envelope.original_sender_id
5186 );
5187 e.insert(OpenBuffer::Operations(ops));
5188 }
5189 }
5190 Ok(())
5191 })
5192 }
5193
5194 async fn handle_create_buffer_for_peer(
5195 this: ModelHandle<Self>,
5196 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5197 _: Arc<Client>,
5198 mut cx: AsyncAppContext,
5199 ) -> Result<()> {
5200 this.update(&mut cx, |this, cx| {
5201 match envelope
5202 .payload
5203 .variant
5204 .ok_or_else(|| anyhow!("missing variant"))?
5205 {
5206 proto::create_buffer_for_peer::Variant::State(mut state) => {
5207 let mut buffer_file = None;
5208 if let Some(file) = state.file.take() {
5209 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5210 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5211 anyhow!("no worktree found for id {}", file.worktree_id)
5212 })?;
5213 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5214 as Arc<dyn language::File>);
5215 }
5216
5217 let buffer_id = state.id;
5218 let buffer = cx.add_model(|_| {
5219 Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5220 });
5221 this.incomplete_remote_buffers
5222 .insert(buffer_id, Some(buffer));
5223 }
5224 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5225 let buffer = this
5226 .incomplete_remote_buffers
5227 .get(&chunk.buffer_id)
5228 .cloned()
5229 .flatten()
5230 .ok_or_else(|| {
5231 anyhow!(
5232 "received chunk for buffer {} without initial state",
5233 chunk.buffer_id
5234 )
5235 })?;
5236 let operations = chunk
5237 .operations
5238 .into_iter()
5239 .map(language::proto::deserialize_operation)
5240 .collect::<Result<Vec<_>>>()?;
5241 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5242
5243 if chunk.is_last {
5244 this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5245 this.register_buffer(&buffer, cx)?;
5246 }
5247 }
5248 }
5249
5250 Ok(())
5251 })
5252 }
5253
5254 async fn handle_update_diff_base(
5255 this: ModelHandle<Self>,
5256 envelope: TypedEnvelope<proto::UpdateDiffBase>,
5257 _: Arc<Client>,
5258 mut cx: AsyncAppContext,
5259 ) -> Result<()> {
5260 this.update(&mut cx, |this, cx| {
5261 let buffer_id = envelope.payload.buffer_id;
5262 let diff_base = envelope.payload.diff_base;
5263 if let Some(buffer) = this
5264 .opened_buffers
5265 .get_mut(&buffer_id)
5266 .and_then(|b| b.upgrade(cx))
5267 .or_else(|| {
5268 this.incomplete_remote_buffers
5269 .get(&buffer_id)
5270 .cloned()
5271 .flatten()
5272 })
5273 {
5274 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5275 }
5276 Ok(())
5277 })
5278 }
5279
5280 async fn handle_update_buffer_file(
5281 this: ModelHandle<Self>,
5282 envelope: TypedEnvelope<proto::UpdateBufferFile>,
5283 _: Arc<Client>,
5284 mut cx: AsyncAppContext,
5285 ) -> Result<()> {
5286 let buffer_id = envelope.payload.buffer_id;
5287
5288 this.update(&mut cx, |this, cx| {
5289 let payload = envelope.payload.clone();
5290 if let Some(buffer) = this
5291 .opened_buffers
5292 .get(&buffer_id)
5293 .and_then(|b| b.upgrade(cx))
5294 .or_else(|| {
5295 this.incomplete_remote_buffers
5296 .get(&buffer_id)
5297 .cloned()
5298 .flatten()
5299 })
5300 {
5301 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5302 let worktree = this
5303 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5304 .ok_or_else(|| anyhow!("no such worktree"))?;
5305 let file = File::from_proto(file, worktree, cx)?;
5306 buffer.update(cx, |buffer, cx| {
5307 buffer.file_updated(Arc::new(file), cx).detach();
5308 });
5309 this.detect_language_for_buffer(&buffer, cx);
5310 }
5311 Ok(())
5312 })
5313 }
5314
5315 async fn handle_save_buffer(
5316 this: ModelHandle<Self>,
5317 envelope: TypedEnvelope<proto::SaveBuffer>,
5318 _: Arc<Client>,
5319 mut cx: AsyncAppContext,
5320 ) -> Result<proto::BufferSaved> {
5321 let buffer_id = envelope.payload.buffer_id;
5322 let requested_version = deserialize_version(envelope.payload.version);
5323
5324 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5325 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5326 let buffer = this
5327 .opened_buffers
5328 .get(&buffer_id)
5329 .and_then(|buffer| buffer.upgrade(cx))
5330 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5331 Ok::<_, anyhow::Error>((project_id, buffer))
5332 })?;
5333 buffer
5334 .update(&mut cx, |buffer, _| {
5335 buffer.wait_for_version(requested_version)
5336 })
5337 .await;
5338
5339 let (saved_version, fingerprint, mtime) = this
5340 .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5341 .await?;
5342 Ok(proto::BufferSaved {
5343 project_id,
5344 buffer_id,
5345 version: serialize_version(&saved_version),
5346 mtime: Some(mtime.into()),
5347 fingerprint: language::proto::serialize_fingerprint(fingerprint),
5348 })
5349 }
5350
5351 async fn handle_reload_buffers(
5352 this: ModelHandle<Self>,
5353 envelope: TypedEnvelope<proto::ReloadBuffers>,
5354 _: Arc<Client>,
5355 mut cx: AsyncAppContext,
5356 ) -> Result<proto::ReloadBuffersResponse> {
5357 let sender_id = envelope.original_sender_id()?;
5358 let reload = this.update(&mut cx, |this, cx| {
5359 let mut buffers = HashSet::default();
5360 for buffer_id in &envelope.payload.buffer_ids {
5361 buffers.insert(
5362 this.opened_buffers
5363 .get(buffer_id)
5364 .and_then(|buffer| buffer.upgrade(cx))
5365 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5366 );
5367 }
5368 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5369 })?;
5370
5371 let project_transaction = reload.await?;
5372 let project_transaction = this.update(&mut cx, |this, cx| {
5373 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5374 });
5375 Ok(proto::ReloadBuffersResponse {
5376 transaction: Some(project_transaction),
5377 })
5378 }
5379
5380 async fn handle_synchronize_buffers(
5381 this: ModelHandle<Self>,
5382 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5383 _: Arc<Client>,
5384 mut cx: AsyncAppContext,
5385 ) -> Result<proto::SynchronizeBuffersResponse> {
5386 let project_id = envelope.payload.project_id;
5387 let mut response = proto::SynchronizeBuffersResponse {
5388 buffers: Default::default(),
5389 };
5390
5391 this.update(&mut cx, |this, cx| {
5392 let Some(guest_id) = envelope.original_sender_id else {
5393 log::error!("missing original_sender_id on SynchronizeBuffers request");
5394 return;
5395 };
5396
5397 this.shared_buffers.entry(guest_id).or_default().clear();
5398 for buffer in envelope.payload.buffers {
5399 let buffer_id = buffer.id;
5400 let remote_version = language::proto::deserialize_version(buffer.version);
5401 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5402 this.shared_buffers
5403 .entry(guest_id)
5404 .or_default()
5405 .insert(buffer_id);
5406
5407 let buffer = buffer.read(cx);
5408 response.buffers.push(proto::BufferVersion {
5409 id: buffer_id,
5410 version: language::proto::serialize_version(&buffer.version),
5411 });
5412
5413 let operations = buffer.serialize_ops(Some(remote_version), cx);
5414 let client = this.client.clone();
5415 if let Some(file) = buffer.file() {
5416 client
5417 .send(proto::UpdateBufferFile {
5418 project_id,
5419 buffer_id: buffer_id as u64,
5420 file: Some(file.to_proto()),
5421 })
5422 .log_err();
5423 }
5424
5425 client
5426 .send(proto::UpdateDiffBase {
5427 project_id,
5428 buffer_id: buffer_id as u64,
5429 diff_base: buffer.diff_base().map(Into::into),
5430 })
5431 .log_err();
5432
5433 client
5434 .send(proto::BufferReloaded {
5435 project_id,
5436 buffer_id,
5437 version: language::proto::serialize_version(buffer.saved_version()),
5438 mtime: Some(buffer.saved_mtime().into()),
5439 fingerprint: language::proto::serialize_fingerprint(
5440 buffer.saved_version_fingerprint(),
5441 ),
5442 line_ending: language::proto::serialize_line_ending(
5443 buffer.line_ending(),
5444 ) as i32,
5445 })
5446 .log_err();
5447
5448 cx.background()
5449 .spawn(
5450 async move {
5451 let operations = operations.await;
5452 for chunk in split_operations(operations) {
5453 client
5454 .request(proto::UpdateBuffer {
5455 project_id,
5456 buffer_id,
5457 operations: chunk,
5458 })
5459 .await?;
5460 }
5461 anyhow::Ok(())
5462 }
5463 .log_err(),
5464 )
5465 .detach();
5466 }
5467 }
5468 });
5469
5470 Ok(response)
5471 }
5472
5473 async fn handle_format_buffers(
5474 this: ModelHandle<Self>,
5475 envelope: TypedEnvelope<proto::FormatBuffers>,
5476 _: Arc<Client>,
5477 mut cx: AsyncAppContext,
5478 ) -> Result<proto::FormatBuffersResponse> {
5479 let sender_id = envelope.original_sender_id()?;
5480 let format = this.update(&mut cx, |this, cx| {
5481 let mut buffers = HashSet::default();
5482 for buffer_id in &envelope.payload.buffer_ids {
5483 buffers.insert(
5484 this.opened_buffers
5485 .get(buffer_id)
5486 .and_then(|buffer| buffer.upgrade(cx))
5487 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5488 );
5489 }
5490 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5491 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5492 })?;
5493
5494 let project_transaction = format.await?;
5495 let project_transaction = this.update(&mut cx, |this, cx| {
5496 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5497 });
5498 Ok(proto::FormatBuffersResponse {
5499 transaction: Some(project_transaction),
5500 })
5501 }
5502
5503 async fn handle_get_completions(
5504 this: ModelHandle<Self>,
5505 envelope: TypedEnvelope<proto::GetCompletions>,
5506 _: Arc<Client>,
5507 mut cx: AsyncAppContext,
5508 ) -> Result<proto::GetCompletionsResponse> {
5509 let buffer = this.read_with(&cx, |this, cx| {
5510 this.opened_buffers
5511 .get(&envelope.payload.buffer_id)
5512 .and_then(|buffer| buffer.upgrade(cx))
5513 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5514 })?;
5515
5516 let version = deserialize_version(envelope.payload.version);
5517 buffer
5518 .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5519 .await;
5520 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5521
5522 let position = envelope
5523 .payload
5524 .position
5525 .and_then(language::proto::deserialize_anchor)
5526 .map(|p| {
5527 buffer.read_with(&cx, |buffer, _| {
5528 buffer.clip_point_utf16(Unclipped(p.to_point_utf16(buffer)), Bias::Left)
5529 })
5530 })
5531 .ok_or_else(|| anyhow!("invalid position"))?;
5532
5533 let completions = this
5534 .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5535 .await?;
5536
5537 Ok(proto::GetCompletionsResponse {
5538 completions: completions
5539 .iter()
5540 .map(language::proto::serialize_completion)
5541 .collect(),
5542 version: serialize_version(&version),
5543 })
5544 }
5545
5546 async fn handle_apply_additional_edits_for_completion(
5547 this: ModelHandle<Self>,
5548 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5549 _: Arc<Client>,
5550 mut cx: AsyncAppContext,
5551 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5552 let (buffer, completion) = this.update(&mut cx, |this, cx| {
5553 let buffer = this
5554 .opened_buffers
5555 .get(&envelope.payload.buffer_id)
5556 .and_then(|buffer| buffer.upgrade(cx))
5557 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5558 let language = buffer.read(cx).language();
5559 let completion = language::proto::deserialize_completion(
5560 envelope
5561 .payload
5562 .completion
5563 .ok_or_else(|| anyhow!("invalid completion"))?,
5564 language.cloned(),
5565 );
5566 Ok::<_, anyhow::Error>((buffer, completion))
5567 })?;
5568
5569 let completion = completion.await?;
5570
5571 let apply_additional_edits = this.update(&mut cx, |this, cx| {
5572 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5573 });
5574
5575 Ok(proto::ApplyCompletionAdditionalEditsResponse {
5576 transaction: apply_additional_edits
5577 .await?
5578 .as_ref()
5579 .map(language::proto::serialize_transaction),
5580 })
5581 }
5582
5583 async fn handle_get_code_actions(
5584 this: ModelHandle<Self>,
5585 envelope: TypedEnvelope<proto::GetCodeActions>,
5586 _: Arc<Client>,
5587 mut cx: AsyncAppContext,
5588 ) -> Result<proto::GetCodeActionsResponse> {
5589 let start = envelope
5590 .payload
5591 .start
5592 .and_then(language::proto::deserialize_anchor)
5593 .ok_or_else(|| anyhow!("invalid start"))?;
5594 let end = envelope
5595 .payload
5596 .end
5597 .and_then(language::proto::deserialize_anchor)
5598 .ok_or_else(|| anyhow!("invalid end"))?;
5599 let buffer = this.update(&mut cx, |this, cx| {
5600 this.opened_buffers
5601 .get(&envelope.payload.buffer_id)
5602 .and_then(|buffer| buffer.upgrade(cx))
5603 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5604 })?;
5605 buffer
5606 .update(&mut cx, |buffer, _| {
5607 buffer.wait_for_version(deserialize_version(envelope.payload.version))
5608 })
5609 .await;
5610
5611 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5612 let code_actions = this.update(&mut cx, |this, cx| {
5613 Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5614 })?;
5615
5616 Ok(proto::GetCodeActionsResponse {
5617 actions: code_actions
5618 .await?
5619 .iter()
5620 .map(language::proto::serialize_code_action)
5621 .collect(),
5622 version: serialize_version(&version),
5623 })
5624 }
5625
5626 async fn handle_apply_code_action(
5627 this: ModelHandle<Self>,
5628 envelope: TypedEnvelope<proto::ApplyCodeAction>,
5629 _: Arc<Client>,
5630 mut cx: AsyncAppContext,
5631 ) -> Result<proto::ApplyCodeActionResponse> {
5632 let sender_id = envelope.original_sender_id()?;
5633 let action = language::proto::deserialize_code_action(
5634 envelope
5635 .payload
5636 .action
5637 .ok_or_else(|| anyhow!("invalid action"))?,
5638 )?;
5639 let apply_code_action = this.update(&mut cx, |this, cx| {
5640 let buffer = this
5641 .opened_buffers
5642 .get(&envelope.payload.buffer_id)
5643 .and_then(|buffer| buffer.upgrade(cx))
5644 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5645 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5646 })?;
5647
5648 let project_transaction = apply_code_action.await?;
5649 let project_transaction = this.update(&mut cx, |this, cx| {
5650 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5651 });
5652 Ok(proto::ApplyCodeActionResponse {
5653 transaction: Some(project_transaction),
5654 })
5655 }
5656
5657 async fn handle_lsp_command<T: LspCommand>(
5658 this: ModelHandle<Self>,
5659 envelope: TypedEnvelope<T::ProtoRequest>,
5660 _: Arc<Client>,
5661 mut cx: AsyncAppContext,
5662 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5663 where
5664 <T::LspRequest as lsp::request::Request>::Result: Send,
5665 {
5666 let sender_id = envelope.original_sender_id()?;
5667 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5668 let buffer_handle = this.read_with(&cx, |this, _| {
5669 this.opened_buffers
5670 .get(&buffer_id)
5671 .and_then(|buffer| buffer.upgrade(&cx))
5672 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5673 })?;
5674 let request = T::from_proto(
5675 envelope.payload,
5676 this.clone(),
5677 buffer_handle.clone(),
5678 cx.clone(),
5679 )
5680 .await?;
5681 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5682 let response = this
5683 .update(&mut cx, |this, cx| {
5684 this.request_lsp(buffer_handle, request, cx)
5685 })
5686 .await?;
5687 this.update(&mut cx, |this, cx| {
5688 Ok(T::response_to_proto(
5689 response,
5690 this,
5691 sender_id,
5692 &buffer_version,
5693 cx,
5694 ))
5695 })
5696 }
5697
5698 async fn handle_get_project_symbols(
5699 this: ModelHandle<Self>,
5700 envelope: TypedEnvelope<proto::GetProjectSymbols>,
5701 _: Arc<Client>,
5702 mut cx: AsyncAppContext,
5703 ) -> Result<proto::GetProjectSymbolsResponse> {
5704 let symbols = this
5705 .update(&mut cx, |this, cx| {
5706 this.symbols(&envelope.payload.query, cx)
5707 })
5708 .await?;
5709
5710 Ok(proto::GetProjectSymbolsResponse {
5711 symbols: symbols.iter().map(serialize_symbol).collect(),
5712 })
5713 }
5714
5715 async fn handle_search_project(
5716 this: ModelHandle<Self>,
5717 envelope: TypedEnvelope<proto::SearchProject>,
5718 _: Arc<Client>,
5719 mut cx: AsyncAppContext,
5720 ) -> Result<proto::SearchProjectResponse> {
5721 let peer_id = envelope.original_sender_id()?;
5722 let query = SearchQuery::from_proto(envelope.payload)?;
5723 let result = this
5724 .update(&mut cx, |this, cx| this.search(query, cx))
5725 .await?;
5726
5727 this.update(&mut cx, |this, cx| {
5728 let mut locations = Vec::new();
5729 for (buffer, ranges) in result {
5730 for range in ranges {
5731 let start = serialize_anchor(&range.start);
5732 let end = serialize_anchor(&range.end);
5733 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5734 locations.push(proto::Location {
5735 buffer_id,
5736 start: Some(start),
5737 end: Some(end),
5738 });
5739 }
5740 }
5741 Ok(proto::SearchProjectResponse { locations })
5742 })
5743 }
5744
5745 async fn handle_open_buffer_for_symbol(
5746 this: ModelHandle<Self>,
5747 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5748 _: Arc<Client>,
5749 mut cx: AsyncAppContext,
5750 ) -> Result<proto::OpenBufferForSymbolResponse> {
5751 let peer_id = envelope.original_sender_id()?;
5752 let symbol = envelope
5753 .payload
5754 .symbol
5755 .ok_or_else(|| anyhow!("invalid symbol"))?;
5756 let symbol = this
5757 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5758 .await?;
5759 let symbol = this.read_with(&cx, |this, _| {
5760 let signature = this.symbol_signature(&symbol.path);
5761 if signature == symbol.signature {
5762 Ok(symbol)
5763 } else {
5764 Err(anyhow!("invalid symbol signature"))
5765 }
5766 })?;
5767 let buffer = this
5768 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5769 .await?;
5770
5771 Ok(proto::OpenBufferForSymbolResponse {
5772 buffer_id: this.update(&mut cx, |this, cx| {
5773 this.create_buffer_for_peer(&buffer, peer_id, cx)
5774 }),
5775 })
5776 }
5777
5778 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5779 let mut hasher = Sha256::new();
5780 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5781 hasher.update(project_path.path.to_string_lossy().as_bytes());
5782 hasher.update(self.nonce.to_be_bytes());
5783 hasher.finalize().as_slice().try_into().unwrap()
5784 }
5785
5786 async fn handle_open_buffer_by_id(
5787 this: ModelHandle<Self>,
5788 envelope: TypedEnvelope<proto::OpenBufferById>,
5789 _: Arc<Client>,
5790 mut cx: AsyncAppContext,
5791 ) -> Result<proto::OpenBufferResponse> {
5792 let peer_id = envelope.original_sender_id()?;
5793 let buffer = this
5794 .update(&mut cx, |this, cx| {
5795 this.open_buffer_by_id(envelope.payload.id, cx)
5796 })
5797 .await?;
5798 this.update(&mut cx, |this, cx| {
5799 Ok(proto::OpenBufferResponse {
5800 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5801 })
5802 })
5803 }
5804
5805 async fn handle_open_buffer_by_path(
5806 this: ModelHandle<Self>,
5807 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5808 _: Arc<Client>,
5809 mut cx: AsyncAppContext,
5810 ) -> Result<proto::OpenBufferResponse> {
5811 let peer_id = envelope.original_sender_id()?;
5812 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5813 let open_buffer = this.update(&mut cx, |this, cx| {
5814 this.open_buffer(
5815 ProjectPath {
5816 worktree_id,
5817 path: PathBuf::from(envelope.payload.path).into(),
5818 },
5819 cx,
5820 )
5821 });
5822
5823 let buffer = open_buffer.await?;
5824 this.update(&mut cx, |this, cx| {
5825 Ok(proto::OpenBufferResponse {
5826 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5827 })
5828 })
5829 }
5830
5831 fn serialize_project_transaction_for_peer(
5832 &mut self,
5833 project_transaction: ProjectTransaction,
5834 peer_id: proto::PeerId,
5835 cx: &mut MutableAppContext,
5836 ) -> proto::ProjectTransaction {
5837 let mut serialized_transaction = proto::ProjectTransaction {
5838 buffer_ids: Default::default(),
5839 transactions: Default::default(),
5840 };
5841 for (buffer, transaction) in project_transaction.0 {
5842 serialized_transaction
5843 .buffer_ids
5844 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5845 serialized_transaction
5846 .transactions
5847 .push(language::proto::serialize_transaction(&transaction));
5848 }
5849 serialized_transaction
5850 }
5851
5852 fn deserialize_project_transaction(
5853 &mut self,
5854 message: proto::ProjectTransaction,
5855 push_to_history: bool,
5856 cx: &mut ModelContext<Self>,
5857 ) -> Task<Result<ProjectTransaction>> {
5858 cx.spawn(|this, mut cx| async move {
5859 let mut project_transaction = ProjectTransaction::default();
5860 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5861 {
5862 let buffer = this
5863 .update(&mut cx, |this, cx| {
5864 this.wait_for_remote_buffer(buffer_id, cx)
5865 })
5866 .await?;
5867 let transaction = language::proto::deserialize_transaction(transaction)?;
5868 project_transaction.0.insert(buffer, transaction);
5869 }
5870
5871 for (buffer, transaction) in &project_transaction.0 {
5872 buffer
5873 .update(&mut cx, |buffer, _| {
5874 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5875 })
5876 .await;
5877
5878 if push_to_history {
5879 buffer.update(&mut cx, |buffer, _| {
5880 buffer.push_transaction(transaction.clone(), Instant::now());
5881 });
5882 }
5883 }
5884
5885 Ok(project_transaction)
5886 })
5887 }
5888
5889 fn create_buffer_for_peer(
5890 &mut self,
5891 buffer: &ModelHandle<Buffer>,
5892 peer_id: proto::PeerId,
5893 cx: &mut MutableAppContext,
5894 ) -> u64 {
5895 let buffer_id = buffer.read(cx).remote_id();
5896 if let Some(project_id) = self.remote_id() {
5897 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5898 if shared_buffers.insert(buffer_id) {
5899 let buffer = buffer.clone();
5900 let operations = buffer.read(cx).serialize_ops(None, cx);
5901 let client = self.client.clone();
5902 cx.spawn(move |cx| async move {
5903 let operations = operations.await;
5904 let state = buffer.read_with(&cx, |buffer, _| buffer.to_proto());
5905
5906 client.send(proto::CreateBufferForPeer {
5907 project_id,
5908 peer_id: Some(peer_id),
5909 variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
5910 })?;
5911
5912 cx.background()
5913 .spawn(async move {
5914 let mut chunks = split_operations(operations).peekable();
5915 while let Some(chunk) = chunks.next() {
5916 let is_last = chunks.peek().is_none();
5917 client.send(proto::CreateBufferForPeer {
5918 project_id,
5919 peer_id: Some(peer_id),
5920 variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
5921 proto::BufferChunk {
5922 buffer_id,
5923 operations: chunk,
5924 is_last,
5925 },
5926 )),
5927 })?;
5928 }
5929 anyhow::Ok(())
5930 })
5931 .await
5932 })
5933 .detach()
5934 }
5935 }
5936
5937 buffer_id
5938 }
5939
5940 fn wait_for_remote_buffer(
5941 &mut self,
5942 id: u64,
5943 cx: &mut ModelContext<Self>,
5944 ) -> Task<Result<ModelHandle<Buffer>>> {
5945 let mut opened_buffer_rx = self.opened_buffer.1.clone();
5946
5947 cx.spawn_weak(|this, mut cx| async move {
5948 let buffer = loop {
5949 let Some(this) = this.upgrade(&cx) else {
5950 return Err(anyhow!("project dropped"));
5951 };
5952 let buffer = this.read_with(&cx, |this, cx| {
5953 this.opened_buffers
5954 .get(&id)
5955 .and_then(|buffer| buffer.upgrade(cx))
5956 });
5957 if let Some(buffer) = buffer {
5958 break buffer;
5959 } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5960 return Err(anyhow!("disconnected before buffer {} could be opened", id));
5961 }
5962
5963 this.update(&mut cx, |this, _| {
5964 this.incomplete_remote_buffers.entry(id).or_default();
5965 });
5966 drop(this);
5967 opened_buffer_rx
5968 .next()
5969 .await
5970 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5971 };
5972 buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5973 Ok(buffer)
5974 })
5975 }
5976
5977 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
5978 let project_id = match self.client_state.as_ref() {
5979 Some(ProjectClientState::Remote {
5980 sharing_has_stopped,
5981 remote_id,
5982 ..
5983 }) => {
5984 if *sharing_has_stopped {
5985 return Task::ready(Err(anyhow!(
5986 "can't synchronize remote buffers on a readonly project"
5987 )));
5988 } else {
5989 *remote_id
5990 }
5991 }
5992 Some(ProjectClientState::Local { .. }) | None => {
5993 return Task::ready(Err(anyhow!(
5994 "can't synchronize remote buffers on a local project"
5995 )))
5996 }
5997 };
5998
5999 let client = self.client.clone();
6000 cx.spawn(|this, cx| async move {
6001 let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
6002 let buffers = this
6003 .opened_buffers
6004 .iter()
6005 .filter_map(|(id, buffer)| {
6006 let buffer = buffer.upgrade(cx)?;
6007 Some(proto::BufferVersion {
6008 id: *id,
6009 version: language::proto::serialize_version(&buffer.read(cx).version),
6010 })
6011 })
6012 .collect();
6013 let incomplete_buffer_ids = this
6014 .incomplete_remote_buffers
6015 .keys()
6016 .copied()
6017 .collect::<Vec<_>>();
6018
6019 (buffers, incomplete_buffer_ids)
6020 });
6021 let response = client
6022 .request(proto::SynchronizeBuffers {
6023 project_id,
6024 buffers,
6025 })
6026 .await?;
6027
6028 let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
6029 let client = client.clone();
6030 let buffer_id = buffer.id;
6031 let remote_version = language::proto::deserialize_version(buffer.version);
6032 this.read_with(&cx, |this, cx| {
6033 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6034 let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
6035 cx.background().spawn(async move {
6036 let operations = operations.await;
6037 for chunk in split_operations(operations) {
6038 client
6039 .request(proto::UpdateBuffer {
6040 project_id,
6041 buffer_id,
6042 operations: chunk,
6043 })
6044 .await?;
6045 }
6046 anyhow::Ok(())
6047 })
6048 } else {
6049 Task::ready(Ok(()))
6050 }
6051 })
6052 });
6053
6054 // Any incomplete buffers have open requests waiting. Request that the host sends
6055 // creates these buffers for us again to unblock any waiting futures.
6056 for id in incomplete_buffer_ids {
6057 cx.background()
6058 .spawn(client.request(proto::OpenBufferById { project_id, id }))
6059 .detach();
6060 }
6061
6062 futures::future::join_all(send_updates_for_buffers)
6063 .await
6064 .into_iter()
6065 .collect()
6066 })
6067 }
6068
6069 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
6070 self.worktrees(cx)
6071 .map(|worktree| {
6072 let worktree = worktree.read(cx);
6073 proto::WorktreeMetadata {
6074 id: worktree.id().to_proto(),
6075 root_name: worktree.root_name().into(),
6076 visible: worktree.is_visible(),
6077 abs_path: worktree.abs_path().to_string_lossy().into(),
6078 }
6079 })
6080 .collect()
6081 }
6082
6083 fn set_worktrees_from_proto(
6084 &mut self,
6085 worktrees: Vec<proto::WorktreeMetadata>,
6086 cx: &mut ModelContext<Project>,
6087 ) -> Result<()> {
6088 let replica_id = self.replica_id();
6089 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
6090
6091 let mut old_worktrees_by_id = self
6092 .worktrees
6093 .drain(..)
6094 .filter_map(|worktree| {
6095 let worktree = worktree.upgrade(cx)?;
6096 Some((worktree.read(cx).id(), worktree))
6097 })
6098 .collect::<HashMap<_, _>>();
6099
6100 for worktree in worktrees {
6101 if let Some(old_worktree) =
6102 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
6103 {
6104 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
6105 } else {
6106 let worktree =
6107 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
6108 let _ = self.add_worktree(&worktree, cx);
6109 }
6110 }
6111
6112 let _ = self.metadata_changed(cx);
6113 for (id, _) in old_worktrees_by_id {
6114 cx.emit(Event::WorktreeRemoved(id));
6115 }
6116
6117 Ok(())
6118 }
6119
6120 fn set_collaborators_from_proto(
6121 &mut self,
6122 messages: Vec<proto::Collaborator>,
6123 cx: &mut ModelContext<Self>,
6124 ) -> Result<()> {
6125 let mut collaborators = HashMap::default();
6126 for message in messages {
6127 let collaborator = Collaborator::from_proto(message)?;
6128 collaborators.insert(collaborator.peer_id, collaborator);
6129 }
6130 for old_peer_id in self.collaborators.keys() {
6131 if !collaborators.contains_key(old_peer_id) {
6132 cx.emit(Event::CollaboratorLeft(*old_peer_id));
6133 }
6134 }
6135 self.collaborators = collaborators;
6136 Ok(())
6137 }
6138
6139 fn deserialize_symbol(
6140 &self,
6141 serialized_symbol: proto::Symbol,
6142 ) -> impl Future<Output = Result<Symbol>> {
6143 let languages = self.languages.clone();
6144 async move {
6145 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
6146 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
6147 let start = serialized_symbol
6148 .start
6149 .ok_or_else(|| anyhow!("invalid start"))?;
6150 let end = serialized_symbol
6151 .end
6152 .ok_or_else(|| anyhow!("invalid end"))?;
6153 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
6154 let path = ProjectPath {
6155 worktree_id,
6156 path: PathBuf::from(serialized_symbol.path).into(),
6157 };
6158 let language = languages.language_for_path(&path.path).await.log_err();
6159 Ok(Symbol {
6160 language_server_name: LanguageServerName(
6161 serialized_symbol.language_server_name.into(),
6162 ),
6163 source_worktree_id,
6164 path,
6165 label: {
6166 match language {
6167 Some(language) => {
6168 language
6169 .label_for_symbol(&serialized_symbol.name, kind)
6170 .await
6171 }
6172 None => None,
6173 }
6174 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
6175 },
6176
6177 name: serialized_symbol.name,
6178 range: Unclipped(PointUtf16::new(start.row, start.column))
6179 ..Unclipped(PointUtf16::new(end.row, end.column)),
6180 kind,
6181 signature: serialized_symbol
6182 .signature
6183 .try_into()
6184 .map_err(|_| anyhow!("invalid signature"))?,
6185 })
6186 }
6187 }
6188
6189 async fn handle_buffer_saved(
6190 this: ModelHandle<Self>,
6191 envelope: TypedEnvelope<proto::BufferSaved>,
6192 _: Arc<Client>,
6193 mut cx: AsyncAppContext,
6194 ) -> Result<()> {
6195 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
6196 let version = deserialize_version(envelope.payload.version);
6197 let mtime = envelope
6198 .payload
6199 .mtime
6200 .ok_or_else(|| anyhow!("missing mtime"))?
6201 .into();
6202
6203 this.update(&mut cx, |this, cx| {
6204 let buffer = this
6205 .opened_buffers
6206 .get(&envelope.payload.buffer_id)
6207 .and_then(|buffer| buffer.upgrade(cx))
6208 .or_else(|| {
6209 this.incomplete_remote_buffers
6210 .get(&envelope.payload.buffer_id)
6211 .and_then(|b| b.clone())
6212 });
6213 if let Some(buffer) = buffer {
6214 buffer.update(cx, |buffer, cx| {
6215 buffer.did_save(version, fingerprint, mtime, cx);
6216 });
6217 }
6218 Ok(())
6219 })
6220 }
6221
6222 async fn handle_buffer_reloaded(
6223 this: ModelHandle<Self>,
6224 envelope: TypedEnvelope<proto::BufferReloaded>,
6225 _: Arc<Client>,
6226 mut cx: AsyncAppContext,
6227 ) -> Result<()> {
6228 let payload = envelope.payload;
6229 let version = deserialize_version(payload.version);
6230 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
6231 let line_ending = deserialize_line_ending(
6232 proto::LineEnding::from_i32(payload.line_ending)
6233 .ok_or_else(|| anyhow!("missing line ending"))?,
6234 );
6235 let mtime = payload
6236 .mtime
6237 .ok_or_else(|| anyhow!("missing mtime"))?
6238 .into();
6239 this.update(&mut cx, |this, cx| {
6240 let buffer = this
6241 .opened_buffers
6242 .get(&payload.buffer_id)
6243 .and_then(|buffer| buffer.upgrade(cx));
6244 if let Some(buffer) = buffer {
6245 buffer.update(cx, |buffer, cx| {
6246 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6247 });
6248 }
6249 Ok(())
6250 })
6251 }
6252
6253 #[allow(clippy::type_complexity)]
6254 fn edits_from_lsp(
6255 &mut self,
6256 buffer: &ModelHandle<Buffer>,
6257 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6258 version: Option<i32>,
6259 cx: &mut ModelContext<Self>,
6260 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6261 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
6262 cx.background().spawn(async move {
6263 let snapshot = snapshot?;
6264 let mut lsp_edits = lsp_edits
6265 .into_iter()
6266 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6267 .collect::<Vec<_>>();
6268 lsp_edits.sort_by_key(|(range, _)| range.start);
6269
6270 let mut lsp_edits = lsp_edits.into_iter().peekable();
6271 let mut edits = Vec::new();
6272 while let Some((range, mut new_text)) = lsp_edits.next() {
6273 // Clip invalid ranges provided by the language server.
6274 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6275 ..snapshot.clip_point_utf16(range.end, Bias::Left);
6276
6277 // Combine any LSP edits that are adjacent.
6278 //
6279 // Also, combine LSP edits that are separated from each other by only
6280 // a newline. This is important because for some code actions,
6281 // Rust-analyzer rewrites the entire buffer via a series of edits that
6282 // are separated by unchanged newline characters.
6283 //
6284 // In order for the diffing logic below to work properly, any edits that
6285 // cancel each other out must be combined into one.
6286 while let Some((next_range, next_text)) = lsp_edits.peek() {
6287 if next_range.start.0 > range.end {
6288 if next_range.start.0.row > range.end.row + 1
6289 || next_range.start.0.column > 0
6290 || snapshot.clip_point_utf16(
6291 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6292 Bias::Left,
6293 ) > range.end
6294 {
6295 break;
6296 }
6297 new_text.push('\n');
6298 }
6299 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6300 new_text.push_str(next_text);
6301 lsp_edits.next();
6302 }
6303
6304 // For multiline edits, perform a diff of the old and new text so that
6305 // we can identify the changes more precisely, preserving the locations
6306 // of any anchors positioned in the unchanged regions.
6307 if range.end.row > range.start.row {
6308 let mut offset = range.start.to_offset(&snapshot);
6309 let old_text = snapshot.text_for_range(range).collect::<String>();
6310
6311 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6312 let mut moved_since_edit = true;
6313 for change in diff.iter_all_changes() {
6314 let tag = change.tag();
6315 let value = change.value();
6316 match tag {
6317 ChangeTag::Equal => {
6318 offset += value.len();
6319 moved_since_edit = true;
6320 }
6321 ChangeTag::Delete => {
6322 let start = snapshot.anchor_after(offset);
6323 let end = snapshot.anchor_before(offset + value.len());
6324 if moved_since_edit {
6325 edits.push((start..end, String::new()));
6326 } else {
6327 edits.last_mut().unwrap().0.end = end;
6328 }
6329 offset += value.len();
6330 moved_since_edit = false;
6331 }
6332 ChangeTag::Insert => {
6333 if moved_since_edit {
6334 let anchor = snapshot.anchor_after(offset);
6335 edits.push((anchor..anchor, value.to_string()));
6336 } else {
6337 edits.last_mut().unwrap().1.push_str(value);
6338 }
6339 moved_since_edit = false;
6340 }
6341 }
6342 }
6343 } else if range.end == range.start {
6344 let anchor = snapshot.anchor_after(range.start);
6345 edits.push((anchor..anchor, new_text));
6346 } else {
6347 let edit_start = snapshot.anchor_after(range.start);
6348 let edit_end = snapshot.anchor_before(range.end);
6349 edits.push((edit_start..edit_end, new_text));
6350 }
6351 }
6352
6353 Ok(edits)
6354 })
6355 }
6356
6357 fn buffer_snapshot_for_lsp_version(
6358 &mut self,
6359 buffer: &ModelHandle<Buffer>,
6360 version: Option<i32>,
6361 cx: &AppContext,
6362 ) -> Result<TextBufferSnapshot> {
6363 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6364
6365 if let Some(version) = version {
6366 let buffer_id = buffer.read(cx).remote_id();
6367 let snapshots = self
6368 .buffer_snapshots
6369 .get_mut(&buffer_id)
6370 .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
6371 let found_snapshot = snapshots
6372 .binary_search_by_key(&version, |e| e.0)
6373 .map(|ix| snapshots[ix].1.clone())
6374 .map_err(|_| {
6375 anyhow!(
6376 "snapshot not found for buffer {} at version {}",
6377 buffer_id,
6378 version
6379 )
6380 })?;
6381 snapshots.retain(|(snapshot_version, _)| {
6382 snapshot_version + OLD_VERSIONS_TO_RETAIN >= version
6383 });
6384 Ok(found_snapshot)
6385 } else {
6386 Ok((buffer.read(cx)).text_snapshot())
6387 }
6388 }
6389
6390 fn language_server_for_buffer(
6391 &self,
6392 buffer: &Buffer,
6393 cx: &AppContext,
6394 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6395 let server_id = self.language_server_id_for_buffer(buffer, cx)?;
6396 let server = self.language_servers.get(&server_id)?;
6397 if let LanguageServerState::Running {
6398 adapter, server, ..
6399 } = server
6400 {
6401 Some((adapter, server))
6402 } else {
6403 None
6404 }
6405 }
6406
6407 fn language_server_id_for_buffer(&self, buffer: &Buffer, cx: &AppContext) -> Option<usize> {
6408 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6409 let name = language.lsp_adapter()?.name.clone();
6410 let worktree_id = file.worktree_id(cx);
6411 let key = (worktree_id, name);
6412 self.language_server_ids.get(&key).copied()
6413 } else {
6414 None
6415 }
6416 }
6417}
6418
6419impl WorktreeHandle {
6420 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6421 match self {
6422 WorktreeHandle::Strong(handle) => Some(handle.clone()),
6423 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6424 }
6425 }
6426}
6427
6428impl OpenBuffer {
6429 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6430 match self {
6431 OpenBuffer::Strong(handle) => Some(handle.clone()),
6432 OpenBuffer::Weak(handle) => handle.upgrade(cx),
6433 OpenBuffer::Operations(_) => None,
6434 }
6435 }
6436}
6437
6438pub struct PathMatchCandidateSet {
6439 pub snapshot: Snapshot,
6440 pub include_ignored: bool,
6441 pub include_root_name: bool,
6442}
6443
6444impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6445 type Candidates = PathMatchCandidateSetIter<'a>;
6446
6447 fn id(&self) -> usize {
6448 self.snapshot.id().to_usize()
6449 }
6450
6451 fn len(&self) -> usize {
6452 if self.include_ignored {
6453 self.snapshot.file_count()
6454 } else {
6455 self.snapshot.visible_file_count()
6456 }
6457 }
6458
6459 fn prefix(&self) -> Arc<str> {
6460 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6461 self.snapshot.root_name().into()
6462 } else if self.include_root_name {
6463 format!("{}/", self.snapshot.root_name()).into()
6464 } else {
6465 "".into()
6466 }
6467 }
6468
6469 fn candidates(&'a self, start: usize) -> Self::Candidates {
6470 PathMatchCandidateSetIter {
6471 traversal: self.snapshot.files(self.include_ignored, start),
6472 }
6473 }
6474}
6475
6476pub struct PathMatchCandidateSetIter<'a> {
6477 traversal: Traversal<'a>,
6478}
6479
6480impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6481 type Item = fuzzy::PathMatchCandidate<'a>;
6482
6483 fn next(&mut self) -> Option<Self::Item> {
6484 self.traversal.next().map(|entry| {
6485 if let EntryKind::File(char_bag) = entry.kind {
6486 fuzzy::PathMatchCandidate {
6487 path: &entry.path,
6488 char_bag,
6489 }
6490 } else {
6491 unreachable!()
6492 }
6493 })
6494 }
6495}
6496
6497impl Entity for Project {
6498 type Event = Event;
6499
6500 fn release(&mut self, _: &mut gpui::MutableAppContext) {
6501 match &self.client_state {
6502 Some(ProjectClientState::Local { remote_id, .. }) => {
6503 let _ = self.client.send(proto::UnshareProject {
6504 project_id: *remote_id,
6505 });
6506 }
6507 Some(ProjectClientState::Remote { remote_id, .. }) => {
6508 let _ = self.client.send(proto::LeaveProject {
6509 project_id: *remote_id,
6510 });
6511 }
6512 _ => {}
6513 }
6514 }
6515
6516 fn app_will_quit(
6517 &mut self,
6518 _: &mut MutableAppContext,
6519 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6520 let shutdown_futures = self
6521 .language_servers
6522 .drain()
6523 .map(|(_, server_state)| async {
6524 match server_state {
6525 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6526 LanguageServerState::Starting(starting_server) => {
6527 starting_server.await?.shutdown()?.await
6528 }
6529 }
6530 })
6531 .collect::<Vec<_>>();
6532
6533 Some(
6534 async move {
6535 futures::future::join_all(shutdown_futures).await;
6536 }
6537 .boxed(),
6538 )
6539 }
6540}
6541
6542impl Collaborator {
6543 fn from_proto(message: proto::Collaborator) -> Result<Self> {
6544 Ok(Self {
6545 peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6546 replica_id: message.replica_id as ReplicaId,
6547 })
6548 }
6549}
6550
6551impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6552 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6553 Self {
6554 worktree_id,
6555 path: path.as_ref().into(),
6556 }
6557 }
6558}
6559
6560fn split_operations(
6561 mut operations: Vec<proto::Operation>,
6562) -> impl Iterator<Item = Vec<proto::Operation>> {
6563 #[cfg(any(test, feature = "test-support"))]
6564 const CHUNK_SIZE: usize = 5;
6565
6566 #[cfg(not(any(test, feature = "test-support")))]
6567 const CHUNK_SIZE: usize = 100;
6568
6569 let mut done = false;
6570 std::iter::from_fn(move || {
6571 if done {
6572 return None;
6573 }
6574
6575 let operations = operations
6576 .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6577 .collect::<Vec<_>>();
6578 if operations.is_empty() {
6579 done = true;
6580 }
6581 Some(operations)
6582 })
6583}
6584
6585fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6586 proto::Symbol {
6587 language_server_name: symbol.language_server_name.0.to_string(),
6588 source_worktree_id: symbol.source_worktree_id.to_proto(),
6589 worktree_id: symbol.path.worktree_id.to_proto(),
6590 path: symbol.path.path.to_string_lossy().to_string(),
6591 name: symbol.name.clone(),
6592 kind: unsafe { mem::transmute(symbol.kind) },
6593 start: Some(proto::PointUtf16 {
6594 row: symbol.range.start.0.row,
6595 column: symbol.range.start.0.column,
6596 }),
6597 end: Some(proto::PointUtf16 {
6598 row: symbol.range.end.0.row,
6599 column: symbol.range.end.0.column,
6600 }),
6601 signature: symbol.signature.to_vec(),
6602 }
6603}
6604
6605fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6606 let mut path_components = path.components();
6607 let mut base_components = base.components();
6608 let mut components: Vec<Component> = Vec::new();
6609 loop {
6610 match (path_components.next(), base_components.next()) {
6611 (None, None) => break,
6612 (Some(a), None) => {
6613 components.push(a);
6614 components.extend(path_components.by_ref());
6615 break;
6616 }
6617 (None, _) => components.push(Component::ParentDir),
6618 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6619 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6620 (Some(a), Some(_)) => {
6621 components.push(Component::ParentDir);
6622 for _ in base_components {
6623 components.push(Component::ParentDir);
6624 }
6625 components.push(a);
6626 components.extend(path_components.by_ref());
6627 break;
6628 }
6629 }
6630 }
6631 components.iter().map(|c| c.as_os_str()).collect()
6632}
6633
6634impl Item for Buffer {
6635 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6636 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6637 }
6638
6639 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6640 File::from_dyn(self.file()).map(|file| ProjectPath {
6641 worktree_id: file.worktree_id(cx),
6642 path: file.path().clone(),
6643 })
6644 }
6645}