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