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