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