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