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