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