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