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