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