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