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