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