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