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