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