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