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