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