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