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