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