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