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