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