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