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