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 markdown, 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 Documentation, Event as BufferEvent, File as _, Language, LanguageRegistry, LanguageServerName,
45 LocalFile, LspAdapterDelegate, OffsetRangeExt, Operation, Patch, PendingLanguageServer,
46 PointUtf16, 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, RwLock};
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: Vec::new(),
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: HashMap::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: HashMap::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 =
2718 cx.update(|cx| adapter.workspace_configuration(server.root_path(), cx))?;
2719 server
2720 .notify::<lsp::notification::DidChangeConfiguration>(
2721 lsp::DidChangeConfigurationParams {
2722 settings: workspace_config.clone(),
2723 },
2724 )
2725 .ok();
2726 }
2727 }
2728
2729 drop(settings_observation);
2730 anyhow::Ok(())
2731 })
2732 }
2733
2734 fn detect_language_for_buffer(
2735 &mut self,
2736 buffer_handle: &Model<Buffer>,
2737 cx: &mut ModelContext<Self>,
2738 ) -> Option<()> {
2739 // If the buffer has a language, set it and start the language server if we haven't already.
2740 let buffer = buffer_handle.read(cx);
2741 let full_path = buffer.file()?.full_path(cx);
2742 let content = buffer.as_rope();
2743 let new_language = self
2744 .languages
2745 .language_for_file(&full_path, Some(content))
2746 .now_or_never()?
2747 .ok()?;
2748 self.set_language_for_buffer(buffer_handle, new_language, cx);
2749 None
2750 }
2751
2752 pub fn set_language_for_buffer(
2753 &mut self,
2754 buffer: &Model<Buffer>,
2755 new_language: Arc<Language>,
2756 cx: &mut ModelContext<Self>,
2757 ) {
2758 buffer.update(cx, |buffer, cx| {
2759 if buffer.language().map_or(true, |old_language| {
2760 !Arc::ptr_eq(old_language, &new_language)
2761 }) {
2762 buffer.set_language(Some(new_language.clone()), cx);
2763 }
2764 });
2765
2766 let buffer_file = buffer.read(cx).file().cloned();
2767 let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
2768 let buffer_file = File::from_dyn(buffer_file.as_ref());
2769 let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
2770 if let Some(prettier_plugins) =
2771 prettier_support::prettier_plugins_for_language(&new_language, &settings)
2772 {
2773 self.install_default_prettier(worktree, prettier_plugins, cx);
2774 };
2775 if let Some(file) = buffer_file {
2776 let worktree = file.worktree.clone();
2777 if let Some(tree) = worktree.read(cx).as_local() {
2778 self.start_language_servers(&worktree, tree.abs_path().clone(), new_language, cx);
2779 }
2780 }
2781 }
2782
2783 fn start_language_servers(
2784 &mut self,
2785 worktree: &Model<Worktree>,
2786 worktree_path: Arc<Path>,
2787 language: Arc<Language>,
2788 cx: &mut ModelContext<Self>,
2789 ) {
2790 let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
2791 let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
2792 if !settings.enable_language_server {
2793 return;
2794 }
2795
2796 let worktree_id = worktree.read(cx).id();
2797 for adapter in language.lsp_adapters() {
2798 self.start_language_server(
2799 worktree_id,
2800 worktree_path.clone(),
2801 adapter.clone(),
2802 language.clone(),
2803 cx,
2804 );
2805 }
2806 }
2807
2808 fn start_language_server(
2809 &mut self,
2810 worktree_id: WorktreeId,
2811 worktree_path: Arc<Path>,
2812 adapter: Arc<CachedLspAdapter>,
2813 language: Arc<Language>,
2814 cx: &mut ModelContext<Self>,
2815 ) {
2816 if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2817 return;
2818 }
2819
2820 let key = (worktree_id, adapter.name.clone());
2821 if self.language_server_ids.contains_key(&key) {
2822 return;
2823 }
2824
2825 let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
2826 let pending_server = match self.languages.create_pending_language_server(
2827 stderr_capture.clone(),
2828 language.clone(),
2829 adapter.clone(),
2830 Arc::clone(&worktree_path),
2831 ProjectLspAdapterDelegate::new(self, cx),
2832 cx,
2833 ) {
2834 Some(pending_server) => pending_server,
2835 None => return,
2836 };
2837
2838 let project_settings = ProjectSettings::get_global(cx);
2839 let lsp = project_settings.lsp.get(&adapter.name.0);
2840 let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2841
2842 let server_id = pending_server.server_id;
2843 let container_dir = pending_server.container_dir.clone();
2844 let state = LanguageServerState::Starting({
2845 let adapter = adapter.clone();
2846 let server_name = adapter.name.0.clone();
2847 let language = language.clone();
2848 let key = key.clone();
2849
2850 cx.spawn(move |this, mut cx| async move {
2851 let result = Self::setup_and_insert_language_server(
2852 this.clone(),
2853 &worktree_path,
2854 override_options,
2855 pending_server,
2856 adapter.clone(),
2857 language.clone(),
2858 server_id,
2859 key,
2860 &mut cx,
2861 )
2862 .await;
2863
2864 match result {
2865 Ok(server) => {
2866 stderr_capture.lock().take();
2867 server
2868 }
2869
2870 Err(err) => {
2871 log::error!("failed to start language server {server_name:?}: {err}");
2872 log::error!("server stderr: {:?}", stderr_capture.lock().take());
2873
2874 let this = this.upgrade()?;
2875 let container_dir = container_dir?;
2876
2877 let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
2878 if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2879 let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
2880 log::error!("Hit {max} reinstallation attempts for {server_name:?}");
2881 return None;
2882 }
2883
2884 let installation_test_binary = adapter
2885 .installation_test_binary(container_dir.to_path_buf())
2886 .await;
2887
2888 this.update(&mut cx, |_, cx| {
2889 Self::check_errored_server(
2890 language,
2891 adapter,
2892 server_id,
2893 installation_test_binary,
2894 cx,
2895 )
2896 })
2897 .ok();
2898
2899 None
2900 }
2901 }
2902 })
2903 });
2904
2905 self.language_servers.insert(server_id, state);
2906 self.language_server_ids.insert(key, server_id);
2907 }
2908
2909 fn reinstall_language_server(
2910 &mut self,
2911 language: Arc<Language>,
2912 adapter: Arc<CachedLspAdapter>,
2913 server_id: LanguageServerId,
2914 cx: &mut ModelContext<Self>,
2915 ) -> Option<Task<()>> {
2916 log::info!("beginning to reinstall server");
2917
2918 let existing_server = match self.language_servers.remove(&server_id) {
2919 Some(LanguageServerState::Running { server, .. }) => Some(server),
2920 _ => None,
2921 };
2922
2923 for worktree in &self.worktrees {
2924 if let Some(worktree) = worktree.upgrade() {
2925 let key = (worktree.read(cx).id(), adapter.name.clone());
2926 self.language_server_ids.remove(&key);
2927 }
2928 }
2929
2930 Some(cx.spawn(move |this, mut cx| async move {
2931 if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2932 log::info!("shutting down existing server");
2933 task.await;
2934 }
2935
2936 // TODO: This is race-safe with regards to preventing new instances from
2937 // starting while deleting, but existing instances in other projects are going
2938 // to be very confused and messed up
2939 let Some(task) = this
2940 .update(&mut cx, |this, cx| {
2941 this.languages.delete_server_container(adapter.clone(), cx)
2942 })
2943 .log_err()
2944 else {
2945 return;
2946 };
2947 task.await;
2948
2949 this.update(&mut cx, |this, cx| {
2950 let worktrees = this.worktrees.clone();
2951 for worktree in worktrees {
2952 let worktree = match worktree.upgrade() {
2953 Some(worktree) => worktree.read(cx),
2954 None => continue,
2955 };
2956 let worktree_id = worktree.id();
2957 let root_path = worktree.abs_path();
2958
2959 this.start_language_server(
2960 worktree_id,
2961 root_path,
2962 adapter.clone(),
2963 language.clone(),
2964 cx,
2965 );
2966 }
2967 })
2968 .ok();
2969 }))
2970 }
2971
2972 async fn setup_and_insert_language_server(
2973 this: WeakModel<Self>,
2974 worktree_path: &Path,
2975 override_initialization_options: Option<serde_json::Value>,
2976 pending_server: PendingLanguageServer,
2977 adapter: Arc<CachedLspAdapter>,
2978 language: Arc<Language>,
2979 server_id: LanguageServerId,
2980 key: (WorktreeId, LanguageServerName),
2981 cx: &mut AsyncAppContext,
2982 ) -> Result<Option<Arc<LanguageServer>>> {
2983 let language_server = Self::setup_pending_language_server(
2984 this.clone(),
2985 override_initialization_options,
2986 pending_server,
2987 worktree_path,
2988 adapter.clone(),
2989 server_id,
2990 cx,
2991 )
2992 .await?;
2993
2994 let this = match this.upgrade() {
2995 Some(this) => this,
2996 None => return Err(anyhow!("failed to upgrade project handle")),
2997 };
2998
2999 this.update(cx, |this, cx| {
3000 this.insert_newly_running_language_server(
3001 language,
3002 adapter,
3003 language_server.clone(),
3004 server_id,
3005 key,
3006 cx,
3007 )
3008 })??;
3009
3010 Ok(Some(language_server))
3011 }
3012
3013 async fn setup_pending_language_server(
3014 this: WeakModel<Self>,
3015 override_options: Option<serde_json::Value>,
3016 pending_server: PendingLanguageServer,
3017 worktree_path: &Path,
3018 adapter: Arc<CachedLspAdapter>,
3019 server_id: LanguageServerId,
3020 cx: &mut AsyncAppContext,
3021 ) -> Result<Arc<LanguageServer>> {
3022 let workspace_config =
3023 cx.update(|cx| adapter.workspace_configuration(worktree_path, cx))?;
3024 let language_server = pending_server.task.await?;
3025
3026 language_server
3027 .on_notification::<lsp::notification::PublishDiagnostics, _>({
3028 let adapter = adapter.clone();
3029 let this = this.clone();
3030 move |mut params, mut cx| {
3031 let adapter = adapter.clone();
3032 if let Some(this) = this.upgrade() {
3033 adapter.process_diagnostics(&mut params);
3034 this.update(&mut cx, |this, cx| {
3035 this.update_diagnostics(
3036 server_id,
3037 params,
3038 &adapter.disk_based_diagnostic_sources,
3039 cx,
3040 )
3041 .log_err();
3042 })
3043 .ok();
3044 }
3045 }
3046 })
3047 .detach();
3048
3049 language_server
3050 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
3051 let adapter = adapter.clone();
3052 let worktree_path = worktree_path.to_path_buf();
3053 move |params, cx| {
3054 let adapter = adapter.clone();
3055 let worktree_path = worktree_path.clone();
3056 async move {
3057 let workspace_config =
3058 cx.update(|cx| adapter.workspace_configuration(&worktree_path, cx))?;
3059 Ok(params
3060 .items
3061 .into_iter()
3062 .map(|item| {
3063 if let Some(section) = &item.section {
3064 workspace_config
3065 .get(section)
3066 .cloned()
3067 .unwrap_or(serde_json::Value::Null)
3068 } else {
3069 workspace_config.clone()
3070 }
3071 })
3072 .collect())
3073 }
3074 }
3075 })
3076 .detach();
3077
3078 // Even though we don't have handling for these requests, respond to them to
3079 // avoid stalling any language server like `gopls` which waits for a response
3080 // to these requests when initializing.
3081 language_server
3082 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
3083 let this = this.clone();
3084 move |params, mut cx| {
3085 let this = this.clone();
3086 async move {
3087 this.update(&mut cx, |this, _| {
3088 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
3089 {
3090 if let lsp::NumberOrString::String(token) = params.token {
3091 status.progress_tokens.insert(token);
3092 }
3093 }
3094 })?;
3095
3096 Ok(())
3097 }
3098 }
3099 })
3100 .detach();
3101
3102 language_server
3103 .on_request::<lsp::request::RegisterCapability, _, _>({
3104 let this = this.clone();
3105 move |params, mut cx| {
3106 let this = this.clone();
3107 async move {
3108 for reg in params.registrations {
3109 if reg.method == "workspace/didChangeWatchedFiles" {
3110 if let Some(options) = reg.register_options {
3111 let options = serde_json::from_value(options)?;
3112 this.update(&mut cx, |this, cx| {
3113 this.on_lsp_did_change_watched_files(
3114 server_id, options, cx,
3115 );
3116 })?;
3117 }
3118 }
3119 }
3120 Ok(())
3121 }
3122 }
3123 })
3124 .detach();
3125
3126 language_server
3127 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
3128 let adapter = adapter.clone();
3129 let this = this.clone();
3130 move |params, cx| {
3131 Self::on_lsp_workspace_edit(
3132 this.clone(),
3133 params,
3134 server_id,
3135 adapter.clone(),
3136 cx,
3137 )
3138 }
3139 })
3140 .detach();
3141
3142 language_server
3143 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
3144 let this = this.clone();
3145 move |(), mut cx| {
3146 let this = this.clone();
3147 async move {
3148 this.update(&mut cx, |project, cx| {
3149 cx.emit(Event::RefreshInlayHints);
3150 project.remote_id().map(|project_id| {
3151 project.client.send(proto::RefreshInlayHints { project_id })
3152 })
3153 })?
3154 .transpose()?;
3155 Ok(())
3156 }
3157 }
3158 })
3159 .detach();
3160
3161 let disk_based_diagnostics_progress_token =
3162 adapter.disk_based_diagnostics_progress_token.clone();
3163
3164 language_server
3165 .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
3166 if let Some(this) = this.upgrade() {
3167 this.update(&mut cx, |this, cx| {
3168 this.on_lsp_progress(
3169 params,
3170 server_id,
3171 disk_based_diagnostics_progress_token.clone(),
3172 cx,
3173 );
3174 })
3175 .ok();
3176 }
3177 })
3178 .detach();
3179 let mut initialization_options = adapter.adapter.initialization_options().await;
3180 match (&mut initialization_options, override_options) {
3181 (Some(initialization_options), Some(override_options)) => {
3182 merge_json_value_into(override_options, initialization_options);
3183 }
3184 (None, override_options) => initialization_options = override_options,
3185 _ => {}
3186 }
3187 let language_server = language_server.initialize(initialization_options).await?;
3188
3189 language_server
3190 .notify::<lsp::notification::DidChangeConfiguration>(
3191 lsp::DidChangeConfigurationParams {
3192 settings: workspace_config,
3193 },
3194 )
3195 .ok();
3196
3197 Ok(language_server)
3198 }
3199
3200 fn insert_newly_running_language_server(
3201 &mut self,
3202 language: Arc<Language>,
3203 adapter: Arc<CachedLspAdapter>,
3204 language_server: Arc<LanguageServer>,
3205 server_id: LanguageServerId,
3206 key: (WorktreeId, LanguageServerName),
3207 cx: &mut ModelContext<Self>,
3208 ) -> Result<()> {
3209 // If the language server for this key doesn't match the server id, don't store the
3210 // server. Which will cause it to be dropped, killing the process
3211 if self
3212 .language_server_ids
3213 .get(&key)
3214 .map(|id| id != &server_id)
3215 .unwrap_or(false)
3216 {
3217 return Ok(());
3218 }
3219
3220 // Update language_servers collection with Running variant of LanguageServerState
3221 // indicating that the server is up and running and ready
3222 self.language_servers.insert(
3223 server_id,
3224 LanguageServerState::Running {
3225 adapter: adapter.clone(),
3226 language: language.clone(),
3227 watched_paths: Default::default(),
3228 server: language_server.clone(),
3229 simulate_disk_based_diagnostics_completion: None,
3230 },
3231 );
3232
3233 self.language_server_statuses.insert(
3234 server_id,
3235 LanguageServerStatus {
3236 name: language_server.name().to_string(),
3237 pending_work: Default::default(),
3238 has_pending_diagnostic_updates: false,
3239 progress_tokens: Default::default(),
3240 },
3241 );
3242
3243 cx.emit(Event::LanguageServerAdded(server_id));
3244
3245 if let Some(project_id) = self.remote_id() {
3246 self.client.send(proto::StartLanguageServer {
3247 project_id,
3248 server: Some(proto::LanguageServer {
3249 id: server_id.0 as u64,
3250 name: language_server.name().to_string(),
3251 }),
3252 })?;
3253 }
3254
3255 // Tell the language server about every open buffer in the worktree that matches the language.
3256 for buffer in self.opened_buffers.values() {
3257 if let Some(buffer_handle) = buffer.upgrade() {
3258 let buffer = buffer_handle.read(cx);
3259 let file = match File::from_dyn(buffer.file()) {
3260 Some(file) => file,
3261 None => continue,
3262 };
3263 let language = match buffer.language() {
3264 Some(language) => language,
3265 None => continue,
3266 };
3267
3268 if file.worktree.read(cx).id() != key.0
3269 || !language.lsp_adapters().iter().any(|a| a.name == key.1)
3270 {
3271 continue;
3272 }
3273
3274 let file = match file.as_local() {
3275 Some(file) => file,
3276 None => continue,
3277 };
3278
3279 let versions = self
3280 .buffer_snapshots
3281 .entry(buffer.remote_id())
3282 .or_default()
3283 .entry(server_id)
3284 .or_insert_with(|| {
3285 vec![LspBufferSnapshot {
3286 version: 0,
3287 snapshot: buffer.text_snapshot(),
3288 }]
3289 });
3290
3291 let snapshot = versions.last().unwrap();
3292 let version = snapshot.version;
3293 let initial_snapshot = &snapshot.snapshot;
3294 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3295 language_server.notify::<lsp::notification::DidOpenTextDocument>(
3296 lsp::DidOpenTextDocumentParams {
3297 text_document: lsp::TextDocumentItem::new(
3298 uri,
3299 adapter
3300 .language_ids
3301 .get(language.name().as_ref())
3302 .cloned()
3303 .unwrap_or_default(),
3304 version,
3305 initial_snapshot.text(),
3306 ),
3307 },
3308 )?;
3309
3310 buffer_handle.update(cx, |buffer, cx| {
3311 buffer.set_completion_triggers(
3312 language_server
3313 .capabilities()
3314 .completion_provider
3315 .as_ref()
3316 .and_then(|provider| provider.trigger_characters.clone())
3317 .unwrap_or_default(),
3318 cx,
3319 )
3320 });
3321 }
3322 }
3323
3324 cx.notify();
3325 Ok(())
3326 }
3327
3328 // Returns a list of all of the worktrees which no longer have a language server and the root path
3329 // for the stopped server
3330 fn stop_language_server(
3331 &mut self,
3332 worktree_id: WorktreeId,
3333 adapter_name: LanguageServerName,
3334 cx: &mut ModelContext<Self>,
3335 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
3336 let key = (worktree_id, adapter_name);
3337 if let Some(server_id) = self.language_server_ids.remove(&key) {
3338 log::info!("stopping language server {}", key.1 .0);
3339
3340 // Remove other entries for this language server as well
3341 let mut orphaned_worktrees = vec![worktree_id];
3342 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3343 for other_key in other_keys {
3344 if self.language_server_ids.get(&other_key) == Some(&server_id) {
3345 self.language_server_ids.remove(&other_key);
3346 orphaned_worktrees.push(other_key.0);
3347 }
3348 }
3349
3350 for buffer in self.opened_buffers.values() {
3351 if let Some(buffer) = buffer.upgrade() {
3352 buffer.update(cx, |buffer, cx| {
3353 buffer.update_diagnostics(server_id, Default::default(), cx);
3354 });
3355 }
3356 }
3357 for worktree in &self.worktrees {
3358 if let Some(worktree) = worktree.upgrade() {
3359 worktree.update(cx, |worktree, cx| {
3360 if let Some(worktree) = worktree.as_local_mut() {
3361 worktree.clear_diagnostics_for_language_server(server_id, cx);
3362 }
3363 });
3364 }
3365 }
3366
3367 self.language_server_statuses.remove(&server_id);
3368 cx.notify();
3369
3370 let server_state = self.language_servers.remove(&server_id);
3371 cx.emit(Event::LanguageServerRemoved(server_id));
3372 cx.spawn(move |this, mut cx| async move {
3373 let mut root_path = None;
3374
3375 let server = match server_state {
3376 Some(LanguageServerState::Starting(task)) => task.await,
3377 Some(LanguageServerState::Running { server, .. }) => Some(server),
3378 None => None,
3379 };
3380
3381 if let Some(server) = server {
3382 root_path = Some(server.root_path().clone());
3383 if let Some(shutdown) = server.shutdown() {
3384 shutdown.await;
3385 }
3386 }
3387
3388 if let Some(this) = this.upgrade() {
3389 this.update(&mut cx, |this, cx| {
3390 this.language_server_statuses.remove(&server_id);
3391 cx.notify();
3392 })
3393 .ok();
3394 }
3395
3396 (root_path, orphaned_worktrees)
3397 })
3398 } else {
3399 Task::ready((None, Vec::new()))
3400 }
3401 }
3402
3403 pub fn restart_language_servers_for_buffers(
3404 &mut self,
3405 buffers: impl IntoIterator<Item = Model<Buffer>>,
3406 cx: &mut ModelContext<Self>,
3407 ) -> Option<()> {
3408 let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
3409 .into_iter()
3410 .filter_map(|buffer| {
3411 let buffer = buffer.read(cx);
3412 let file = File::from_dyn(buffer.file())?;
3413 let full_path = file.full_path(cx);
3414 let language = self
3415 .languages
3416 .language_for_file(&full_path, Some(buffer.as_rope()))
3417 .now_or_never()?
3418 .ok()?;
3419 Some((file.worktree.clone(), language))
3420 })
3421 .collect();
3422 for (worktree, language) in language_server_lookup_info {
3423 self.restart_language_servers(worktree, language, cx);
3424 }
3425
3426 None
3427 }
3428
3429 // TODO This will break in the case where the adapter's root paths and worktrees are not equal
3430 fn restart_language_servers(
3431 &mut self,
3432 worktree: Model<Worktree>,
3433 language: Arc<Language>,
3434 cx: &mut ModelContext<Self>,
3435 ) {
3436 let worktree_id = worktree.read(cx).id();
3437 let fallback_path = worktree.read(cx).abs_path();
3438
3439 let mut stops = Vec::new();
3440 for adapter in language.lsp_adapters() {
3441 stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
3442 }
3443
3444 if stops.is_empty() {
3445 return;
3446 }
3447 let mut stops = stops.into_iter();
3448
3449 cx.spawn(move |this, mut cx| async move {
3450 let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
3451 for stop in stops {
3452 let (_, worktrees) = stop.await;
3453 orphaned_worktrees.extend_from_slice(&worktrees);
3454 }
3455
3456 let this = match this.upgrade() {
3457 Some(this) => this,
3458 None => return,
3459 };
3460
3461 this.update(&mut cx, |this, cx| {
3462 // Attempt to restart using original server path. Fallback to passed in
3463 // path if we could not retrieve the root path
3464 let root_path = original_root_path
3465 .map(|path_buf| Arc::from(path_buf.as_path()))
3466 .unwrap_or(fallback_path);
3467
3468 this.start_language_servers(&worktree, root_path, language.clone(), cx);
3469
3470 // Lookup new server ids and set them for each of the orphaned worktrees
3471 for adapter in language.lsp_adapters() {
3472 if let Some(new_server_id) = this
3473 .language_server_ids
3474 .get(&(worktree_id, adapter.name.clone()))
3475 .cloned()
3476 {
3477 for &orphaned_worktree in &orphaned_worktrees {
3478 this.language_server_ids
3479 .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
3480 }
3481 }
3482 }
3483 })
3484 .ok();
3485 })
3486 .detach();
3487 }
3488
3489 fn check_errored_server(
3490 language: Arc<Language>,
3491 adapter: Arc<CachedLspAdapter>,
3492 server_id: LanguageServerId,
3493 installation_test_binary: Option<LanguageServerBinary>,
3494 cx: &mut ModelContext<Self>,
3495 ) {
3496 if !adapter.can_be_reinstalled() {
3497 log::info!(
3498 "Validation check requested for {:?} but it cannot be reinstalled",
3499 adapter.name.0
3500 );
3501 return;
3502 }
3503
3504 cx.spawn(move |this, mut cx| async move {
3505 log::info!("About to spawn test binary");
3506
3507 // A lack of test binary counts as a failure
3508 let process = installation_test_binary.and_then(|binary| {
3509 smol::process::Command::new(&binary.path)
3510 .current_dir(&binary.path)
3511 .args(binary.arguments)
3512 .stdin(Stdio::piped())
3513 .stdout(Stdio::piped())
3514 .stderr(Stdio::inherit())
3515 .kill_on_drop(true)
3516 .spawn()
3517 .ok()
3518 });
3519
3520 const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3521 let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
3522
3523 let mut errored = false;
3524 if let Some(mut process) = process {
3525 futures::select! {
3526 status = process.status().fuse() => match status {
3527 Ok(status) => errored = !status.success(),
3528 Err(_) => errored = true,
3529 },
3530
3531 _ = timeout => {
3532 log::info!("test binary time-ed out, this counts as a success");
3533 _ = process.kill();
3534 }
3535 }
3536 } else {
3537 log::warn!("test binary failed to launch");
3538 errored = true;
3539 }
3540
3541 if errored {
3542 log::warn!("test binary check failed");
3543 let task = this
3544 .update(&mut cx, move |this, cx| {
3545 this.reinstall_language_server(language, adapter, server_id, cx)
3546 })
3547 .ok()
3548 .flatten();
3549
3550 if let Some(task) = task {
3551 task.await;
3552 }
3553 }
3554 })
3555 .detach();
3556 }
3557
3558 fn on_lsp_progress(
3559 &mut self,
3560 progress: lsp::ProgressParams,
3561 language_server_id: LanguageServerId,
3562 disk_based_diagnostics_progress_token: Option<String>,
3563 cx: &mut ModelContext<Self>,
3564 ) {
3565 let token = match progress.token {
3566 lsp::NumberOrString::String(token) => token,
3567 lsp::NumberOrString::Number(token) => {
3568 log::info!("skipping numeric progress token {}", token);
3569 return;
3570 }
3571 };
3572 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3573 let language_server_status =
3574 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3575 status
3576 } else {
3577 return;
3578 };
3579
3580 if !language_server_status.progress_tokens.contains(&token) {
3581 return;
3582 }
3583
3584 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3585 .as_ref()
3586 .map_or(false, |disk_based_token| {
3587 token.starts_with(disk_based_token)
3588 });
3589
3590 match progress {
3591 lsp::WorkDoneProgress::Begin(report) => {
3592 if is_disk_based_diagnostics_progress {
3593 language_server_status.has_pending_diagnostic_updates = true;
3594 self.disk_based_diagnostics_started(language_server_id, cx);
3595 self.buffer_ordered_messages_tx
3596 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3597 language_server_id,
3598 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3599 })
3600 .ok();
3601 } else {
3602 self.on_lsp_work_start(
3603 language_server_id,
3604 token.clone(),
3605 LanguageServerProgress {
3606 message: report.message.clone(),
3607 percentage: report.percentage.map(|p| p as usize),
3608 last_update_at: Instant::now(),
3609 },
3610 cx,
3611 );
3612 self.buffer_ordered_messages_tx
3613 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3614 language_server_id,
3615 message: proto::update_language_server::Variant::WorkStart(
3616 proto::LspWorkStart {
3617 token,
3618 message: report.message,
3619 percentage: report.percentage.map(|p| p as u32),
3620 },
3621 ),
3622 })
3623 .ok();
3624 }
3625 }
3626 lsp::WorkDoneProgress::Report(report) => {
3627 if !is_disk_based_diagnostics_progress {
3628 self.on_lsp_work_progress(
3629 language_server_id,
3630 token.clone(),
3631 LanguageServerProgress {
3632 message: report.message.clone(),
3633 percentage: report.percentage.map(|p| p as usize),
3634 last_update_at: Instant::now(),
3635 },
3636 cx,
3637 );
3638 self.buffer_ordered_messages_tx
3639 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3640 language_server_id,
3641 message: proto::update_language_server::Variant::WorkProgress(
3642 proto::LspWorkProgress {
3643 token,
3644 message: report.message,
3645 percentage: report.percentage.map(|p| p as u32),
3646 },
3647 ),
3648 })
3649 .ok();
3650 }
3651 }
3652 lsp::WorkDoneProgress::End(_) => {
3653 language_server_status.progress_tokens.remove(&token);
3654
3655 if is_disk_based_diagnostics_progress {
3656 language_server_status.has_pending_diagnostic_updates = false;
3657 self.disk_based_diagnostics_finished(language_server_id, cx);
3658 self.buffer_ordered_messages_tx
3659 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3660 language_server_id,
3661 message:
3662 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3663 Default::default(),
3664 ),
3665 })
3666 .ok();
3667 } else {
3668 self.on_lsp_work_end(language_server_id, token.clone(), cx);
3669 self.buffer_ordered_messages_tx
3670 .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3671 language_server_id,
3672 message: proto::update_language_server::Variant::WorkEnd(
3673 proto::LspWorkEnd { token },
3674 ),
3675 })
3676 .ok();
3677 }
3678 }
3679 }
3680 }
3681
3682 fn on_lsp_work_start(
3683 &mut self,
3684 language_server_id: LanguageServerId,
3685 token: String,
3686 progress: LanguageServerProgress,
3687 cx: &mut ModelContext<Self>,
3688 ) {
3689 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3690 status.pending_work.insert(token, progress);
3691 cx.notify();
3692 }
3693 }
3694
3695 fn on_lsp_work_progress(
3696 &mut self,
3697 language_server_id: LanguageServerId,
3698 token: String,
3699 progress: LanguageServerProgress,
3700 cx: &mut ModelContext<Self>,
3701 ) {
3702 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3703 let entry = status
3704 .pending_work
3705 .entry(token)
3706 .or_insert(LanguageServerProgress {
3707 message: Default::default(),
3708 percentage: Default::default(),
3709 last_update_at: progress.last_update_at,
3710 });
3711 if progress.message.is_some() {
3712 entry.message = progress.message;
3713 }
3714 if progress.percentage.is_some() {
3715 entry.percentage = progress.percentage;
3716 }
3717 entry.last_update_at = progress.last_update_at;
3718 cx.notify();
3719 }
3720 }
3721
3722 fn on_lsp_work_end(
3723 &mut self,
3724 language_server_id: LanguageServerId,
3725 token: String,
3726 cx: &mut ModelContext<Self>,
3727 ) {
3728 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3729 cx.emit(Event::RefreshInlayHints);
3730 status.pending_work.remove(&token);
3731 cx.notify();
3732 }
3733 }
3734
3735 fn on_lsp_did_change_watched_files(
3736 &mut self,
3737 language_server_id: LanguageServerId,
3738 params: DidChangeWatchedFilesRegistrationOptions,
3739 cx: &mut ModelContext<Self>,
3740 ) {
3741 if let Some(LanguageServerState::Running { watched_paths, .. }) =
3742 self.language_servers.get_mut(&language_server_id)
3743 {
3744 let mut builders = HashMap::default();
3745 for watcher in params.watchers {
3746 for worktree in &self.worktrees {
3747 if let Some(worktree) = worktree.upgrade() {
3748 let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3749 if let Some(abs_path) = tree.abs_path().to_str() {
3750 let relative_glob_pattern = match &watcher.glob_pattern {
3751 lsp::GlobPattern::String(s) => s
3752 .strip_prefix(abs_path)
3753 .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3754 lsp::GlobPattern::Relative(rp) => {
3755 let base_uri = match &rp.base_uri {
3756 lsp::OneOf::Left(workspace_folder) => {
3757 &workspace_folder.uri
3758 }
3759 lsp::OneOf::Right(base_uri) => base_uri,
3760 };
3761 base_uri.to_file_path().ok().and_then(|file_path| {
3762 (file_path.to_str() == Some(abs_path))
3763 .then_some(rp.pattern.as_str())
3764 })
3765 }
3766 };
3767 if let Some(relative_glob_pattern) = relative_glob_pattern {
3768 let literal_prefix = glob_literal_prefix(relative_glob_pattern);
3769 tree.as_local_mut()
3770 .unwrap()
3771 .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3772 if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3773 builders
3774 .entry(tree.id())
3775 .or_insert_with(|| GlobSetBuilder::new())
3776 .add(glob);
3777 }
3778 return true;
3779 }
3780 }
3781 false
3782 });
3783 if glob_is_inside_worktree {
3784 break;
3785 }
3786 }
3787 }
3788 }
3789
3790 watched_paths.clear();
3791 for (worktree_id, builder) in builders {
3792 if let Ok(globset) = builder.build() {
3793 watched_paths.insert(worktree_id, globset);
3794 }
3795 }
3796
3797 cx.notify();
3798 }
3799 }
3800
3801 async fn on_lsp_workspace_edit(
3802 this: WeakModel<Self>,
3803 params: lsp::ApplyWorkspaceEditParams,
3804 server_id: LanguageServerId,
3805 adapter: Arc<CachedLspAdapter>,
3806 mut cx: AsyncAppContext,
3807 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3808 let this = this
3809 .upgrade()
3810 .ok_or_else(|| anyhow!("project project closed"))?;
3811 let language_server = this
3812 .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
3813 .ok_or_else(|| anyhow!("language server not found"))?;
3814 let transaction = Self::deserialize_workspace_edit(
3815 this.clone(),
3816 params.edit,
3817 true,
3818 adapter.clone(),
3819 language_server.clone(),
3820 &mut cx,
3821 )
3822 .await
3823 .log_err();
3824 this.update(&mut cx, |this, _| {
3825 if let Some(transaction) = transaction {
3826 this.last_workspace_edits_by_language_server
3827 .insert(server_id, transaction);
3828 }
3829 })?;
3830 Ok(lsp::ApplyWorkspaceEditResponse {
3831 applied: true,
3832 failed_change: None,
3833 failure_reason: None,
3834 })
3835 }
3836
3837 pub fn language_server_statuses(
3838 &self,
3839 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3840 self.language_server_statuses.values()
3841 }
3842
3843 pub fn update_diagnostics(
3844 &mut self,
3845 language_server_id: LanguageServerId,
3846 mut params: lsp::PublishDiagnosticsParams,
3847 disk_based_sources: &[String],
3848 cx: &mut ModelContext<Self>,
3849 ) -> Result<()> {
3850 let abs_path = params
3851 .uri
3852 .to_file_path()
3853 .map_err(|_| anyhow!("URI is not a file"))?;
3854 let mut diagnostics = Vec::default();
3855 let mut primary_diagnostic_group_ids = HashMap::default();
3856 let mut sources_by_group_id = HashMap::default();
3857 let mut supporting_diagnostics = HashMap::default();
3858
3859 // Ensure that primary diagnostics are always the most severe
3860 params.diagnostics.sort_by_key(|item| item.severity);
3861
3862 for diagnostic in ¶ms.diagnostics {
3863 let source = diagnostic.source.as_ref();
3864 let code = diagnostic.code.as_ref().map(|code| match code {
3865 lsp::NumberOrString::Number(code) => code.to_string(),
3866 lsp::NumberOrString::String(code) => code.clone(),
3867 });
3868 let range = range_from_lsp(diagnostic.range);
3869 let is_supporting = diagnostic
3870 .related_information
3871 .as_ref()
3872 .map_or(false, |infos| {
3873 infos.iter().any(|info| {
3874 primary_diagnostic_group_ids.contains_key(&(
3875 source,
3876 code.clone(),
3877 range_from_lsp(info.location.range),
3878 ))
3879 })
3880 });
3881
3882 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3883 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3884 });
3885
3886 if is_supporting {
3887 supporting_diagnostics.insert(
3888 (source, code.clone(), range),
3889 (diagnostic.severity, is_unnecessary),
3890 );
3891 } else {
3892 let group_id = post_inc(&mut self.next_diagnostic_group_id);
3893 let is_disk_based =
3894 source.map_or(false, |source| disk_based_sources.contains(source));
3895
3896 sources_by_group_id.insert(group_id, source);
3897 primary_diagnostic_group_ids
3898 .insert((source, code.clone(), range.clone()), group_id);
3899
3900 diagnostics.push(DiagnosticEntry {
3901 range,
3902 diagnostic: Diagnostic {
3903 source: diagnostic.source.clone(),
3904 code: code.clone(),
3905 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3906 message: diagnostic.message.trim().to_string(),
3907 group_id,
3908 is_primary: true,
3909 is_disk_based,
3910 is_unnecessary,
3911 },
3912 });
3913 if let Some(infos) = &diagnostic.related_information {
3914 for info in infos {
3915 if info.location.uri == params.uri && !info.message.is_empty() {
3916 let range = range_from_lsp(info.location.range);
3917 diagnostics.push(DiagnosticEntry {
3918 range,
3919 diagnostic: Diagnostic {
3920 source: diagnostic.source.clone(),
3921 code: code.clone(),
3922 severity: DiagnosticSeverity::INFORMATION,
3923 message: info.message.trim().to_string(),
3924 group_id,
3925 is_primary: false,
3926 is_disk_based,
3927 is_unnecessary: false,
3928 },
3929 });
3930 }
3931 }
3932 }
3933 }
3934 }
3935
3936 for entry in &mut diagnostics {
3937 let diagnostic = &mut entry.diagnostic;
3938 if !diagnostic.is_primary {
3939 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3940 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3941 source,
3942 diagnostic.code.clone(),
3943 entry.range.clone(),
3944 )) {
3945 if let Some(severity) = severity {
3946 diagnostic.severity = severity;
3947 }
3948 diagnostic.is_unnecessary = is_unnecessary;
3949 }
3950 }
3951 }
3952
3953 self.update_diagnostic_entries(
3954 language_server_id,
3955 abs_path,
3956 params.version,
3957 diagnostics,
3958 cx,
3959 )?;
3960 Ok(())
3961 }
3962
3963 pub fn update_diagnostic_entries(
3964 &mut self,
3965 server_id: LanguageServerId,
3966 abs_path: PathBuf,
3967 version: Option<i32>,
3968 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3969 cx: &mut ModelContext<Project>,
3970 ) -> Result<(), anyhow::Error> {
3971 let (worktree, relative_path) = self
3972 .find_local_worktree(&abs_path, cx)
3973 .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3974
3975 let project_path = ProjectPath {
3976 worktree_id: worktree.read(cx).id(),
3977 path: relative_path.into(),
3978 };
3979
3980 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3981 self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3982 }
3983
3984 let updated = worktree.update(cx, |worktree, cx| {
3985 worktree
3986 .as_local_mut()
3987 .ok_or_else(|| anyhow!("not a local worktree"))?
3988 .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3989 })?;
3990 if updated {
3991 cx.emit(Event::DiagnosticsUpdated {
3992 language_server_id: server_id,
3993 path: project_path,
3994 });
3995 }
3996 Ok(())
3997 }
3998
3999 fn update_buffer_diagnostics(
4000 &mut self,
4001 buffer: &Model<Buffer>,
4002 server_id: LanguageServerId,
4003 version: Option<i32>,
4004 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4005 cx: &mut ModelContext<Self>,
4006 ) -> Result<()> {
4007 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
4008 Ordering::Equal
4009 .then_with(|| b.is_primary.cmp(&a.is_primary))
4010 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
4011 .then_with(|| a.severity.cmp(&b.severity))
4012 .then_with(|| a.message.cmp(&b.message))
4013 }
4014
4015 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
4016
4017 diagnostics.sort_unstable_by(|a, b| {
4018 Ordering::Equal
4019 .then_with(|| a.range.start.cmp(&b.range.start))
4020 .then_with(|| b.range.end.cmp(&a.range.end))
4021 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
4022 });
4023
4024 let mut sanitized_diagnostics = Vec::new();
4025 let edits_since_save = Patch::new(
4026 snapshot
4027 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
4028 .collect(),
4029 );
4030 for entry in diagnostics {
4031 let start;
4032 let end;
4033 if entry.diagnostic.is_disk_based {
4034 // Some diagnostics are based on files on disk instead of buffers'
4035 // current contents. Adjust these diagnostics' ranges to reflect
4036 // any unsaved edits.
4037 start = edits_since_save.old_to_new(entry.range.start);
4038 end = edits_since_save.old_to_new(entry.range.end);
4039 } else {
4040 start = entry.range.start;
4041 end = entry.range.end;
4042 }
4043
4044 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
4045 ..snapshot.clip_point_utf16(end, Bias::Right);
4046
4047 // Expand empty ranges by one codepoint
4048 if range.start == range.end {
4049 // This will be go to the next boundary when being clipped
4050 range.end.column += 1;
4051 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
4052 if range.start == range.end && range.end.column > 0 {
4053 range.start.column -= 1;
4054 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
4055 }
4056 }
4057
4058 sanitized_diagnostics.push(DiagnosticEntry {
4059 range,
4060 diagnostic: entry.diagnostic,
4061 });
4062 }
4063 drop(edits_since_save);
4064
4065 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
4066 buffer.update(cx, |buffer, cx| {
4067 buffer.update_diagnostics(server_id, set, cx)
4068 });
4069 Ok(())
4070 }
4071
4072 pub fn reload_buffers(
4073 &self,
4074 buffers: HashSet<Model<Buffer>>,
4075 push_to_history: bool,
4076 cx: &mut ModelContext<Self>,
4077 ) -> Task<Result<ProjectTransaction>> {
4078 let mut local_buffers = Vec::new();
4079 let mut remote_buffers = None;
4080 for buffer_handle in buffers {
4081 let buffer = buffer_handle.read(cx);
4082 if buffer.is_dirty() {
4083 if let Some(file) = File::from_dyn(buffer.file()) {
4084 if file.is_local() {
4085 local_buffers.push(buffer_handle);
4086 } else {
4087 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
4088 }
4089 }
4090 }
4091 }
4092
4093 let remote_buffers = self.remote_id().zip(remote_buffers);
4094 let client = self.client.clone();
4095
4096 cx.spawn(move |this, mut cx| async move {
4097 let mut project_transaction = ProjectTransaction::default();
4098
4099 if let Some((project_id, remote_buffers)) = remote_buffers {
4100 let response = client
4101 .request(proto::ReloadBuffers {
4102 project_id,
4103 buffer_ids: remote_buffers
4104 .iter()
4105 .filter_map(|buffer| {
4106 buffer.update(&mut cx, |buffer, _| buffer.remote_id()).ok()
4107 })
4108 .collect(),
4109 })
4110 .await?
4111 .transaction
4112 .ok_or_else(|| anyhow!("missing transaction"))?;
4113 project_transaction = this
4114 .update(&mut cx, |this, cx| {
4115 this.deserialize_project_transaction(response, push_to_history, cx)
4116 })?
4117 .await?;
4118 }
4119
4120 for buffer in local_buffers {
4121 let transaction = buffer
4122 .update(&mut cx, |buffer, cx| buffer.reload(cx))?
4123 .await?;
4124 buffer.update(&mut cx, |buffer, cx| {
4125 if let Some(transaction) = transaction {
4126 if !push_to_history {
4127 buffer.forget_transaction(transaction.id);
4128 }
4129 project_transaction.0.insert(cx.handle(), transaction);
4130 }
4131 })?;
4132 }
4133
4134 Ok(project_transaction)
4135 })
4136 }
4137
4138 pub fn format(
4139 &mut self,
4140 buffers: HashSet<Model<Buffer>>,
4141 push_to_history: bool,
4142 trigger: FormatTrigger,
4143 cx: &mut ModelContext<Project>,
4144 ) -> Task<anyhow::Result<ProjectTransaction>> {
4145 if self.is_local() {
4146 let mut buffers_with_paths_and_servers = buffers
4147 .into_iter()
4148 .filter_map(|buffer_handle| {
4149 let buffer = buffer_handle.read(cx);
4150 let file = File::from_dyn(buffer.file())?;
4151 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
4152 let server = self
4153 .primary_language_server_for_buffer(buffer, cx)
4154 .map(|s| s.1.clone());
4155 Some((buffer_handle, buffer_abs_path, server))
4156 })
4157 .collect::<Vec<_>>();
4158
4159 cx.spawn(move |project, mut cx| async move {
4160 // Do not allow multiple concurrent formatting requests for the
4161 // same buffer.
4162 project.update(&mut cx, |this, cx| {
4163 buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
4164 this.buffers_being_formatted
4165 .insert(buffer.read(cx).remote_id())
4166 });
4167 })?;
4168
4169 let _cleanup = defer({
4170 let this = project.clone();
4171 let mut cx = cx.clone();
4172 let buffers = &buffers_with_paths_and_servers;
4173 move || {
4174 this.update(&mut cx, |this, cx| {
4175 for (buffer, _, _) in buffers {
4176 this.buffers_being_formatted
4177 .remove(&buffer.read(cx).remote_id());
4178 }
4179 })
4180 .ok();
4181 }
4182 });
4183
4184 let mut project_transaction = ProjectTransaction::default();
4185 for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
4186 let settings = buffer.update(&mut cx, |buffer, cx| {
4187 language_settings(buffer.language(), buffer.file(), cx).clone()
4188 })?;
4189
4190 let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
4191 let ensure_final_newline = settings.ensure_final_newline_on_save;
4192 let tab_size = settings.tab_size;
4193
4194 // First, format buffer's whitespace according to the settings.
4195 let trailing_whitespace_diff = if remove_trailing_whitespace {
4196 Some(
4197 buffer
4198 .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
4199 .await,
4200 )
4201 } else {
4202 None
4203 };
4204 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
4205 buffer.finalize_last_transaction();
4206 buffer.start_transaction();
4207 if let Some(diff) = trailing_whitespace_diff {
4208 buffer.apply_diff(diff, cx);
4209 }
4210 if ensure_final_newline {
4211 buffer.ensure_final_newline(cx);
4212 }
4213 buffer.end_transaction(cx)
4214 })?;
4215
4216 // Apply language-specific formatting using either a language server
4217 // or external command.
4218 let mut format_operation = None;
4219 match (&settings.formatter, &settings.format_on_save) {
4220 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4221
4222 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4223 | (_, FormatOnSave::LanguageServer) => {
4224 if let Some((language_server, buffer_abs_path)) =
4225 language_server.as_ref().zip(buffer_abs_path.as_ref())
4226 {
4227 format_operation = Some(FormatOperation::Lsp(
4228 Self::format_via_lsp(
4229 &project,
4230 buffer,
4231 buffer_abs_path,
4232 language_server,
4233 tab_size,
4234 &mut cx,
4235 )
4236 .await
4237 .context("failed to format via language server")?,
4238 ));
4239 }
4240 }
4241
4242 (
4243 Formatter::External { command, arguments },
4244 FormatOnSave::On | FormatOnSave::Off,
4245 )
4246 | (_, FormatOnSave::External { command, arguments }) => {
4247 if let Some(buffer_abs_path) = buffer_abs_path {
4248 format_operation = Self::format_via_external_command(
4249 buffer,
4250 buffer_abs_path,
4251 command,
4252 arguments,
4253 &mut cx,
4254 )
4255 .await
4256 .context(format!(
4257 "failed to format via external command {:?}",
4258 command
4259 ))?
4260 .map(FormatOperation::External);
4261 }
4262 }
4263 (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4264 if let Some(new_operation) =
4265 prettier_support::format_with_prettier(&project, buffer, &mut cx)
4266 .await
4267 {
4268 format_operation = Some(new_operation);
4269 } else if let Some((language_server, buffer_abs_path)) =
4270 language_server.as_ref().zip(buffer_abs_path.as_ref())
4271 {
4272 format_operation = Some(FormatOperation::Lsp(
4273 Self::format_via_lsp(
4274 &project,
4275 buffer,
4276 buffer_abs_path,
4277 language_server,
4278 tab_size,
4279 &mut cx,
4280 )
4281 .await
4282 .context("failed to format via language server")?,
4283 ));
4284 }
4285 }
4286 (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
4287 if let Some(new_operation) =
4288 prettier_support::format_with_prettier(&project, buffer, &mut cx)
4289 .await
4290 {
4291 format_operation = Some(new_operation);
4292 }
4293 }
4294 };
4295
4296 buffer.update(&mut cx, |b, cx| {
4297 // If the buffer had its whitespace formatted and was edited while the language-specific
4298 // formatting was being computed, avoid applying the language-specific formatting, because
4299 // it can't be grouped with the whitespace formatting in the undo history.
4300 if let Some(transaction_id) = whitespace_transaction_id {
4301 if b.peek_undo_stack()
4302 .map_or(true, |e| e.transaction_id() != transaction_id)
4303 {
4304 format_operation.take();
4305 }
4306 }
4307
4308 // Apply any language-specific formatting, and group the two formatting operations
4309 // in the buffer's undo history.
4310 if let Some(operation) = format_operation {
4311 match operation {
4312 FormatOperation::Lsp(edits) => {
4313 b.edit(edits, None, cx);
4314 }
4315 FormatOperation::External(diff) => {
4316 b.apply_diff(diff, cx);
4317 }
4318 FormatOperation::Prettier(diff) => {
4319 b.apply_diff(diff, cx);
4320 }
4321 }
4322
4323 if let Some(transaction_id) = whitespace_transaction_id {
4324 b.group_until_transaction(transaction_id);
4325 }
4326 }
4327
4328 if let Some(transaction) = b.finalize_last_transaction().cloned() {
4329 if !push_to_history {
4330 b.forget_transaction(transaction.id);
4331 }
4332 project_transaction.0.insert(buffer.clone(), transaction);
4333 }
4334 })?;
4335 }
4336
4337 Ok(project_transaction)
4338 })
4339 } else {
4340 let remote_id = self.remote_id();
4341 let client = self.client.clone();
4342 cx.spawn(move |this, mut cx| async move {
4343 let mut project_transaction = ProjectTransaction::default();
4344 if let Some(project_id) = remote_id {
4345 let response = client
4346 .request(proto::FormatBuffers {
4347 project_id,
4348 trigger: trigger as i32,
4349 buffer_ids: buffers
4350 .iter()
4351 .map(|buffer| {
4352 buffer.update(&mut cx, |buffer, _| buffer.remote_id())
4353 })
4354 .collect::<Result<_>>()?,
4355 })
4356 .await?
4357 .transaction
4358 .ok_or_else(|| anyhow!("missing transaction"))?;
4359 project_transaction = this
4360 .update(&mut cx, |this, cx| {
4361 this.deserialize_project_transaction(response, push_to_history, cx)
4362 })?
4363 .await?;
4364 }
4365 Ok(project_transaction)
4366 })
4367 }
4368 }
4369
4370 async fn format_via_lsp(
4371 this: &WeakModel<Self>,
4372 buffer: &Model<Buffer>,
4373 abs_path: &Path,
4374 language_server: &Arc<LanguageServer>,
4375 tab_size: NonZeroU32,
4376 cx: &mut AsyncAppContext,
4377 ) -> Result<Vec<(Range<Anchor>, String)>> {
4378 let uri = lsp::Url::from_file_path(abs_path)
4379 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4380 let text_document = lsp::TextDocumentIdentifier::new(uri);
4381 let capabilities = &language_server.capabilities();
4382
4383 let formatting_provider = capabilities.document_formatting_provider.as_ref();
4384 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4385
4386 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4387 language_server
4388 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4389 text_document,
4390 options: lsp_command::lsp_formatting_options(tab_size.get()),
4391 work_done_progress_params: Default::default(),
4392 })
4393 .await?
4394 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4395 let buffer_start = lsp::Position::new(0, 0);
4396 let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
4397
4398 language_server
4399 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4400 text_document,
4401 range: lsp::Range::new(buffer_start, buffer_end),
4402 options: lsp_command::lsp_formatting_options(tab_size.get()),
4403 work_done_progress_params: Default::default(),
4404 })
4405 .await?
4406 } else {
4407 None
4408 };
4409
4410 if let Some(lsp_edits) = lsp_edits {
4411 this.update(cx, |this, cx| {
4412 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4413 })?
4414 .await
4415 } else {
4416 Ok(Vec::new())
4417 }
4418 }
4419
4420 async fn format_via_external_command(
4421 buffer: &Model<Buffer>,
4422 buffer_abs_path: &Path,
4423 command: &str,
4424 arguments: &[String],
4425 cx: &mut AsyncAppContext,
4426 ) -> Result<Option<Diff>> {
4427 let working_dir_path = buffer.update(cx, |buffer, cx| {
4428 let file = File::from_dyn(buffer.file())?;
4429 let worktree = file.worktree.read(cx).as_local()?;
4430 let mut worktree_path = worktree.abs_path().to_path_buf();
4431 if worktree.root_entry()?.is_file() {
4432 worktree_path.pop();
4433 }
4434 Some(worktree_path)
4435 })?;
4436
4437 if let Some(working_dir_path) = working_dir_path {
4438 let mut child =
4439 smol::process::Command::new(command)
4440 .args(arguments.iter().map(|arg| {
4441 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4442 }))
4443 .current_dir(&working_dir_path)
4444 .stdin(smol::process::Stdio::piped())
4445 .stdout(smol::process::Stdio::piped())
4446 .stderr(smol::process::Stdio::piped())
4447 .spawn()?;
4448 let stdin = child
4449 .stdin
4450 .as_mut()
4451 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4452 let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
4453 for chunk in text.chunks() {
4454 stdin.write_all(chunk.as_bytes()).await?;
4455 }
4456 stdin.flush().await?;
4457
4458 let output = child.output().await?;
4459 if !output.status.success() {
4460 return Err(anyhow!(
4461 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4462 output.status.code(),
4463 String::from_utf8_lossy(&output.stdout),
4464 String::from_utf8_lossy(&output.stderr),
4465 ));
4466 }
4467
4468 let stdout = String::from_utf8(output.stdout)?;
4469 Ok(Some(
4470 buffer
4471 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
4472 .await,
4473 ))
4474 } else {
4475 Ok(None)
4476 }
4477 }
4478
4479 pub fn definition<T: ToPointUtf16>(
4480 &self,
4481 buffer: &Model<Buffer>,
4482 position: T,
4483 cx: &mut ModelContext<Self>,
4484 ) -> Task<Result<Vec<LocationLink>>> {
4485 let position = position.to_point_utf16(buffer.read(cx));
4486 self.request_lsp(
4487 buffer.clone(),
4488 LanguageServerToQuery::Primary,
4489 GetDefinition { position },
4490 cx,
4491 )
4492 }
4493
4494 pub fn type_definition<T: ToPointUtf16>(
4495 &self,
4496 buffer: &Model<Buffer>,
4497 position: T,
4498 cx: &mut ModelContext<Self>,
4499 ) -> Task<Result<Vec<LocationLink>>> {
4500 let position = position.to_point_utf16(buffer.read(cx));
4501 self.request_lsp(
4502 buffer.clone(),
4503 LanguageServerToQuery::Primary,
4504 GetTypeDefinition { position },
4505 cx,
4506 )
4507 }
4508
4509 pub fn references<T: ToPointUtf16>(
4510 &self,
4511 buffer: &Model<Buffer>,
4512 position: T,
4513 cx: &mut ModelContext<Self>,
4514 ) -> Task<Result<Vec<Location>>> {
4515 let position = position.to_point_utf16(buffer.read(cx));
4516 self.request_lsp(
4517 buffer.clone(),
4518 LanguageServerToQuery::Primary,
4519 GetReferences { position },
4520 cx,
4521 )
4522 }
4523
4524 pub fn document_highlights<T: ToPointUtf16>(
4525 &self,
4526 buffer: &Model<Buffer>,
4527 position: T,
4528 cx: &mut ModelContext<Self>,
4529 ) -> Task<Result<Vec<DocumentHighlight>>> {
4530 let position = position.to_point_utf16(buffer.read(cx));
4531 self.request_lsp(
4532 buffer.clone(),
4533 LanguageServerToQuery::Primary,
4534 GetDocumentHighlights { position },
4535 cx,
4536 )
4537 }
4538
4539 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4540 if self.is_local() {
4541 let mut requests = Vec::new();
4542 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4543 let worktree_id = *worktree_id;
4544 let worktree_handle = self.worktree_for_id(worktree_id, cx);
4545 let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4546 Some(worktree) => worktree,
4547 None => continue,
4548 };
4549 let worktree_abs_path = worktree.abs_path().clone();
4550
4551 let (adapter, language, server) = match self.language_servers.get(server_id) {
4552 Some(LanguageServerState::Running {
4553 adapter,
4554 language,
4555 server,
4556 ..
4557 }) => (adapter.clone(), language.clone(), server),
4558
4559 _ => continue,
4560 };
4561
4562 requests.push(
4563 server
4564 .request::<lsp::request::WorkspaceSymbolRequest>(
4565 lsp::WorkspaceSymbolParams {
4566 query: query.to_string(),
4567 ..Default::default()
4568 },
4569 )
4570 .log_err()
4571 .map(move |response| {
4572 let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4573 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4574 flat_responses.into_iter().map(|lsp_symbol| {
4575 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4576 }).collect::<Vec<_>>()
4577 }
4578 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4579 nested_responses.into_iter().filter_map(|lsp_symbol| {
4580 let location = match lsp_symbol.location {
4581 OneOf::Left(location) => location,
4582 OneOf::Right(_) => {
4583 error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4584 return None
4585 }
4586 };
4587 Some((lsp_symbol.name, lsp_symbol.kind, location))
4588 }).collect::<Vec<_>>()
4589 }
4590 }).unwrap_or_default();
4591
4592 (
4593 adapter,
4594 language,
4595 worktree_id,
4596 worktree_abs_path,
4597 lsp_symbols,
4598 )
4599 }),
4600 );
4601 }
4602
4603 cx.spawn(move |this, mut cx| async move {
4604 let responses = futures::future::join_all(requests).await;
4605 let this = match this.upgrade() {
4606 Some(this) => this,
4607 None => return Ok(Vec::new()),
4608 };
4609
4610 let symbols = this.update(&mut cx, |this, cx| {
4611 let mut symbols = Vec::new();
4612 for (
4613 adapter,
4614 adapter_language,
4615 source_worktree_id,
4616 worktree_abs_path,
4617 lsp_symbols,
4618 ) in responses
4619 {
4620 symbols.extend(lsp_symbols.into_iter().filter_map(
4621 |(symbol_name, symbol_kind, symbol_location)| {
4622 let abs_path = symbol_location.uri.to_file_path().ok()?;
4623 let mut worktree_id = source_worktree_id;
4624 let path;
4625 if let Some((worktree, rel_path)) =
4626 this.find_local_worktree(&abs_path, cx)
4627 {
4628 worktree_id = worktree.read(cx).id();
4629 path = rel_path;
4630 } else {
4631 path = relativize_path(&worktree_abs_path, &abs_path);
4632 }
4633
4634 let project_path = ProjectPath {
4635 worktree_id,
4636 path: path.into(),
4637 };
4638 let signature = this.symbol_signature(&project_path);
4639 let adapter_language = adapter_language.clone();
4640 let language = this
4641 .languages
4642 .language_for_file(&project_path.path, None)
4643 .unwrap_or_else(move |_| adapter_language);
4644 let language_server_name = adapter.name.clone();
4645 Some(async move {
4646 let language = language.await;
4647 let label =
4648 language.label_for_symbol(&symbol_name, symbol_kind).await;
4649
4650 Symbol {
4651 language_server_name,
4652 source_worktree_id,
4653 path: project_path,
4654 label: label.unwrap_or_else(|| {
4655 CodeLabel::plain(symbol_name.clone(), None)
4656 }),
4657 kind: symbol_kind,
4658 name: symbol_name,
4659 range: range_from_lsp(symbol_location.range),
4660 signature,
4661 }
4662 })
4663 },
4664 ));
4665 }
4666
4667 symbols
4668 })?;
4669
4670 Ok(futures::future::join_all(symbols).await)
4671 })
4672 } else if let Some(project_id) = self.remote_id() {
4673 let request = self.client.request(proto::GetProjectSymbols {
4674 project_id,
4675 query: query.to_string(),
4676 });
4677 cx.spawn(move |this, mut cx| async move {
4678 let response = request.await?;
4679 let mut symbols = Vec::new();
4680 if let Some(this) = this.upgrade() {
4681 let new_symbols = this.update(&mut cx, |this, _| {
4682 response
4683 .symbols
4684 .into_iter()
4685 .map(|symbol| this.deserialize_symbol(symbol))
4686 .collect::<Vec<_>>()
4687 })?;
4688 symbols = futures::future::join_all(new_symbols)
4689 .await
4690 .into_iter()
4691 .filter_map(|symbol| symbol.log_err())
4692 .collect::<Vec<_>>();
4693 }
4694 Ok(symbols)
4695 })
4696 } else {
4697 Task::ready(Ok(Default::default()))
4698 }
4699 }
4700
4701 pub fn open_buffer_for_symbol(
4702 &mut self,
4703 symbol: &Symbol,
4704 cx: &mut ModelContext<Self>,
4705 ) -> Task<Result<Model<Buffer>>> {
4706 if self.is_local() {
4707 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4708 symbol.source_worktree_id,
4709 symbol.language_server_name.clone(),
4710 )) {
4711 *id
4712 } else {
4713 return Task::ready(Err(anyhow!(
4714 "language server for worktree and language not found"
4715 )));
4716 };
4717
4718 let worktree_abs_path = if let Some(worktree_abs_path) = self
4719 .worktree_for_id(symbol.path.worktree_id, cx)
4720 .and_then(|worktree| worktree.read(cx).as_local())
4721 .map(|local_worktree| local_worktree.abs_path())
4722 {
4723 worktree_abs_path
4724 } else {
4725 return Task::ready(Err(anyhow!("worktree not found for symbol")));
4726 };
4727
4728 let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
4729 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4730 uri
4731 } else {
4732 return Task::ready(Err(anyhow!("invalid symbol path")));
4733 };
4734
4735 self.open_local_buffer_via_lsp(
4736 symbol_uri,
4737 language_server_id,
4738 symbol.language_server_name.clone(),
4739 cx,
4740 )
4741 } else if let Some(project_id) = self.remote_id() {
4742 let request = self.client.request(proto::OpenBufferForSymbol {
4743 project_id,
4744 symbol: Some(serialize_symbol(symbol)),
4745 });
4746 cx.spawn(move |this, mut cx| async move {
4747 let response = request.await?;
4748 this.update(&mut cx, |this, cx| {
4749 this.wait_for_remote_buffer(response.buffer_id, cx)
4750 })?
4751 .await
4752 })
4753 } else {
4754 Task::ready(Err(anyhow!("project does not have a remote id")))
4755 }
4756 }
4757
4758 pub fn hover<T: ToPointUtf16>(
4759 &self,
4760 buffer: &Model<Buffer>,
4761 position: T,
4762 cx: &mut ModelContext<Self>,
4763 ) -> Task<Result<Option<Hover>>> {
4764 let position = position.to_point_utf16(buffer.read(cx));
4765 self.request_lsp(
4766 buffer.clone(),
4767 LanguageServerToQuery::Primary,
4768 GetHover { position },
4769 cx,
4770 )
4771 }
4772
4773 pub fn completions<T: ToOffset + ToPointUtf16>(
4774 &self,
4775 buffer: &Model<Buffer>,
4776 position: T,
4777 cx: &mut ModelContext<Self>,
4778 ) -> Task<Result<Vec<Completion>>> {
4779 let position = position.to_point_utf16(buffer.read(cx));
4780 if self.is_local() {
4781 let snapshot = buffer.read(cx).snapshot();
4782 let offset = position.to_offset(&snapshot);
4783 let scope = snapshot.language_scope_at(offset);
4784
4785 let server_ids: Vec<_> = self
4786 .language_servers_for_buffer(buffer.read(cx), cx)
4787 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4788 .filter(|(adapter, _)| {
4789 scope
4790 .as_ref()
4791 .map(|scope| scope.language_allowed(&adapter.name))
4792 .unwrap_or(true)
4793 })
4794 .map(|(_, server)| server.server_id())
4795 .collect();
4796
4797 let buffer = buffer.clone();
4798 cx.spawn(move |this, mut cx| async move {
4799 let mut tasks = Vec::with_capacity(server_ids.len());
4800 this.update(&mut cx, |this, cx| {
4801 for server_id in server_ids {
4802 tasks.push(this.request_lsp(
4803 buffer.clone(),
4804 LanguageServerToQuery::Other(server_id),
4805 GetCompletions { position },
4806 cx,
4807 ));
4808 }
4809 })?;
4810
4811 let mut completions = Vec::new();
4812 for task in tasks {
4813 if let Ok(new_completions) = task.await {
4814 completions.extend_from_slice(&new_completions);
4815 }
4816 }
4817
4818 Ok(completions)
4819 })
4820 } else if let Some(project_id) = self.remote_id() {
4821 self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4822 } else {
4823 Task::ready(Ok(Default::default()))
4824 }
4825 }
4826
4827 pub fn resolve_completions(
4828 &self,
4829 completion_indices: Vec<usize>,
4830 completions: Arc<RwLock<Box<[Completion]>>>,
4831 cx: &mut ModelContext<Self>,
4832 ) -> Task<Result<bool>> {
4833 let client = self.client();
4834 let language_registry = self.languages().clone();
4835
4836 let is_remote = self.is_remote();
4837 let project_id = self.remote_id();
4838
4839 cx.spawn(move |this, mut cx| async move {
4840 let mut did_resolve = false;
4841 if is_remote {
4842 let project_id =
4843 project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
4844
4845 for completion_index in completion_indices {
4846 let completions_guard = completions.read();
4847 let completion = &completions_guard[completion_index];
4848 if completion.documentation.is_some() {
4849 continue;
4850 }
4851
4852 did_resolve = true;
4853 let server_id = completion.server_id;
4854 let completion = completion.lsp_completion.clone();
4855 drop(completions_guard);
4856
4857 Self::resolve_completion_documentation_remote(
4858 project_id,
4859 server_id,
4860 completions.clone(),
4861 completion_index,
4862 completion,
4863 client.clone(),
4864 language_registry.clone(),
4865 )
4866 .await;
4867 }
4868 } else {
4869 for completion_index in completion_indices {
4870 let completions_guard = completions.read();
4871 let completion = &completions_guard[completion_index];
4872 if completion.documentation.is_some() {
4873 continue;
4874 }
4875
4876 let server_id = completion.server_id;
4877 let completion = completion.lsp_completion.clone();
4878 drop(completions_guard);
4879
4880 let server = this
4881 .read_with(&mut cx, |project, _| {
4882 project.language_server_for_id(server_id)
4883 })
4884 .ok()
4885 .flatten();
4886 let Some(server) = server else {
4887 continue;
4888 };
4889
4890 did_resolve = true;
4891 Self::resolve_completion_documentation_local(
4892 server,
4893 completions.clone(),
4894 completion_index,
4895 completion,
4896 language_registry.clone(),
4897 )
4898 .await;
4899 }
4900 }
4901
4902 Ok(did_resolve)
4903 })
4904 }
4905
4906 async fn resolve_completion_documentation_local(
4907 server: Arc<lsp::LanguageServer>,
4908 completions: Arc<RwLock<Box<[Completion]>>>,
4909 completion_index: usize,
4910 completion: lsp::CompletionItem,
4911 language_registry: Arc<LanguageRegistry>,
4912 ) {
4913 let can_resolve = server
4914 .capabilities()
4915 .completion_provider
4916 .as_ref()
4917 .and_then(|options| options.resolve_provider)
4918 .unwrap_or(false);
4919 if !can_resolve {
4920 return;
4921 }
4922
4923 let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
4924 let Some(completion_item) = request.await.log_err() else {
4925 return;
4926 };
4927
4928 if let Some(lsp_documentation) = completion_item.documentation {
4929 let documentation = language::prepare_completion_documentation(
4930 &lsp_documentation,
4931 &language_registry,
4932 None, // TODO: Try to reasonably work out which language the completion is for
4933 )
4934 .await;
4935
4936 let mut completions = completions.write();
4937 let completion = &mut completions[completion_index];
4938 completion.documentation = Some(documentation);
4939 } else {
4940 let mut completions = completions.write();
4941 let completion = &mut completions[completion_index];
4942 completion.documentation = Some(Documentation::Undocumented);
4943 }
4944 }
4945
4946 async fn resolve_completion_documentation_remote(
4947 project_id: u64,
4948 server_id: LanguageServerId,
4949 completions: Arc<RwLock<Box<[Completion]>>>,
4950 completion_index: usize,
4951 completion: lsp::CompletionItem,
4952 client: Arc<Client>,
4953 language_registry: Arc<LanguageRegistry>,
4954 ) {
4955 let request = proto::ResolveCompletionDocumentation {
4956 project_id,
4957 language_server_id: server_id.0 as u64,
4958 lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
4959 };
4960
4961 let Some(response) = client
4962 .request(request)
4963 .await
4964 .context("completion documentation resolve proto request")
4965 .log_err()
4966 else {
4967 return;
4968 };
4969
4970 if response.text.is_empty() {
4971 let mut completions = completions.write();
4972 let completion = &mut completions[completion_index];
4973 completion.documentation = Some(Documentation::Undocumented);
4974 }
4975
4976 let documentation = if response.is_markdown {
4977 Documentation::MultiLineMarkdown(
4978 markdown::parse_markdown(&response.text, &language_registry, None).await,
4979 )
4980 } else if response.text.lines().count() <= 1 {
4981 Documentation::SingleLine(response.text)
4982 } else {
4983 Documentation::MultiLinePlainText(response.text)
4984 };
4985
4986 let mut completions = completions.write();
4987 let completion = &mut completions[completion_index];
4988 completion.documentation = Some(documentation);
4989 }
4990
4991 pub fn apply_additional_edits_for_completion(
4992 &self,
4993 buffer_handle: Model<Buffer>,
4994 completion: Completion,
4995 push_to_history: bool,
4996 cx: &mut ModelContext<Self>,
4997 ) -> Task<Result<Option<Transaction>>> {
4998 let buffer = buffer_handle.read(cx);
4999 let buffer_id = buffer.remote_id();
5000
5001 if self.is_local() {
5002 let server_id = completion.server_id;
5003 let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
5004 Some((_, server)) => server.clone(),
5005 _ => return Task::ready(Ok(Default::default())),
5006 };
5007
5008 cx.spawn(move |this, mut cx| async move {
5009 let can_resolve = lang_server
5010 .capabilities()
5011 .completion_provider
5012 .as_ref()
5013 .and_then(|options| options.resolve_provider)
5014 .unwrap_or(false);
5015 let additional_text_edits = if can_resolve {
5016 lang_server
5017 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
5018 .await?
5019 .additional_text_edits
5020 } else {
5021 completion.lsp_completion.additional_text_edits
5022 };
5023 if let Some(edits) = additional_text_edits {
5024 let edits = this
5025 .update(&mut cx, |this, cx| {
5026 this.edits_from_lsp(
5027 &buffer_handle,
5028 edits,
5029 lang_server.server_id(),
5030 None,
5031 cx,
5032 )
5033 })?
5034 .await?;
5035
5036 buffer_handle.update(&mut cx, |buffer, cx| {
5037 buffer.finalize_last_transaction();
5038 buffer.start_transaction();
5039
5040 for (range, text) in edits {
5041 let primary = &completion.old_range;
5042 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5043 && primary.end.cmp(&range.start, buffer).is_ge();
5044 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5045 && range.end.cmp(&primary.end, buffer).is_ge();
5046
5047 //Skip additional edits which overlap with the primary completion edit
5048 //https://github.com/zed-industries/zed/pull/1871
5049 if !start_within && !end_within {
5050 buffer.edit([(range, text)], None, cx);
5051 }
5052 }
5053
5054 let transaction = if buffer.end_transaction(cx).is_some() {
5055 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5056 if !push_to_history {
5057 buffer.forget_transaction(transaction.id);
5058 }
5059 Some(transaction)
5060 } else {
5061 None
5062 };
5063 Ok(transaction)
5064 })?
5065 } else {
5066 Ok(None)
5067 }
5068 })
5069 } else if let Some(project_id) = self.remote_id() {
5070 let client = self.client.clone();
5071 cx.spawn(move |_, mut cx| async move {
5072 let response = client
5073 .request(proto::ApplyCompletionAdditionalEdits {
5074 project_id,
5075 buffer_id,
5076 completion: Some(language::proto::serialize_completion(&completion)),
5077 })
5078 .await?;
5079
5080 if let Some(transaction) = response.transaction {
5081 let transaction = language::proto::deserialize_transaction(transaction)?;
5082 buffer_handle
5083 .update(&mut cx, |buffer, _| {
5084 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5085 })?
5086 .await?;
5087 if push_to_history {
5088 buffer_handle.update(&mut cx, |buffer, _| {
5089 buffer.push_transaction(transaction.clone(), Instant::now());
5090 })?;
5091 }
5092 Ok(Some(transaction))
5093 } else {
5094 Ok(None)
5095 }
5096 })
5097 } else {
5098 Task::ready(Err(anyhow!("project does not have a remote id")))
5099 }
5100 }
5101
5102 pub fn code_actions<T: Clone + ToOffset>(
5103 &self,
5104 buffer_handle: &Model<Buffer>,
5105 range: Range<T>,
5106 cx: &mut ModelContext<Self>,
5107 ) -> Task<Result<Vec<CodeAction>>> {
5108 let buffer = buffer_handle.read(cx);
5109 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5110 self.request_lsp(
5111 buffer_handle.clone(),
5112 LanguageServerToQuery::Primary,
5113 GetCodeActions { range },
5114 cx,
5115 )
5116 }
5117
5118 pub fn apply_code_action(
5119 &self,
5120 buffer_handle: Model<Buffer>,
5121 mut action: CodeAction,
5122 push_to_history: bool,
5123 cx: &mut ModelContext<Self>,
5124 ) -> Task<Result<ProjectTransaction>> {
5125 if self.is_local() {
5126 let buffer = buffer_handle.read(cx);
5127 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
5128 self.language_server_for_buffer(buffer, action.server_id, cx)
5129 {
5130 (adapter.clone(), server.clone())
5131 } else {
5132 return Task::ready(Ok(Default::default()));
5133 };
5134 let range = action.range.to_point_utf16(buffer);
5135
5136 cx.spawn(move |this, mut cx| async move {
5137 if let Some(lsp_range) = action
5138 .lsp_action
5139 .data
5140 .as_mut()
5141 .and_then(|d| d.get_mut("codeActionParams"))
5142 .and_then(|d| d.get_mut("range"))
5143 {
5144 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
5145 action.lsp_action = lang_server
5146 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
5147 .await?;
5148 } else {
5149 let actions = this
5150 .update(&mut cx, |this, cx| {
5151 this.code_actions(&buffer_handle, action.range, cx)
5152 })?
5153 .await?;
5154 action.lsp_action = actions
5155 .into_iter()
5156 .find(|a| a.lsp_action.title == action.lsp_action.title)
5157 .ok_or_else(|| anyhow!("code action is outdated"))?
5158 .lsp_action;
5159 }
5160
5161 if let Some(edit) = action.lsp_action.edit {
5162 if edit.changes.is_some() || edit.document_changes.is_some() {
5163 return Self::deserialize_workspace_edit(
5164 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5165 edit,
5166 push_to_history,
5167 lsp_adapter.clone(),
5168 lang_server.clone(),
5169 &mut cx,
5170 )
5171 .await;
5172 }
5173 }
5174
5175 if let Some(command) = action.lsp_action.command {
5176 this.update(&mut cx, |this, _| {
5177 this.last_workspace_edits_by_language_server
5178 .remove(&lang_server.server_id());
5179 })?;
5180
5181 let result = lang_server
5182 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5183 command: command.command,
5184 arguments: command.arguments.unwrap_or_default(),
5185 ..Default::default()
5186 })
5187 .await;
5188
5189 if let Err(err) = result {
5190 // TODO: LSP ERROR
5191 return Err(err);
5192 }
5193
5194 return Ok(this.update(&mut cx, |this, _| {
5195 this.last_workspace_edits_by_language_server
5196 .remove(&lang_server.server_id())
5197 .unwrap_or_default()
5198 })?);
5199 }
5200
5201 Ok(ProjectTransaction::default())
5202 })
5203 } else if let Some(project_id) = self.remote_id() {
5204 let client = self.client.clone();
5205 let request = proto::ApplyCodeAction {
5206 project_id,
5207 buffer_id: buffer_handle.read(cx).remote_id(),
5208 action: Some(language::proto::serialize_code_action(&action)),
5209 };
5210 cx.spawn(move |this, mut cx| async move {
5211 let response = client
5212 .request(request)
5213 .await?
5214 .transaction
5215 .ok_or_else(|| anyhow!("missing transaction"))?;
5216 this.update(&mut cx, |this, cx| {
5217 this.deserialize_project_transaction(response, push_to_history, cx)
5218 })?
5219 .await
5220 })
5221 } else {
5222 Task::ready(Err(anyhow!("project does not have a remote id")))
5223 }
5224 }
5225
5226 fn apply_on_type_formatting(
5227 &self,
5228 buffer: Model<Buffer>,
5229 position: Anchor,
5230 trigger: String,
5231 cx: &mut ModelContext<Self>,
5232 ) -> Task<Result<Option<Transaction>>> {
5233 if self.is_local() {
5234 cx.spawn(move |this, mut cx| async move {
5235 // Do not allow multiple concurrent formatting requests for the
5236 // same buffer.
5237 this.update(&mut cx, |this, cx| {
5238 this.buffers_being_formatted
5239 .insert(buffer.read(cx).remote_id())
5240 })?;
5241
5242 let _cleanup = defer({
5243 let this = this.clone();
5244 let mut cx = cx.clone();
5245 let closure_buffer = buffer.clone();
5246 move || {
5247 this.update(&mut cx, |this, cx| {
5248 this.buffers_being_formatted
5249 .remove(&closure_buffer.read(cx).remote_id());
5250 })
5251 .ok();
5252 }
5253 });
5254
5255 buffer
5256 .update(&mut cx, |buffer, _| {
5257 buffer.wait_for_edits(Some(position.timestamp))
5258 })?
5259 .await?;
5260 this.update(&mut cx, |this, cx| {
5261 let position = position.to_point_utf16(buffer.read(cx));
5262 this.on_type_format(buffer, position, trigger, false, cx)
5263 })?
5264 .await
5265 })
5266 } else if let Some(project_id) = self.remote_id() {
5267 let client = self.client.clone();
5268 let request = proto::OnTypeFormatting {
5269 project_id,
5270 buffer_id: buffer.read(cx).remote_id(),
5271 position: Some(serialize_anchor(&position)),
5272 trigger,
5273 version: serialize_version(&buffer.read(cx).version()),
5274 };
5275 cx.spawn(move |_, _| async move {
5276 client
5277 .request(request)
5278 .await?
5279 .transaction
5280 .map(language::proto::deserialize_transaction)
5281 .transpose()
5282 })
5283 } else {
5284 Task::ready(Err(anyhow!("project does not have a remote id")))
5285 }
5286 }
5287
5288 async fn deserialize_edits(
5289 this: Model<Self>,
5290 buffer_to_edit: Model<Buffer>,
5291 edits: Vec<lsp::TextEdit>,
5292 push_to_history: bool,
5293 _: Arc<CachedLspAdapter>,
5294 language_server: Arc<LanguageServer>,
5295 cx: &mut AsyncAppContext,
5296 ) -> Result<Option<Transaction>> {
5297 let edits = this
5298 .update(cx, |this, cx| {
5299 this.edits_from_lsp(
5300 &buffer_to_edit,
5301 edits,
5302 language_server.server_id(),
5303 None,
5304 cx,
5305 )
5306 })?
5307 .await?;
5308
5309 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5310 buffer.finalize_last_transaction();
5311 buffer.start_transaction();
5312 for (range, text) in edits {
5313 buffer.edit([(range, text)], None, cx);
5314 }
5315
5316 if buffer.end_transaction(cx).is_some() {
5317 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5318 if !push_to_history {
5319 buffer.forget_transaction(transaction.id);
5320 }
5321 Some(transaction)
5322 } else {
5323 None
5324 }
5325 })?;
5326
5327 Ok(transaction)
5328 }
5329
5330 async fn deserialize_workspace_edit(
5331 this: Model<Self>,
5332 edit: lsp::WorkspaceEdit,
5333 push_to_history: bool,
5334 lsp_adapter: Arc<CachedLspAdapter>,
5335 language_server: Arc<LanguageServer>,
5336 cx: &mut AsyncAppContext,
5337 ) -> Result<ProjectTransaction> {
5338 let fs = this.update(cx, |this, _| this.fs.clone())?;
5339 let mut operations = Vec::new();
5340 if let Some(document_changes) = edit.document_changes {
5341 match document_changes {
5342 lsp::DocumentChanges::Edits(edits) => {
5343 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5344 }
5345 lsp::DocumentChanges::Operations(ops) => operations = ops,
5346 }
5347 } else if let Some(changes) = edit.changes {
5348 operations.extend(changes.into_iter().map(|(uri, edits)| {
5349 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5350 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5351 uri,
5352 version: None,
5353 },
5354 edits: edits.into_iter().map(OneOf::Left).collect(),
5355 })
5356 }));
5357 }
5358
5359 let mut project_transaction = ProjectTransaction::default();
5360 for operation in operations {
5361 match operation {
5362 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5363 let abs_path = op
5364 .uri
5365 .to_file_path()
5366 .map_err(|_| anyhow!("can't convert URI to path"))?;
5367
5368 if let Some(parent_path) = abs_path.parent() {
5369 fs.create_dir(parent_path).await?;
5370 }
5371 if abs_path.ends_with("/") {
5372 fs.create_dir(&abs_path).await?;
5373 } else {
5374 fs.create_file(
5375 &abs_path,
5376 op.options
5377 .map(|options| fs::CreateOptions {
5378 overwrite: options.overwrite.unwrap_or(false),
5379 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5380 })
5381 .unwrap_or_default(),
5382 )
5383 .await?;
5384 }
5385 }
5386
5387 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5388 let source_abs_path = op
5389 .old_uri
5390 .to_file_path()
5391 .map_err(|_| anyhow!("can't convert URI to path"))?;
5392 let target_abs_path = op
5393 .new_uri
5394 .to_file_path()
5395 .map_err(|_| anyhow!("can't convert URI to path"))?;
5396 fs.rename(
5397 &source_abs_path,
5398 &target_abs_path,
5399 op.options
5400 .map(|options| fs::RenameOptions {
5401 overwrite: options.overwrite.unwrap_or(false),
5402 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5403 })
5404 .unwrap_or_default(),
5405 )
5406 .await?;
5407 }
5408
5409 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5410 let abs_path = op
5411 .uri
5412 .to_file_path()
5413 .map_err(|_| anyhow!("can't convert URI to path"))?;
5414 let options = op
5415 .options
5416 .map(|options| fs::RemoveOptions {
5417 recursive: options.recursive.unwrap_or(false),
5418 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5419 })
5420 .unwrap_or_default();
5421 if abs_path.ends_with("/") {
5422 fs.remove_dir(&abs_path, options).await?;
5423 } else {
5424 fs.remove_file(&abs_path, options).await?;
5425 }
5426 }
5427
5428 lsp::DocumentChangeOperation::Edit(op) => {
5429 let buffer_to_edit = this
5430 .update(cx, |this, cx| {
5431 this.open_local_buffer_via_lsp(
5432 op.text_document.uri,
5433 language_server.server_id(),
5434 lsp_adapter.name.clone(),
5435 cx,
5436 )
5437 })?
5438 .await?;
5439
5440 let edits = this
5441 .update(cx, |this, cx| {
5442 let edits = op.edits.into_iter().map(|edit| match edit {
5443 OneOf::Left(edit) => edit,
5444 OneOf::Right(edit) => edit.text_edit,
5445 });
5446 this.edits_from_lsp(
5447 &buffer_to_edit,
5448 edits,
5449 language_server.server_id(),
5450 op.text_document.version,
5451 cx,
5452 )
5453 })?
5454 .await?;
5455
5456 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5457 buffer.finalize_last_transaction();
5458 buffer.start_transaction();
5459 for (range, text) in edits {
5460 buffer.edit([(range, text)], None, cx);
5461 }
5462 let transaction = if buffer.end_transaction(cx).is_some() {
5463 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5464 if !push_to_history {
5465 buffer.forget_transaction(transaction.id);
5466 }
5467 Some(transaction)
5468 } else {
5469 None
5470 };
5471
5472 transaction
5473 })?;
5474 if let Some(transaction) = transaction {
5475 project_transaction.0.insert(buffer_to_edit, transaction);
5476 }
5477 }
5478 }
5479 }
5480
5481 Ok(project_transaction)
5482 }
5483
5484 pub fn prepare_rename<T: ToPointUtf16>(
5485 &self,
5486 buffer: Model<Buffer>,
5487 position: T,
5488 cx: &mut ModelContext<Self>,
5489 ) -> Task<Result<Option<Range<Anchor>>>> {
5490 let position = position.to_point_utf16(buffer.read(cx));
5491 self.request_lsp(
5492 buffer,
5493 LanguageServerToQuery::Primary,
5494 PrepareRename { position },
5495 cx,
5496 )
5497 }
5498
5499 pub fn perform_rename<T: ToPointUtf16>(
5500 &self,
5501 buffer: Model<Buffer>,
5502 position: T,
5503 new_name: String,
5504 push_to_history: bool,
5505 cx: &mut ModelContext<Self>,
5506 ) -> Task<Result<ProjectTransaction>> {
5507 let position = position.to_point_utf16(buffer.read(cx));
5508 self.request_lsp(
5509 buffer,
5510 LanguageServerToQuery::Primary,
5511 PerformRename {
5512 position,
5513 new_name,
5514 push_to_history,
5515 },
5516 cx,
5517 )
5518 }
5519
5520 pub fn on_type_format<T: ToPointUtf16>(
5521 &self,
5522 buffer: Model<Buffer>,
5523 position: T,
5524 trigger: String,
5525 push_to_history: bool,
5526 cx: &mut ModelContext<Self>,
5527 ) -> Task<Result<Option<Transaction>>> {
5528 let (position, tab_size) = buffer.update(cx, |buffer, cx| {
5529 let position = position.to_point_utf16(buffer);
5530 (
5531 position,
5532 language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
5533 .tab_size,
5534 )
5535 });
5536 self.request_lsp(
5537 buffer.clone(),
5538 LanguageServerToQuery::Primary,
5539 OnTypeFormatting {
5540 position,
5541 trigger,
5542 options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5543 push_to_history,
5544 },
5545 cx,
5546 )
5547 }
5548
5549 pub fn inlay_hints<T: ToOffset>(
5550 &self,
5551 buffer_handle: Model<Buffer>,
5552 range: Range<T>,
5553 cx: &mut ModelContext<Self>,
5554 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5555 let buffer = buffer_handle.read(cx);
5556 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5557 let range_start = range.start;
5558 let range_end = range.end;
5559 let buffer_id = buffer.remote_id();
5560 let buffer_version = buffer.version().clone();
5561 let lsp_request = InlayHints { range };
5562
5563 if self.is_local() {
5564 let lsp_request_task = self.request_lsp(
5565 buffer_handle.clone(),
5566 LanguageServerToQuery::Primary,
5567 lsp_request,
5568 cx,
5569 );
5570 cx.spawn(move |_, mut cx| async move {
5571 buffer_handle
5572 .update(&mut cx, |buffer, _| {
5573 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5574 })?
5575 .await
5576 .context("waiting for inlay hint request range edits")?;
5577 lsp_request_task.await.context("inlay hints LSP request")
5578 })
5579 } else if let Some(project_id) = self.remote_id() {
5580 let client = self.client.clone();
5581 let request = proto::InlayHints {
5582 project_id,
5583 buffer_id,
5584 start: Some(serialize_anchor(&range_start)),
5585 end: Some(serialize_anchor(&range_end)),
5586 version: serialize_version(&buffer_version),
5587 };
5588 cx.spawn(move |project, cx| async move {
5589 let response = client
5590 .request(request)
5591 .await
5592 .context("inlay hints proto request")?;
5593 let hints_request_result = LspCommand::response_from_proto(
5594 lsp_request,
5595 response,
5596 project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5597 buffer_handle.clone(),
5598 cx,
5599 )
5600 .await;
5601
5602 hints_request_result.context("inlay hints proto response conversion")
5603 })
5604 } else {
5605 Task::ready(Err(anyhow!("project does not have a remote id")))
5606 }
5607 }
5608
5609 pub fn resolve_inlay_hint(
5610 &self,
5611 hint: InlayHint,
5612 buffer_handle: Model<Buffer>,
5613 server_id: LanguageServerId,
5614 cx: &mut ModelContext<Self>,
5615 ) -> Task<anyhow::Result<InlayHint>> {
5616 if self.is_local() {
5617 let buffer = buffer_handle.read(cx);
5618 let (_, lang_server) = if let Some((adapter, server)) =
5619 self.language_server_for_buffer(buffer, server_id, cx)
5620 {
5621 (adapter.clone(), server.clone())
5622 } else {
5623 return Task::ready(Ok(hint));
5624 };
5625 if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5626 return Task::ready(Ok(hint));
5627 }
5628
5629 let buffer_snapshot = buffer.snapshot();
5630 cx.spawn(move |_, mut cx| async move {
5631 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5632 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5633 );
5634 let resolved_hint = resolve_task
5635 .await
5636 .context("inlay hint resolve LSP request")?;
5637 let resolved_hint = InlayHints::lsp_to_project_hint(
5638 resolved_hint,
5639 &buffer_handle,
5640 server_id,
5641 ResolveState::Resolved,
5642 false,
5643 &mut cx,
5644 )
5645 .await?;
5646 Ok(resolved_hint)
5647 })
5648 } else if let Some(project_id) = self.remote_id() {
5649 let client = self.client.clone();
5650 let request = proto::ResolveInlayHint {
5651 project_id,
5652 buffer_id: buffer_handle.read(cx).remote_id(),
5653 language_server_id: server_id.0 as u64,
5654 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5655 };
5656 cx.spawn(move |_, _| async move {
5657 let response = client
5658 .request(request)
5659 .await
5660 .context("inlay hints proto request")?;
5661 match response.hint {
5662 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5663 .context("inlay hints proto resolve response conversion"),
5664 None => Ok(hint),
5665 }
5666 })
5667 } else {
5668 Task::ready(Err(anyhow!("project does not have a remote id")))
5669 }
5670 }
5671
5672 #[allow(clippy::type_complexity)]
5673 pub fn search(
5674 &self,
5675 query: SearchQuery,
5676 cx: &mut ModelContext<Self>,
5677 ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5678 if self.is_local() {
5679 self.search_local(query, cx)
5680 } else if let Some(project_id) = self.remote_id() {
5681 let (tx, rx) = smol::channel::unbounded();
5682 let request = self.client.request(query.to_proto(project_id));
5683 cx.spawn(move |this, mut cx| async move {
5684 let response = request.await?;
5685 let mut result = HashMap::default();
5686 for location in response.locations {
5687 let target_buffer = this
5688 .update(&mut cx, |this, cx| {
5689 this.wait_for_remote_buffer(location.buffer_id, cx)
5690 })?
5691 .await?;
5692 let start = location
5693 .start
5694 .and_then(deserialize_anchor)
5695 .ok_or_else(|| anyhow!("missing target start"))?;
5696 let end = location
5697 .end
5698 .and_then(deserialize_anchor)
5699 .ok_or_else(|| anyhow!("missing target end"))?;
5700 result
5701 .entry(target_buffer)
5702 .or_insert(Vec::new())
5703 .push(start..end)
5704 }
5705 for (buffer, ranges) in result {
5706 let _ = tx.send((buffer, ranges)).await;
5707 }
5708 Result::<(), anyhow::Error>::Ok(())
5709 })
5710 .detach_and_log_err(cx);
5711 rx
5712 } else {
5713 unimplemented!();
5714 }
5715 }
5716
5717 pub fn search_local(
5718 &self,
5719 query: SearchQuery,
5720 cx: &mut ModelContext<Self>,
5721 ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5722 // Local search is split into several phases.
5723 // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5724 // and the second phase that finds positions of all the matches found in the candidate files.
5725 // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5726 //
5727 // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5728 // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5729 //
5730 // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5731 // 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
5732 // of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5733 // 2. At this point, we have a list of all potentially matching buffers/files.
5734 // We sort that list by buffer path - this list is retained for later use.
5735 // We ensure that all buffers are now opened and available in project.
5736 // 3. We run a scan over all the candidate buffers on multiple background threads.
5737 // We cannot assume that there will even be a match - while at least one match
5738 // is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5739 // There is also an auxiliary background thread responsible for result gathering.
5740 // 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),
5741 // it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5742 // 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
5743 // entry - which might already be available thanks to out-of-order processing.
5744 //
5745 // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5746 // 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.
5747 // 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
5748 // in face of constantly updating list of sorted matches.
5749 // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5750 let snapshots = self
5751 .visible_worktrees(cx)
5752 .filter_map(|tree| {
5753 let tree = tree.read(cx).as_local()?;
5754 Some(tree.snapshot())
5755 })
5756 .collect::<Vec<_>>();
5757
5758 let background = cx.background_executor().clone();
5759 let path_count: usize = snapshots
5760 .iter()
5761 .map(|s| {
5762 if query.include_ignored() {
5763 s.file_count()
5764 } else {
5765 s.visible_file_count()
5766 }
5767 })
5768 .sum();
5769 if path_count == 0 {
5770 let (_, rx) = smol::channel::bounded(1024);
5771 return rx;
5772 }
5773 let workers = background.num_cpus().min(path_count);
5774 let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5775 let mut unnamed_files = vec![];
5776 let opened_buffers = self
5777 .opened_buffers
5778 .iter()
5779 .filter_map(|(_, b)| {
5780 let buffer = b.upgrade()?;
5781 let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
5782 let is_ignored = buffer
5783 .project_path(cx)
5784 .and_then(|path| self.entry_for_path(&path, cx))
5785 .map_or(false, |entry| entry.is_ignored);
5786 (is_ignored, buffer.snapshot())
5787 });
5788 if is_ignored && !query.include_ignored() {
5789 return None;
5790 } else if let Some(path) = snapshot.file().map(|file| file.path()) {
5791 Some((path.clone(), (buffer, snapshot)))
5792 } else {
5793 unnamed_files.push(buffer);
5794 None
5795 }
5796 })
5797 .collect();
5798 cx.background_executor()
5799 .spawn(Self::background_search(
5800 unnamed_files,
5801 opened_buffers,
5802 cx.background_executor().clone(),
5803 self.fs.clone(),
5804 workers,
5805 query.clone(),
5806 path_count,
5807 snapshots,
5808 matching_paths_tx,
5809 ))
5810 .detach();
5811
5812 let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5813 let background = cx.background_executor().clone();
5814 let (result_tx, result_rx) = smol::channel::bounded(1024);
5815 cx.background_executor()
5816 .spawn(async move {
5817 let Ok(buffers) = buffers.await else {
5818 return;
5819 };
5820
5821 let buffers_len = buffers.len();
5822 if buffers_len == 0 {
5823 return;
5824 }
5825 let query = &query;
5826 let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5827 background
5828 .scoped(|scope| {
5829 #[derive(Clone)]
5830 struct FinishedStatus {
5831 entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
5832 buffer_index: SearchMatchCandidateIndex,
5833 }
5834
5835 for _ in 0..workers {
5836 let finished_tx = finished_tx.clone();
5837 let mut buffers_rx = buffers_rx.clone();
5838 scope.spawn(async move {
5839 while let Some((entry, buffer_index)) = buffers_rx.next().await {
5840 let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5841 {
5842 if query.file_matches(
5843 snapshot.file().map(|file| file.path().as_ref()),
5844 ) {
5845 query
5846 .search(snapshot, None)
5847 .await
5848 .iter()
5849 .map(|range| {
5850 snapshot.anchor_before(range.start)
5851 ..snapshot.anchor_after(range.end)
5852 })
5853 .collect()
5854 } else {
5855 Vec::new()
5856 }
5857 } else {
5858 Vec::new()
5859 };
5860
5861 let status = if !buffer_matches.is_empty() {
5862 let entry = if let Some((buffer, _)) = entry.as_ref() {
5863 Some((buffer.clone(), buffer_matches))
5864 } else {
5865 None
5866 };
5867 FinishedStatus {
5868 entry,
5869 buffer_index,
5870 }
5871 } else {
5872 FinishedStatus {
5873 entry: None,
5874 buffer_index,
5875 }
5876 };
5877 if finished_tx.send(status).await.is_err() {
5878 break;
5879 }
5880 }
5881 });
5882 }
5883 // Report sorted matches
5884 scope.spawn(async move {
5885 let mut current_index = 0;
5886 let mut scratch = vec![None; buffers_len];
5887 while let Some(status) = finished_rx.next().await {
5888 debug_assert!(
5889 scratch[status.buffer_index].is_none(),
5890 "Got match status of position {} twice",
5891 status.buffer_index
5892 );
5893 let index = status.buffer_index;
5894 scratch[index] = Some(status);
5895 while current_index < buffers_len {
5896 let Some(current_entry) = scratch[current_index].take() else {
5897 // We intentionally **do not** increment `current_index` here. When next element arrives
5898 // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5899 // this time.
5900 break;
5901 };
5902 if let Some(entry) = current_entry.entry {
5903 result_tx.send(entry).await.log_err();
5904 }
5905 current_index += 1;
5906 }
5907 if current_index == buffers_len {
5908 break;
5909 }
5910 }
5911 });
5912 })
5913 .await;
5914 })
5915 .detach();
5916 result_rx
5917 }
5918
5919 /// Pick paths that might potentially contain a match of a given search query.
5920 async fn background_search(
5921 unnamed_buffers: Vec<Model<Buffer>>,
5922 opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
5923 executor: BackgroundExecutor,
5924 fs: Arc<dyn Fs>,
5925 workers: usize,
5926 query: SearchQuery,
5927 path_count: usize,
5928 snapshots: Vec<LocalSnapshot>,
5929 matching_paths_tx: Sender<SearchMatchCandidate>,
5930 ) {
5931 let fs = &fs;
5932 let query = &query;
5933 let matching_paths_tx = &matching_paths_tx;
5934 let snapshots = &snapshots;
5935 let paths_per_worker = (path_count + workers - 1) / workers;
5936 for buffer in unnamed_buffers {
5937 matching_paths_tx
5938 .send(SearchMatchCandidate::OpenBuffer {
5939 buffer: buffer.clone(),
5940 path: None,
5941 })
5942 .await
5943 .log_err();
5944 }
5945 for (path, (buffer, _)) in opened_buffers.iter() {
5946 matching_paths_tx
5947 .send(SearchMatchCandidate::OpenBuffer {
5948 buffer: buffer.clone(),
5949 path: Some(path.clone()),
5950 })
5951 .await
5952 .log_err();
5953 }
5954 executor
5955 .scoped(|scope| {
5956 let max_concurrent_workers = Arc::new(Semaphore::new(workers));
5957
5958 for worker_ix in 0..workers {
5959 let worker_start_ix = worker_ix * paths_per_worker;
5960 let worker_end_ix = worker_start_ix + paths_per_worker;
5961 let unnamed_buffers = opened_buffers.clone();
5962 let limiter = Arc::clone(&max_concurrent_workers);
5963 scope.spawn(async move {
5964 let _guard = limiter.acquire().await;
5965 let mut snapshot_start_ix = 0;
5966 let mut abs_path = PathBuf::new();
5967 for snapshot in snapshots {
5968 let snapshot_end_ix = snapshot_start_ix
5969 + if query.include_ignored() {
5970 snapshot.file_count()
5971 } else {
5972 snapshot.visible_file_count()
5973 };
5974 if worker_end_ix <= snapshot_start_ix {
5975 break;
5976 } else if worker_start_ix > snapshot_end_ix {
5977 snapshot_start_ix = snapshot_end_ix;
5978 continue;
5979 } else {
5980 let start_in_snapshot =
5981 worker_start_ix.saturating_sub(snapshot_start_ix);
5982 let end_in_snapshot =
5983 cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5984
5985 for entry in snapshot
5986 .files(query.include_ignored(), start_in_snapshot)
5987 .take(end_in_snapshot - start_in_snapshot)
5988 {
5989 if matching_paths_tx.is_closed() {
5990 break;
5991 }
5992 if unnamed_buffers.contains_key(&entry.path) {
5993 continue;
5994 }
5995 let matches = if query.file_matches(Some(&entry.path)) {
5996 abs_path.clear();
5997 abs_path.push(&snapshot.abs_path());
5998 abs_path.push(&entry.path);
5999 if let Some(file) = fs.open_sync(&abs_path).await.log_err()
6000 {
6001 query.detect(file).unwrap_or(false)
6002 } else {
6003 false
6004 }
6005 } else {
6006 false
6007 };
6008
6009 if matches {
6010 let project_path = SearchMatchCandidate::Path {
6011 worktree_id: snapshot.id(),
6012 path: entry.path.clone(),
6013 is_ignored: entry.is_ignored,
6014 };
6015 if matching_paths_tx.send(project_path).await.is_err() {
6016 break;
6017 }
6018 }
6019 }
6020
6021 snapshot_start_ix = snapshot_end_ix;
6022 }
6023 }
6024 });
6025 }
6026
6027 if query.include_ignored() {
6028 for snapshot in snapshots {
6029 for ignored_entry in snapshot
6030 .entries(query.include_ignored())
6031 .filter(|e| e.is_ignored)
6032 {
6033 let limiter = Arc::clone(&max_concurrent_workers);
6034 scope.spawn(async move {
6035 let _guard = limiter.acquire().await;
6036 let mut ignored_paths_to_process =
6037 VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
6038 while let Some(ignored_abs_path) =
6039 ignored_paths_to_process.pop_front()
6040 {
6041 if let Some(fs_metadata) = fs
6042 .metadata(&ignored_abs_path)
6043 .await
6044 .with_context(|| {
6045 format!("fetching fs metadata for {ignored_abs_path:?}")
6046 })
6047 .log_err()
6048 .flatten()
6049 {
6050 if fs_metadata.is_dir {
6051 if let Some(mut subfiles) = fs
6052 .read_dir(&ignored_abs_path)
6053 .await
6054 .with_context(|| {
6055 format!(
6056 "listing ignored path {ignored_abs_path:?}"
6057 )
6058 })
6059 .log_err()
6060 {
6061 while let Some(subfile) = subfiles.next().await {
6062 if let Some(subfile) = subfile.log_err() {
6063 ignored_paths_to_process.push_back(subfile);
6064 }
6065 }
6066 }
6067 } else if !fs_metadata.is_symlink {
6068 if !query.file_matches(Some(&ignored_abs_path))
6069 || snapshot.is_path_excluded(
6070 ignored_entry.path.to_path_buf(),
6071 )
6072 {
6073 continue;
6074 }
6075 let matches = if let Some(file) = fs
6076 .open_sync(&ignored_abs_path)
6077 .await
6078 .with_context(|| {
6079 format!(
6080 "Opening ignored path {ignored_abs_path:?}"
6081 )
6082 })
6083 .log_err()
6084 {
6085 query.detect(file).unwrap_or(false)
6086 } else {
6087 false
6088 };
6089 if matches {
6090 let project_path = SearchMatchCandidate::Path {
6091 worktree_id: snapshot.id(),
6092 path: Arc::from(
6093 ignored_abs_path
6094 .strip_prefix(snapshot.abs_path())
6095 .expect(
6096 "scanning worktree-related files",
6097 ),
6098 ),
6099 is_ignored: true,
6100 };
6101 if matching_paths_tx
6102 .send(project_path)
6103 .await
6104 .is_err()
6105 {
6106 return;
6107 }
6108 }
6109 }
6110 }
6111 }
6112 });
6113 }
6114 }
6115 }
6116 })
6117 .await;
6118 }
6119
6120 pub fn request_lsp<R: LspCommand>(
6121 &self,
6122 buffer_handle: Model<Buffer>,
6123 server: LanguageServerToQuery,
6124 request: R,
6125 cx: &mut ModelContext<Self>,
6126 ) -> Task<Result<R::Response>>
6127 where
6128 <R::LspRequest as lsp::request::Request>::Result: Send,
6129 <R::LspRequest as lsp::request::Request>::Params: Send,
6130 {
6131 let buffer = buffer_handle.read(cx);
6132 if self.is_local() {
6133 let language_server = match server {
6134 LanguageServerToQuery::Primary => {
6135 match self.primary_language_server_for_buffer(buffer, cx) {
6136 Some((_, server)) => Some(Arc::clone(server)),
6137 None => return Task::ready(Ok(Default::default())),
6138 }
6139 }
6140 LanguageServerToQuery::Other(id) => self
6141 .language_server_for_buffer(buffer, id, cx)
6142 .map(|(_, server)| Arc::clone(server)),
6143 };
6144 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
6145 if let (Some(file), Some(language_server)) = (file, language_server) {
6146 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
6147 return cx.spawn(move |this, cx| async move {
6148 if !request.check_capabilities(language_server.capabilities()) {
6149 return Ok(Default::default());
6150 }
6151
6152 let result = language_server.request::<R::LspRequest>(lsp_params).await;
6153 let response = match result {
6154 Ok(response) => response,
6155
6156 Err(err) => {
6157 log::warn!(
6158 "Generic lsp request to {} failed: {}",
6159 language_server.name(),
6160 err
6161 );
6162 return Err(err);
6163 }
6164 };
6165
6166 request
6167 .response_from_lsp(
6168 response,
6169 this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6170 buffer_handle,
6171 language_server.server_id(),
6172 cx,
6173 )
6174 .await
6175 });
6176 }
6177 } else if let Some(project_id) = self.remote_id() {
6178 return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6179 }
6180
6181 Task::ready(Ok(Default::default()))
6182 }
6183
6184 fn send_lsp_proto_request<R: LspCommand>(
6185 &self,
6186 buffer: Model<Buffer>,
6187 project_id: u64,
6188 request: R,
6189 cx: &mut ModelContext<'_, Project>,
6190 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6191 let rpc = self.client.clone();
6192 let message = request.to_proto(project_id, buffer.read(cx));
6193 cx.spawn(move |this, mut cx| async move {
6194 // Ensure the project is still alive by the time the task
6195 // is scheduled.
6196 this.upgrade().context("project dropped")?;
6197 let response = rpc.request(message).await?;
6198 let this = this.upgrade().context("project dropped")?;
6199 if this.update(&mut cx, |this, _| this.is_disconnected())? {
6200 Err(anyhow!("disconnected before completing request"))
6201 } else {
6202 request
6203 .response_from_proto(response, this, buffer, cx)
6204 .await
6205 }
6206 })
6207 }
6208
6209 fn sort_candidates_and_open_buffers(
6210 mut matching_paths_rx: Receiver<SearchMatchCandidate>,
6211 cx: &mut ModelContext<Self>,
6212 ) -> (
6213 futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
6214 Receiver<(
6215 Option<(Model<Buffer>, BufferSnapshot)>,
6216 SearchMatchCandidateIndex,
6217 )>,
6218 ) {
6219 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
6220 let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
6221 cx.spawn(move |this, cx| async move {
6222 let mut buffers = Vec::new();
6223 let mut ignored_buffers = Vec::new();
6224 while let Some(entry) = matching_paths_rx.next().await {
6225 if matches!(
6226 entry,
6227 SearchMatchCandidate::Path {
6228 is_ignored: true,
6229 ..
6230 }
6231 ) {
6232 ignored_buffers.push(entry);
6233 } else {
6234 buffers.push(entry);
6235 }
6236 }
6237 buffers.sort_by_key(|candidate| candidate.path());
6238 ignored_buffers.sort_by_key(|candidate| candidate.path());
6239 buffers.extend(ignored_buffers);
6240 let matching_paths = buffers.clone();
6241 let _ = sorted_buffers_tx.send(buffers);
6242 for (index, candidate) in matching_paths.into_iter().enumerate() {
6243 if buffers_tx.is_closed() {
6244 break;
6245 }
6246 let this = this.clone();
6247 let buffers_tx = buffers_tx.clone();
6248 cx.spawn(move |mut cx| async move {
6249 let buffer = match candidate {
6250 SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6251 SearchMatchCandidate::Path {
6252 worktree_id, path, ..
6253 } => this
6254 .update(&mut cx, |this, cx| {
6255 this.open_buffer((worktree_id, path), cx)
6256 })?
6257 .await
6258 .log_err(),
6259 };
6260 if let Some(buffer) = buffer {
6261 let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6262 buffers_tx
6263 .send((Some((buffer, snapshot)), index))
6264 .await
6265 .log_err();
6266 } else {
6267 buffers_tx.send((None, index)).await.log_err();
6268 }
6269
6270 Ok::<_, anyhow::Error>(())
6271 })
6272 .detach();
6273 }
6274 })
6275 .detach();
6276 (sorted_buffers_rx, buffers_rx)
6277 }
6278
6279 pub fn find_or_create_local_worktree(
6280 &mut self,
6281 abs_path: impl AsRef<Path>,
6282 visible: bool,
6283 cx: &mut ModelContext<Self>,
6284 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6285 let abs_path = abs_path.as_ref();
6286 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6287 Task::ready(Ok((tree, relative_path)))
6288 } else {
6289 let worktree = self.create_local_worktree(abs_path, visible, cx);
6290 cx.background_executor()
6291 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6292 }
6293 }
6294
6295 pub fn find_local_worktree(
6296 &self,
6297 abs_path: &Path,
6298 cx: &AppContext,
6299 ) -> Option<(Model<Worktree>, PathBuf)> {
6300 for tree in &self.worktrees {
6301 if let Some(tree) = tree.upgrade() {
6302 if let Some(relative_path) = tree
6303 .read(cx)
6304 .as_local()
6305 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6306 {
6307 return Some((tree.clone(), relative_path.into()));
6308 }
6309 }
6310 }
6311 None
6312 }
6313
6314 pub fn is_shared(&self) -> bool {
6315 match &self.client_state {
6316 ProjectClientState::Shared { .. } => true,
6317 ProjectClientState::Local | ProjectClientState::Remote { .. } => false,
6318 }
6319 }
6320
6321 fn create_local_worktree(
6322 &mut self,
6323 abs_path: impl AsRef<Path>,
6324 visible: bool,
6325 cx: &mut ModelContext<Self>,
6326 ) -> Task<Result<Model<Worktree>>> {
6327 let fs = self.fs.clone();
6328 let client = self.client.clone();
6329 let next_entry_id = self.next_entry_id.clone();
6330 let path: Arc<Path> = abs_path.as_ref().into();
6331 let task = self
6332 .loading_local_worktrees
6333 .entry(path.clone())
6334 .or_insert_with(|| {
6335 cx.spawn(move |project, mut cx| {
6336 async move {
6337 let worktree = Worktree::local(
6338 client.clone(),
6339 path.clone(),
6340 visible,
6341 fs,
6342 next_entry_id,
6343 &mut cx,
6344 )
6345 .await;
6346
6347 project.update(&mut cx, |project, _| {
6348 project.loading_local_worktrees.remove(&path);
6349 })?;
6350
6351 let worktree = worktree?;
6352 project
6353 .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6354 Ok(worktree)
6355 }
6356 .map_err(Arc::new)
6357 })
6358 .shared()
6359 })
6360 .clone();
6361 cx.background_executor().spawn(async move {
6362 match task.await {
6363 Ok(worktree) => Ok(worktree),
6364 Err(err) => Err(anyhow!("{}", err)),
6365 }
6366 })
6367 }
6368
6369 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6370 let mut servers_to_remove = HashMap::default();
6371 let mut servers_to_preserve = HashSet::default();
6372 for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
6373 if worktree_id == &id_to_remove {
6374 servers_to_remove.insert(server_id, server_name.clone());
6375 } else {
6376 servers_to_preserve.insert(server_id);
6377 }
6378 }
6379 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
6380 for (server_id_to_remove, server_name) in servers_to_remove {
6381 self.language_server_ids
6382 .remove(&(id_to_remove, server_name));
6383 self.language_server_statuses.remove(&server_id_to_remove);
6384 self.last_workspace_edits_by_language_server
6385 .remove(&server_id_to_remove);
6386 self.language_servers.remove(&server_id_to_remove);
6387 cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
6388 }
6389
6390 let mut prettier_instances_to_clean = FuturesUnordered::new();
6391 if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
6392 for path in prettier_paths.iter().flatten() {
6393 if let Some(prettier_instance) = self.prettier_instances.remove(path) {
6394 prettier_instances_to_clean.push(async move {
6395 prettier_instance
6396 .server()
6397 .await
6398 .map(|server| server.server_id())
6399 });
6400 }
6401 }
6402 }
6403 cx.spawn(|project, mut cx| async move {
6404 while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
6405 if let Some(prettier_server_id) = prettier_server_id {
6406 project
6407 .update(&mut cx, |project, cx| {
6408 project
6409 .supplementary_language_servers
6410 .remove(&prettier_server_id);
6411 cx.emit(Event::LanguageServerRemoved(prettier_server_id));
6412 })
6413 .ok();
6414 }
6415 }
6416 })
6417 .detach();
6418
6419 self.worktrees.retain(|worktree| {
6420 if let Some(worktree) = worktree.upgrade() {
6421 let id = worktree.read(cx).id();
6422 if id == id_to_remove {
6423 cx.emit(Event::WorktreeRemoved(id));
6424 false
6425 } else {
6426 true
6427 }
6428 } else {
6429 false
6430 }
6431 });
6432 self.metadata_changed(cx);
6433 }
6434
6435 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6436 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6437 if worktree.read(cx).is_local() {
6438 cx.subscribe(worktree, |this, worktree, event, cx| match event {
6439 worktree::Event::UpdatedEntries(changes) => {
6440 this.update_local_worktree_buffers(&worktree, changes, cx);
6441 this.update_local_worktree_language_servers(&worktree, changes, cx);
6442 this.update_local_worktree_settings(&worktree, changes, cx);
6443 this.update_prettier_settings(&worktree, changes, cx);
6444 cx.emit(Event::WorktreeUpdatedEntries(
6445 worktree.read(cx).id(),
6446 changes.clone(),
6447 ));
6448 }
6449 worktree::Event::UpdatedGitRepositories(updated_repos) => {
6450 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6451 }
6452 })
6453 .detach();
6454 }
6455
6456 let push_strong_handle = {
6457 let worktree = worktree.read(cx);
6458 self.is_shared() || worktree.is_visible() || worktree.is_remote()
6459 };
6460 if push_strong_handle {
6461 self.worktrees
6462 .push(WorktreeHandle::Strong(worktree.clone()));
6463 } else {
6464 self.worktrees
6465 .push(WorktreeHandle::Weak(worktree.downgrade()));
6466 }
6467
6468 let handle_id = worktree.entity_id();
6469 cx.observe_release(worktree, move |this, worktree, cx| {
6470 let _ = this.remove_worktree(worktree.id(), cx);
6471 cx.update_global::<SettingsStore, _>(|store, cx| {
6472 store
6473 .clear_local_settings(handle_id.as_u64() as usize, cx)
6474 .log_err()
6475 });
6476 })
6477 .detach();
6478
6479 cx.emit(Event::WorktreeAdded);
6480 self.metadata_changed(cx);
6481 }
6482
6483 fn update_local_worktree_buffers(
6484 &mut self,
6485 worktree_handle: &Model<Worktree>,
6486 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6487 cx: &mut ModelContext<Self>,
6488 ) {
6489 let snapshot = worktree_handle.read(cx).snapshot();
6490
6491 let mut renamed_buffers = Vec::new();
6492 for (path, entry_id, _) in changes {
6493 let worktree_id = worktree_handle.read(cx).id();
6494 let project_path = ProjectPath {
6495 worktree_id,
6496 path: path.clone(),
6497 };
6498
6499 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6500 Some(&buffer_id) => buffer_id,
6501 None => match self.local_buffer_ids_by_path.get(&project_path) {
6502 Some(&buffer_id) => buffer_id,
6503 None => {
6504 continue;
6505 }
6506 },
6507 };
6508
6509 let open_buffer = self.opened_buffers.get(&buffer_id);
6510 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6511 buffer
6512 } else {
6513 self.opened_buffers.remove(&buffer_id);
6514 self.local_buffer_ids_by_path.remove(&project_path);
6515 self.local_buffer_ids_by_entry_id.remove(entry_id);
6516 continue;
6517 };
6518
6519 buffer.update(cx, |buffer, cx| {
6520 if let Some(old_file) = File::from_dyn(buffer.file()) {
6521 if old_file.worktree != *worktree_handle {
6522 return;
6523 }
6524
6525 let new_file = if let Some(entry) = old_file
6526 .entry_id
6527 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
6528 {
6529 File {
6530 is_local: true,
6531 entry_id: Some(entry.id),
6532 mtime: entry.mtime,
6533 path: entry.path.clone(),
6534 worktree: worktree_handle.clone(),
6535 is_deleted: false,
6536 }
6537 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6538 File {
6539 is_local: true,
6540 entry_id: Some(entry.id),
6541 mtime: entry.mtime,
6542 path: entry.path.clone(),
6543 worktree: worktree_handle.clone(),
6544 is_deleted: false,
6545 }
6546 } else {
6547 File {
6548 is_local: true,
6549 entry_id: old_file.entry_id,
6550 path: old_file.path().clone(),
6551 mtime: old_file.mtime(),
6552 worktree: worktree_handle.clone(),
6553 is_deleted: true,
6554 }
6555 };
6556
6557 let old_path = old_file.abs_path(cx);
6558 if new_file.abs_path(cx) != old_path {
6559 renamed_buffers.push((cx.handle(), old_file.clone()));
6560 self.local_buffer_ids_by_path.remove(&project_path);
6561 self.local_buffer_ids_by_path.insert(
6562 ProjectPath {
6563 worktree_id,
6564 path: path.clone(),
6565 },
6566 buffer_id,
6567 );
6568 }
6569
6570 if new_file.entry_id != Some(*entry_id) {
6571 self.local_buffer_ids_by_entry_id.remove(entry_id);
6572 if let Some(entry_id) = new_file.entry_id {
6573 self.local_buffer_ids_by_entry_id
6574 .insert(entry_id, buffer_id);
6575 }
6576 }
6577
6578 if new_file != *old_file {
6579 if let Some(project_id) = self.remote_id() {
6580 self.client
6581 .send(proto::UpdateBufferFile {
6582 project_id,
6583 buffer_id: buffer_id as u64,
6584 file: Some(new_file.to_proto()),
6585 })
6586 .log_err();
6587 }
6588
6589 buffer.file_updated(Arc::new(new_file), cx);
6590 }
6591 }
6592 });
6593 }
6594
6595 for (buffer, old_file) in renamed_buffers {
6596 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6597 self.detect_language_for_buffer(&buffer, cx);
6598 self.register_buffer_with_language_servers(&buffer, cx);
6599 }
6600 }
6601
6602 fn update_local_worktree_language_servers(
6603 &mut self,
6604 worktree_handle: &Model<Worktree>,
6605 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6606 cx: &mut ModelContext<Self>,
6607 ) {
6608 if changes.is_empty() {
6609 return;
6610 }
6611
6612 let worktree_id = worktree_handle.read(cx).id();
6613 let mut language_server_ids = self
6614 .language_server_ids
6615 .iter()
6616 .filter_map(|((server_worktree_id, _), server_id)| {
6617 (*server_worktree_id == worktree_id).then_some(*server_id)
6618 })
6619 .collect::<Vec<_>>();
6620 language_server_ids.sort();
6621 language_server_ids.dedup();
6622
6623 let abs_path = worktree_handle.read(cx).abs_path();
6624 for server_id in &language_server_ids {
6625 if let Some(LanguageServerState::Running {
6626 server,
6627 watched_paths,
6628 ..
6629 }) = self.language_servers.get(server_id)
6630 {
6631 if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6632 let params = lsp::DidChangeWatchedFilesParams {
6633 changes: changes
6634 .iter()
6635 .filter_map(|(path, _, change)| {
6636 if !watched_paths.is_match(&path) {
6637 return None;
6638 }
6639 let typ = match change {
6640 PathChange::Loaded => return None,
6641 PathChange::Added => lsp::FileChangeType::CREATED,
6642 PathChange::Removed => lsp::FileChangeType::DELETED,
6643 PathChange::Updated => lsp::FileChangeType::CHANGED,
6644 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6645 };
6646 Some(lsp::FileEvent {
6647 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6648 typ,
6649 })
6650 })
6651 .collect(),
6652 };
6653
6654 if !params.changes.is_empty() {
6655 server
6656 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6657 .log_err();
6658 }
6659 }
6660 }
6661 }
6662 }
6663
6664 fn update_local_worktree_buffers_git_repos(
6665 &mut self,
6666 worktree_handle: Model<Worktree>,
6667 changed_repos: &UpdatedGitRepositoriesSet,
6668 cx: &mut ModelContext<Self>,
6669 ) {
6670 debug_assert!(worktree_handle.read(cx).is_local());
6671
6672 // Identify the loading buffers whose containing repository that has changed.
6673 let future_buffers = self
6674 .loading_buffers_by_path
6675 .iter()
6676 .filter_map(|(project_path, receiver)| {
6677 if project_path.worktree_id != worktree_handle.read(cx).id() {
6678 return None;
6679 }
6680 let path = &project_path.path;
6681 changed_repos
6682 .iter()
6683 .find(|(work_dir, _)| path.starts_with(work_dir))?;
6684 let receiver = receiver.clone();
6685 let path = path.clone();
6686 Some(async move {
6687 wait_for_loading_buffer(receiver)
6688 .await
6689 .ok()
6690 .map(|buffer| (buffer, path))
6691 })
6692 })
6693 .collect::<FuturesUnordered<_>>();
6694
6695 // Identify the current buffers whose containing repository has changed.
6696 let current_buffers = self
6697 .opened_buffers
6698 .values()
6699 .filter_map(|buffer| {
6700 let buffer = buffer.upgrade()?;
6701 let file = File::from_dyn(buffer.read(cx).file())?;
6702 if file.worktree != worktree_handle {
6703 return None;
6704 }
6705 let path = file.path();
6706 changed_repos
6707 .iter()
6708 .find(|(work_dir, _)| path.starts_with(work_dir))?;
6709 Some((buffer, path.clone()))
6710 })
6711 .collect::<Vec<_>>();
6712
6713 if future_buffers.len() + current_buffers.len() == 0 {
6714 return;
6715 }
6716
6717 let remote_id = self.remote_id();
6718 let client = self.client.clone();
6719 cx.spawn(move |_, mut cx| async move {
6720 // Wait for all of the buffers to load.
6721 let future_buffers = future_buffers.collect::<Vec<_>>().await;
6722
6723 // Reload the diff base for every buffer whose containing git repository has changed.
6724 let snapshot =
6725 worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
6726 let diff_bases_by_buffer = cx
6727 .background_executor()
6728 .spawn(async move {
6729 future_buffers
6730 .into_iter()
6731 .filter_map(|e| e)
6732 .chain(current_buffers)
6733 .filter_map(|(buffer, path)| {
6734 let (work_directory, repo) =
6735 snapshot.repository_and_work_directory_for_path(&path)?;
6736 let repo = snapshot.get_local_repo(&repo)?;
6737 let relative_path = path.strip_prefix(&work_directory).ok()?;
6738 let base_text = repo.repo_ptr.lock().load_index_text(relative_path);
6739 Some((buffer, base_text))
6740 })
6741 .collect::<Vec<_>>()
6742 })
6743 .await;
6744
6745 // Assign the new diff bases on all of the buffers.
6746 for (buffer, diff_base) in diff_bases_by_buffer {
6747 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6748 buffer.set_diff_base(diff_base.clone(), cx);
6749 buffer.remote_id()
6750 })?;
6751 if let Some(project_id) = remote_id {
6752 client
6753 .send(proto::UpdateDiffBase {
6754 project_id,
6755 buffer_id,
6756 diff_base,
6757 })
6758 .log_err();
6759 }
6760 }
6761
6762 anyhow::Ok(())
6763 })
6764 .detach();
6765 }
6766
6767 fn update_local_worktree_settings(
6768 &mut self,
6769 worktree: &Model<Worktree>,
6770 changes: &UpdatedEntriesSet,
6771 cx: &mut ModelContext<Self>,
6772 ) {
6773 let project_id = self.remote_id();
6774 let worktree_id = worktree.entity_id();
6775 let worktree = worktree.read(cx).as_local().unwrap();
6776 let remote_worktree_id = worktree.id();
6777
6778 let mut settings_contents = Vec::new();
6779 for (path, _, change) in changes.iter() {
6780 if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6781 let settings_dir = Arc::from(
6782 path.ancestors()
6783 .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6784 .unwrap(),
6785 );
6786 let fs = self.fs.clone();
6787 let removed = *change == PathChange::Removed;
6788 let abs_path = worktree.absolutize(path);
6789 settings_contents.push(async move {
6790 (
6791 settings_dir,
6792 if removed {
6793 None
6794 } else {
6795 Some(async move { fs.load(&abs_path?).await }.await)
6796 },
6797 )
6798 });
6799 }
6800 }
6801
6802 if settings_contents.is_empty() {
6803 return;
6804 }
6805
6806 let client = self.client.clone();
6807 cx.spawn(move |_, cx| async move {
6808 let settings_contents: Vec<(Arc<Path>, _)> =
6809 futures::future::join_all(settings_contents).await;
6810 cx.update(|cx| {
6811 cx.update_global::<SettingsStore, _>(|store, cx| {
6812 for (directory, file_content) in settings_contents {
6813 let file_content = file_content.and_then(|content| content.log_err());
6814 store
6815 .set_local_settings(
6816 worktree_id.as_u64() as usize,
6817 directory.clone(),
6818 file_content.as_ref().map(String::as_str),
6819 cx,
6820 )
6821 .log_err();
6822 if let Some(remote_id) = project_id {
6823 client
6824 .send(proto::UpdateWorktreeSettings {
6825 project_id: remote_id,
6826 worktree_id: remote_worktree_id.to_proto(),
6827 path: directory.to_string_lossy().into_owned(),
6828 content: file_content,
6829 })
6830 .log_err();
6831 }
6832 }
6833 });
6834 })
6835 .ok();
6836 })
6837 .detach();
6838 }
6839
6840 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6841 let new_active_entry = entry.and_then(|project_path| {
6842 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6843 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6844 Some(entry.id)
6845 });
6846 if new_active_entry != self.active_entry {
6847 self.active_entry = new_active_entry;
6848 cx.emit(Event::ActiveEntryChanged(new_active_entry));
6849 }
6850 }
6851
6852 pub fn language_servers_running_disk_based_diagnostics(
6853 &self,
6854 ) -> impl Iterator<Item = LanguageServerId> + '_ {
6855 self.language_server_statuses
6856 .iter()
6857 .filter_map(|(id, status)| {
6858 if status.has_pending_diagnostic_updates {
6859 Some(*id)
6860 } else {
6861 None
6862 }
6863 })
6864 }
6865
6866 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
6867 let mut summary = DiagnosticSummary::default();
6868 for (_, _, path_summary) in
6869 self.diagnostic_summaries(include_ignored, cx)
6870 .filter(|(path, _, _)| {
6871 let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
6872 include_ignored || worktree == Some(false)
6873 })
6874 {
6875 summary.error_count += path_summary.error_count;
6876 summary.warning_count += path_summary.warning_count;
6877 }
6878 summary
6879 }
6880
6881 pub fn diagnostic_summaries<'a>(
6882 &'a self,
6883 include_ignored: bool,
6884 cx: &'a AppContext,
6885 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6886 self.visible_worktrees(cx)
6887 .flat_map(move |worktree| {
6888 let worktree = worktree.read(cx);
6889 let worktree_id = worktree.id();
6890 worktree
6891 .diagnostic_summaries()
6892 .map(move |(path, server_id, summary)| {
6893 (ProjectPath { worktree_id, path }, server_id, summary)
6894 })
6895 })
6896 .filter(move |(path, _, _)| {
6897 let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
6898 include_ignored || worktree == Some(false)
6899 })
6900 }
6901
6902 pub fn disk_based_diagnostics_started(
6903 &mut self,
6904 language_server_id: LanguageServerId,
6905 cx: &mut ModelContext<Self>,
6906 ) {
6907 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6908 }
6909
6910 pub fn disk_based_diagnostics_finished(
6911 &mut self,
6912 language_server_id: LanguageServerId,
6913 cx: &mut ModelContext<Self>,
6914 ) {
6915 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6916 }
6917
6918 pub fn active_entry(&self) -> Option<ProjectEntryId> {
6919 self.active_entry
6920 }
6921
6922 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6923 self.worktree_for_id(path.worktree_id, cx)?
6924 .read(cx)
6925 .entry_for_path(&path.path)
6926 .cloned()
6927 }
6928
6929 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6930 let worktree = self.worktree_for_entry(entry_id, cx)?;
6931 let worktree = worktree.read(cx);
6932 let worktree_id = worktree.id();
6933 let path = worktree.entry_for_id(entry_id)?.path.clone();
6934 Some(ProjectPath { worktree_id, path })
6935 }
6936
6937 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6938 let workspace_root = self
6939 .worktree_for_id(project_path.worktree_id, cx)?
6940 .read(cx)
6941 .abs_path();
6942 let project_path = project_path.path.as_ref();
6943
6944 Some(if project_path == Path::new("") {
6945 workspace_root.to_path_buf()
6946 } else {
6947 workspace_root.join(project_path)
6948 })
6949 }
6950
6951 // RPC message handlers
6952
6953 async fn handle_unshare_project(
6954 this: Model<Self>,
6955 _: TypedEnvelope<proto::UnshareProject>,
6956 _: Arc<Client>,
6957 mut cx: AsyncAppContext,
6958 ) -> Result<()> {
6959 this.update(&mut cx, |this, cx| {
6960 if this.is_local() {
6961 this.unshare(cx)?;
6962 } else {
6963 this.disconnected_from_host(cx);
6964 }
6965 Ok(())
6966 })?
6967 }
6968
6969 async fn handle_add_collaborator(
6970 this: Model<Self>,
6971 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6972 _: Arc<Client>,
6973 mut cx: AsyncAppContext,
6974 ) -> Result<()> {
6975 let collaborator = envelope
6976 .payload
6977 .collaborator
6978 .take()
6979 .ok_or_else(|| anyhow!("empty collaborator"))?;
6980
6981 let collaborator = Collaborator::from_proto(collaborator)?;
6982 this.update(&mut cx, |this, cx| {
6983 this.shared_buffers.remove(&collaborator.peer_id);
6984 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6985 this.collaborators
6986 .insert(collaborator.peer_id, collaborator);
6987 cx.notify();
6988 })?;
6989
6990 Ok(())
6991 }
6992
6993 async fn handle_update_project_collaborator(
6994 this: Model<Self>,
6995 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6996 _: Arc<Client>,
6997 mut cx: AsyncAppContext,
6998 ) -> Result<()> {
6999 let old_peer_id = envelope
7000 .payload
7001 .old_peer_id
7002 .ok_or_else(|| anyhow!("missing old peer id"))?;
7003 let new_peer_id = envelope
7004 .payload
7005 .new_peer_id
7006 .ok_or_else(|| anyhow!("missing new peer id"))?;
7007 this.update(&mut cx, |this, cx| {
7008 let collaborator = this
7009 .collaborators
7010 .remove(&old_peer_id)
7011 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
7012 let is_host = collaborator.replica_id == 0;
7013 this.collaborators.insert(new_peer_id, collaborator);
7014
7015 let buffers = this.shared_buffers.remove(&old_peer_id);
7016 log::info!(
7017 "peer {} became {}. moving buffers {:?}",
7018 old_peer_id,
7019 new_peer_id,
7020 &buffers
7021 );
7022 if let Some(buffers) = buffers {
7023 this.shared_buffers.insert(new_peer_id, buffers);
7024 }
7025
7026 if is_host {
7027 this.opened_buffers
7028 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
7029 this.buffer_ordered_messages_tx
7030 .unbounded_send(BufferOrderedMessage::Resync)
7031 .unwrap();
7032 }
7033
7034 cx.emit(Event::CollaboratorUpdated {
7035 old_peer_id,
7036 new_peer_id,
7037 });
7038 cx.notify();
7039 Ok(())
7040 })?
7041 }
7042
7043 async fn handle_remove_collaborator(
7044 this: Model<Self>,
7045 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
7046 _: Arc<Client>,
7047 mut cx: AsyncAppContext,
7048 ) -> Result<()> {
7049 this.update(&mut cx, |this, cx| {
7050 let peer_id = envelope
7051 .payload
7052 .peer_id
7053 .ok_or_else(|| anyhow!("invalid peer id"))?;
7054 let replica_id = this
7055 .collaborators
7056 .remove(&peer_id)
7057 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
7058 .replica_id;
7059 for buffer in this.opened_buffers.values() {
7060 if let Some(buffer) = buffer.upgrade() {
7061 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
7062 }
7063 }
7064 this.shared_buffers.remove(&peer_id);
7065
7066 cx.emit(Event::CollaboratorLeft(peer_id));
7067 cx.notify();
7068 Ok(())
7069 })?
7070 }
7071
7072 async fn handle_update_project(
7073 this: Model<Self>,
7074 envelope: TypedEnvelope<proto::UpdateProject>,
7075 _: Arc<Client>,
7076 mut cx: AsyncAppContext,
7077 ) -> Result<()> {
7078 this.update(&mut cx, |this, cx| {
7079 // Don't handle messages that were sent before the response to us joining the project
7080 if envelope.message_id > this.join_project_response_message_id {
7081 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
7082 }
7083 Ok(())
7084 })?
7085 }
7086
7087 async fn handle_update_worktree(
7088 this: Model<Self>,
7089 envelope: TypedEnvelope<proto::UpdateWorktree>,
7090 _: Arc<Client>,
7091 mut cx: AsyncAppContext,
7092 ) -> Result<()> {
7093 this.update(&mut cx, |this, cx| {
7094 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7095 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7096 worktree.update(cx, |worktree, _| {
7097 let worktree = worktree.as_remote_mut().unwrap();
7098 worktree.update_from_remote(envelope.payload);
7099 });
7100 }
7101 Ok(())
7102 })?
7103 }
7104
7105 async fn handle_update_worktree_settings(
7106 this: Model<Self>,
7107 envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
7108 _: Arc<Client>,
7109 mut cx: AsyncAppContext,
7110 ) -> Result<()> {
7111 this.update(&mut cx, |this, cx| {
7112 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7113 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7114 cx.update_global::<SettingsStore, _>(|store, cx| {
7115 store
7116 .set_local_settings(
7117 worktree.entity_id().as_u64() as usize,
7118 PathBuf::from(&envelope.payload.path).into(),
7119 envelope.payload.content.as_ref().map(String::as_str),
7120 cx,
7121 )
7122 .log_err();
7123 });
7124 }
7125 Ok(())
7126 })?
7127 }
7128
7129 async fn handle_create_project_entry(
7130 this: Model<Self>,
7131 envelope: TypedEnvelope<proto::CreateProjectEntry>,
7132 _: Arc<Client>,
7133 mut cx: AsyncAppContext,
7134 ) -> Result<proto::ProjectEntryResponse> {
7135 let worktree = this.update(&mut cx, |this, cx| {
7136 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7137 this.worktree_for_id(worktree_id, cx)
7138 .ok_or_else(|| anyhow!("worktree not found"))
7139 })??;
7140 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7141 let entry = worktree
7142 .update(&mut cx, |worktree, cx| {
7143 let worktree = worktree.as_local_mut().unwrap();
7144 let path = PathBuf::from(envelope.payload.path);
7145 worktree.create_entry(path, envelope.payload.is_directory, cx)
7146 })?
7147 .await?;
7148 Ok(proto::ProjectEntryResponse {
7149 entry: entry.as_ref().map(|e| e.into()),
7150 worktree_scan_id: worktree_scan_id as u64,
7151 })
7152 }
7153
7154 async fn handle_rename_project_entry(
7155 this: Model<Self>,
7156 envelope: TypedEnvelope<proto::RenameProjectEntry>,
7157 _: Arc<Client>,
7158 mut cx: AsyncAppContext,
7159 ) -> Result<proto::ProjectEntryResponse> {
7160 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7161 let worktree = this.update(&mut cx, |this, cx| {
7162 this.worktree_for_entry(entry_id, cx)
7163 .ok_or_else(|| anyhow!("worktree not found"))
7164 })??;
7165 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7166 let entry = worktree
7167 .update(&mut cx, |worktree, cx| {
7168 let new_path = PathBuf::from(envelope.payload.new_path);
7169 worktree
7170 .as_local_mut()
7171 .unwrap()
7172 .rename_entry(entry_id, new_path, cx)
7173 })?
7174 .await?;
7175 Ok(proto::ProjectEntryResponse {
7176 entry: entry.as_ref().map(|e| e.into()),
7177 worktree_scan_id: worktree_scan_id as u64,
7178 })
7179 }
7180
7181 async fn handle_copy_project_entry(
7182 this: Model<Self>,
7183 envelope: TypedEnvelope<proto::CopyProjectEntry>,
7184 _: Arc<Client>,
7185 mut cx: AsyncAppContext,
7186 ) -> Result<proto::ProjectEntryResponse> {
7187 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7188 let worktree = this.update(&mut cx, |this, cx| {
7189 this.worktree_for_entry(entry_id, cx)
7190 .ok_or_else(|| anyhow!("worktree not found"))
7191 })??;
7192 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7193 let entry = worktree
7194 .update(&mut cx, |worktree, cx| {
7195 let new_path = PathBuf::from(envelope.payload.new_path);
7196 worktree
7197 .as_local_mut()
7198 .unwrap()
7199 .copy_entry(entry_id, new_path, cx)
7200 })?
7201 .await?;
7202 Ok(proto::ProjectEntryResponse {
7203 entry: entry.as_ref().map(|e| e.into()),
7204 worktree_scan_id: worktree_scan_id as u64,
7205 })
7206 }
7207
7208 async fn handle_delete_project_entry(
7209 this: Model<Self>,
7210 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
7211 _: Arc<Client>,
7212 mut cx: AsyncAppContext,
7213 ) -> Result<proto::ProjectEntryResponse> {
7214 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7215
7216 this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
7217
7218 let worktree = this.update(&mut cx, |this, cx| {
7219 this.worktree_for_entry(entry_id, cx)
7220 .ok_or_else(|| anyhow!("worktree not found"))
7221 })??;
7222 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7223 worktree
7224 .update(&mut cx, |worktree, cx| {
7225 worktree
7226 .as_local_mut()
7227 .unwrap()
7228 .delete_entry(entry_id, cx)
7229 .ok_or_else(|| anyhow!("invalid entry"))
7230 })??
7231 .await?;
7232 Ok(proto::ProjectEntryResponse {
7233 entry: None,
7234 worktree_scan_id: worktree_scan_id as u64,
7235 })
7236 }
7237
7238 async fn handle_expand_project_entry(
7239 this: Model<Self>,
7240 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7241 _: Arc<Client>,
7242 mut cx: AsyncAppContext,
7243 ) -> Result<proto::ExpandProjectEntryResponse> {
7244 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7245 let worktree = this
7246 .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7247 .ok_or_else(|| anyhow!("invalid request"))?;
7248 worktree
7249 .update(&mut cx, |worktree, cx| {
7250 worktree
7251 .as_local_mut()
7252 .unwrap()
7253 .expand_entry(entry_id, cx)
7254 .ok_or_else(|| anyhow!("invalid entry"))
7255 })??
7256 .await?;
7257 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7258 Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7259 }
7260
7261 async fn handle_update_diagnostic_summary(
7262 this: Model<Self>,
7263 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7264 _: Arc<Client>,
7265 mut cx: AsyncAppContext,
7266 ) -> Result<()> {
7267 this.update(&mut cx, |this, cx| {
7268 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7269 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7270 if let Some(summary) = envelope.payload.summary {
7271 let project_path = ProjectPath {
7272 worktree_id,
7273 path: Path::new(&summary.path).into(),
7274 };
7275 worktree.update(cx, |worktree, _| {
7276 worktree
7277 .as_remote_mut()
7278 .unwrap()
7279 .update_diagnostic_summary(project_path.path.clone(), &summary);
7280 });
7281 cx.emit(Event::DiagnosticsUpdated {
7282 language_server_id: LanguageServerId(summary.language_server_id as usize),
7283 path: project_path,
7284 });
7285 }
7286 }
7287 Ok(())
7288 })?
7289 }
7290
7291 async fn handle_start_language_server(
7292 this: Model<Self>,
7293 envelope: TypedEnvelope<proto::StartLanguageServer>,
7294 _: Arc<Client>,
7295 mut cx: AsyncAppContext,
7296 ) -> Result<()> {
7297 let server = envelope
7298 .payload
7299 .server
7300 .ok_or_else(|| anyhow!("invalid server"))?;
7301 this.update(&mut cx, |this, cx| {
7302 this.language_server_statuses.insert(
7303 LanguageServerId(server.id as usize),
7304 LanguageServerStatus {
7305 name: server.name,
7306 pending_work: Default::default(),
7307 has_pending_diagnostic_updates: false,
7308 progress_tokens: Default::default(),
7309 },
7310 );
7311 cx.notify();
7312 })?;
7313 Ok(())
7314 }
7315
7316 async fn handle_update_language_server(
7317 this: Model<Self>,
7318 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7319 _: Arc<Client>,
7320 mut cx: AsyncAppContext,
7321 ) -> Result<()> {
7322 this.update(&mut cx, |this, cx| {
7323 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7324
7325 match envelope
7326 .payload
7327 .variant
7328 .ok_or_else(|| anyhow!("invalid variant"))?
7329 {
7330 proto::update_language_server::Variant::WorkStart(payload) => {
7331 this.on_lsp_work_start(
7332 language_server_id,
7333 payload.token,
7334 LanguageServerProgress {
7335 message: payload.message,
7336 percentage: payload.percentage.map(|p| p as usize),
7337 last_update_at: Instant::now(),
7338 },
7339 cx,
7340 );
7341 }
7342
7343 proto::update_language_server::Variant::WorkProgress(payload) => {
7344 this.on_lsp_work_progress(
7345 language_server_id,
7346 payload.token,
7347 LanguageServerProgress {
7348 message: payload.message,
7349 percentage: payload.percentage.map(|p| p as usize),
7350 last_update_at: Instant::now(),
7351 },
7352 cx,
7353 );
7354 }
7355
7356 proto::update_language_server::Variant::WorkEnd(payload) => {
7357 this.on_lsp_work_end(language_server_id, payload.token, cx);
7358 }
7359
7360 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7361 this.disk_based_diagnostics_started(language_server_id, cx);
7362 }
7363
7364 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7365 this.disk_based_diagnostics_finished(language_server_id, cx)
7366 }
7367 }
7368
7369 Ok(())
7370 })?
7371 }
7372
7373 async fn handle_update_buffer(
7374 this: Model<Self>,
7375 envelope: TypedEnvelope<proto::UpdateBuffer>,
7376 _: Arc<Client>,
7377 mut cx: AsyncAppContext,
7378 ) -> Result<proto::Ack> {
7379 this.update(&mut cx, |this, cx| {
7380 let payload = envelope.payload.clone();
7381 let buffer_id = payload.buffer_id;
7382 let ops = payload
7383 .operations
7384 .into_iter()
7385 .map(language::proto::deserialize_operation)
7386 .collect::<Result<Vec<_>, _>>()?;
7387 let is_remote = this.is_remote();
7388 match this.opened_buffers.entry(buffer_id) {
7389 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7390 OpenBuffer::Strong(buffer) => {
7391 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7392 }
7393 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7394 OpenBuffer::Weak(_) => {}
7395 },
7396 hash_map::Entry::Vacant(e) => {
7397 assert!(
7398 is_remote,
7399 "received buffer update from {:?}",
7400 envelope.original_sender_id
7401 );
7402 e.insert(OpenBuffer::Operations(ops));
7403 }
7404 }
7405 Ok(proto::Ack {})
7406 })?
7407 }
7408
7409 async fn handle_create_buffer_for_peer(
7410 this: Model<Self>,
7411 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7412 _: Arc<Client>,
7413 mut cx: AsyncAppContext,
7414 ) -> Result<()> {
7415 this.update(&mut cx, |this, cx| {
7416 match envelope
7417 .payload
7418 .variant
7419 .ok_or_else(|| anyhow!("missing variant"))?
7420 {
7421 proto::create_buffer_for_peer::Variant::State(mut state) => {
7422 let mut buffer_file = None;
7423 if let Some(file) = state.file.take() {
7424 let worktree_id = WorktreeId::from_proto(file.worktree_id);
7425 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7426 anyhow!("no worktree found for id {}", file.worktree_id)
7427 })?;
7428 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7429 as Arc<dyn language::File>);
7430 }
7431
7432 let buffer_id = state.id;
7433 let buffer = cx.new_model(|_| {
7434 Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
7435 .unwrap()
7436 });
7437 this.incomplete_remote_buffers
7438 .insert(buffer_id, Some(buffer));
7439 }
7440 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7441 let buffer = this
7442 .incomplete_remote_buffers
7443 .get(&chunk.buffer_id)
7444 .cloned()
7445 .flatten()
7446 .ok_or_else(|| {
7447 anyhow!(
7448 "received chunk for buffer {} without initial state",
7449 chunk.buffer_id
7450 )
7451 })?;
7452 let operations = chunk
7453 .operations
7454 .into_iter()
7455 .map(language::proto::deserialize_operation)
7456 .collect::<Result<Vec<_>>>()?;
7457 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7458
7459 if chunk.is_last {
7460 this.incomplete_remote_buffers.remove(&chunk.buffer_id);
7461 this.register_buffer(&buffer, cx)?;
7462 }
7463 }
7464 }
7465
7466 Ok(())
7467 })?
7468 }
7469
7470 async fn handle_update_diff_base(
7471 this: Model<Self>,
7472 envelope: TypedEnvelope<proto::UpdateDiffBase>,
7473 _: Arc<Client>,
7474 mut cx: AsyncAppContext,
7475 ) -> Result<()> {
7476 this.update(&mut cx, |this, cx| {
7477 let buffer_id = envelope.payload.buffer_id;
7478 let diff_base = envelope.payload.diff_base;
7479 if let Some(buffer) = this
7480 .opened_buffers
7481 .get_mut(&buffer_id)
7482 .and_then(|b| b.upgrade())
7483 .or_else(|| {
7484 this.incomplete_remote_buffers
7485 .get(&buffer_id)
7486 .cloned()
7487 .flatten()
7488 })
7489 {
7490 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7491 }
7492 Ok(())
7493 })?
7494 }
7495
7496 async fn handle_update_buffer_file(
7497 this: Model<Self>,
7498 envelope: TypedEnvelope<proto::UpdateBufferFile>,
7499 _: Arc<Client>,
7500 mut cx: AsyncAppContext,
7501 ) -> Result<()> {
7502 let buffer_id = envelope.payload.buffer_id;
7503
7504 this.update(&mut cx, |this, cx| {
7505 let payload = envelope.payload.clone();
7506 if let Some(buffer) = this
7507 .opened_buffers
7508 .get(&buffer_id)
7509 .and_then(|b| b.upgrade())
7510 .or_else(|| {
7511 this.incomplete_remote_buffers
7512 .get(&buffer_id)
7513 .cloned()
7514 .flatten()
7515 })
7516 {
7517 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7518 let worktree = this
7519 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7520 .ok_or_else(|| anyhow!("no such worktree"))?;
7521 let file = File::from_proto(file, worktree, cx)?;
7522 buffer.update(cx, |buffer, cx| {
7523 buffer.file_updated(Arc::new(file), cx);
7524 });
7525 this.detect_language_for_buffer(&buffer, cx);
7526 }
7527 Ok(())
7528 })?
7529 }
7530
7531 async fn handle_save_buffer(
7532 this: Model<Self>,
7533 envelope: TypedEnvelope<proto::SaveBuffer>,
7534 _: Arc<Client>,
7535 mut cx: AsyncAppContext,
7536 ) -> Result<proto::BufferSaved> {
7537 let buffer_id = envelope.payload.buffer_id;
7538 let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7539 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7540 let buffer = this
7541 .opened_buffers
7542 .get(&buffer_id)
7543 .and_then(|buffer| buffer.upgrade())
7544 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7545 anyhow::Ok((project_id, buffer))
7546 })??;
7547 buffer
7548 .update(&mut cx, |buffer, _| {
7549 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7550 })?
7551 .await?;
7552 let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7553
7554 this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7555 .await?;
7556 Ok(buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7557 project_id,
7558 buffer_id,
7559 version: serialize_version(buffer.saved_version()),
7560 mtime: Some(buffer.saved_mtime().into()),
7561 fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7562 })?)
7563 }
7564
7565 async fn handle_reload_buffers(
7566 this: Model<Self>,
7567 envelope: TypedEnvelope<proto::ReloadBuffers>,
7568 _: Arc<Client>,
7569 mut cx: AsyncAppContext,
7570 ) -> Result<proto::ReloadBuffersResponse> {
7571 let sender_id = envelope.original_sender_id()?;
7572 let reload = this.update(&mut cx, |this, cx| {
7573 let mut buffers = HashSet::default();
7574 for buffer_id in &envelope.payload.buffer_ids {
7575 buffers.insert(
7576 this.opened_buffers
7577 .get(buffer_id)
7578 .and_then(|buffer| buffer.upgrade())
7579 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7580 );
7581 }
7582 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7583 })??;
7584
7585 let project_transaction = reload.await?;
7586 let project_transaction = this.update(&mut cx, |this, cx| {
7587 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7588 })?;
7589 Ok(proto::ReloadBuffersResponse {
7590 transaction: Some(project_transaction),
7591 })
7592 }
7593
7594 async fn handle_synchronize_buffers(
7595 this: Model<Self>,
7596 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7597 _: Arc<Client>,
7598 mut cx: AsyncAppContext,
7599 ) -> Result<proto::SynchronizeBuffersResponse> {
7600 let project_id = envelope.payload.project_id;
7601 let mut response = proto::SynchronizeBuffersResponse {
7602 buffers: Default::default(),
7603 };
7604
7605 this.update(&mut cx, |this, cx| {
7606 let Some(guest_id) = envelope.original_sender_id else {
7607 error!("missing original_sender_id on SynchronizeBuffers request");
7608 return;
7609 };
7610
7611 this.shared_buffers.entry(guest_id).or_default().clear();
7612 for buffer in envelope.payload.buffers {
7613 let buffer_id = buffer.id;
7614 let remote_version = language::proto::deserialize_version(&buffer.version);
7615 if let Some(buffer) = this.buffer_for_id(buffer_id) {
7616 this.shared_buffers
7617 .entry(guest_id)
7618 .or_default()
7619 .insert(buffer_id);
7620
7621 let buffer = buffer.read(cx);
7622 response.buffers.push(proto::BufferVersion {
7623 id: buffer_id,
7624 version: language::proto::serialize_version(&buffer.version),
7625 });
7626
7627 let operations = buffer.serialize_ops(Some(remote_version), cx);
7628 let client = this.client.clone();
7629 if let Some(file) = buffer.file() {
7630 client
7631 .send(proto::UpdateBufferFile {
7632 project_id,
7633 buffer_id: buffer_id as u64,
7634 file: Some(file.to_proto()),
7635 })
7636 .log_err();
7637 }
7638
7639 client
7640 .send(proto::UpdateDiffBase {
7641 project_id,
7642 buffer_id: buffer_id as u64,
7643 diff_base: buffer.diff_base().map(Into::into),
7644 })
7645 .log_err();
7646
7647 client
7648 .send(proto::BufferReloaded {
7649 project_id,
7650 buffer_id,
7651 version: language::proto::serialize_version(buffer.saved_version()),
7652 mtime: Some(buffer.saved_mtime().into()),
7653 fingerprint: language::proto::serialize_fingerprint(
7654 buffer.saved_version_fingerprint(),
7655 ),
7656 line_ending: language::proto::serialize_line_ending(
7657 buffer.line_ending(),
7658 ) as i32,
7659 })
7660 .log_err();
7661
7662 cx.background_executor()
7663 .spawn(
7664 async move {
7665 let operations = operations.await;
7666 for chunk in split_operations(operations) {
7667 client
7668 .request(proto::UpdateBuffer {
7669 project_id,
7670 buffer_id,
7671 operations: chunk,
7672 })
7673 .await?;
7674 }
7675 anyhow::Ok(())
7676 }
7677 .log_err(),
7678 )
7679 .detach();
7680 }
7681 }
7682 })?;
7683
7684 Ok(response)
7685 }
7686
7687 async fn handle_format_buffers(
7688 this: Model<Self>,
7689 envelope: TypedEnvelope<proto::FormatBuffers>,
7690 _: Arc<Client>,
7691 mut cx: AsyncAppContext,
7692 ) -> Result<proto::FormatBuffersResponse> {
7693 let sender_id = envelope.original_sender_id()?;
7694 let format = this.update(&mut cx, |this, cx| {
7695 let mut buffers = HashSet::default();
7696 for buffer_id in &envelope.payload.buffer_ids {
7697 buffers.insert(
7698 this.opened_buffers
7699 .get(buffer_id)
7700 .and_then(|buffer| buffer.upgrade())
7701 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7702 );
7703 }
7704 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7705 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7706 })??;
7707
7708 let project_transaction = format.await?;
7709 let project_transaction = this.update(&mut cx, |this, cx| {
7710 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7711 })?;
7712 Ok(proto::FormatBuffersResponse {
7713 transaction: Some(project_transaction),
7714 })
7715 }
7716
7717 async fn handle_apply_additional_edits_for_completion(
7718 this: Model<Self>,
7719 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7720 _: Arc<Client>,
7721 mut cx: AsyncAppContext,
7722 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7723 let (buffer, completion) = this.update(&mut cx, |this, cx| {
7724 let buffer = this
7725 .opened_buffers
7726 .get(&envelope.payload.buffer_id)
7727 .and_then(|buffer| buffer.upgrade())
7728 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7729 let language = buffer.read(cx).language();
7730 let completion = language::proto::deserialize_completion(
7731 envelope
7732 .payload
7733 .completion
7734 .ok_or_else(|| anyhow!("invalid completion"))?,
7735 language.cloned(),
7736 );
7737 Ok::<_, anyhow::Error>((buffer, completion))
7738 })??;
7739
7740 let completion = completion.await?;
7741
7742 let apply_additional_edits = this.update(&mut cx, |this, cx| {
7743 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7744 })?;
7745
7746 Ok(proto::ApplyCompletionAdditionalEditsResponse {
7747 transaction: apply_additional_edits
7748 .await?
7749 .as_ref()
7750 .map(language::proto::serialize_transaction),
7751 })
7752 }
7753
7754 async fn handle_apply_code_action(
7755 this: Model<Self>,
7756 envelope: TypedEnvelope<proto::ApplyCodeAction>,
7757 _: Arc<Client>,
7758 mut cx: AsyncAppContext,
7759 ) -> Result<proto::ApplyCodeActionResponse> {
7760 let sender_id = envelope.original_sender_id()?;
7761 let action = language::proto::deserialize_code_action(
7762 envelope
7763 .payload
7764 .action
7765 .ok_or_else(|| anyhow!("invalid action"))?,
7766 )?;
7767 let apply_code_action = this.update(&mut cx, |this, cx| {
7768 let buffer = this
7769 .opened_buffers
7770 .get(&envelope.payload.buffer_id)
7771 .and_then(|buffer| buffer.upgrade())
7772 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7773 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7774 })??;
7775
7776 let project_transaction = apply_code_action.await?;
7777 let project_transaction = this.update(&mut cx, |this, cx| {
7778 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7779 })?;
7780 Ok(proto::ApplyCodeActionResponse {
7781 transaction: Some(project_transaction),
7782 })
7783 }
7784
7785 async fn handle_on_type_formatting(
7786 this: Model<Self>,
7787 envelope: TypedEnvelope<proto::OnTypeFormatting>,
7788 _: Arc<Client>,
7789 mut cx: AsyncAppContext,
7790 ) -> Result<proto::OnTypeFormattingResponse> {
7791 let on_type_formatting = this.update(&mut cx, |this, cx| {
7792 let buffer = this
7793 .opened_buffers
7794 .get(&envelope.payload.buffer_id)
7795 .and_then(|buffer| buffer.upgrade())
7796 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7797 let position = envelope
7798 .payload
7799 .position
7800 .and_then(deserialize_anchor)
7801 .ok_or_else(|| anyhow!("invalid position"))?;
7802 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7803 buffer,
7804 position,
7805 envelope.payload.trigger.clone(),
7806 cx,
7807 ))
7808 })??;
7809
7810 let transaction = on_type_formatting
7811 .await?
7812 .as_ref()
7813 .map(language::proto::serialize_transaction);
7814 Ok(proto::OnTypeFormattingResponse { transaction })
7815 }
7816
7817 async fn handle_inlay_hints(
7818 this: Model<Self>,
7819 envelope: TypedEnvelope<proto::InlayHints>,
7820 _: Arc<Client>,
7821 mut cx: AsyncAppContext,
7822 ) -> Result<proto::InlayHintsResponse> {
7823 let sender_id = envelope.original_sender_id()?;
7824 let buffer = this.update(&mut cx, |this, _| {
7825 this.opened_buffers
7826 .get(&envelope.payload.buffer_id)
7827 .and_then(|buffer| buffer.upgrade())
7828 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7829 })??;
7830 let buffer_version = deserialize_version(&envelope.payload.version);
7831
7832 buffer
7833 .update(&mut cx, |buffer, _| {
7834 buffer.wait_for_version(buffer_version.clone())
7835 })?
7836 .await
7837 .with_context(|| {
7838 format!(
7839 "waiting for version {:?} for buffer {}",
7840 buffer_version,
7841 buffer.entity_id()
7842 )
7843 })?;
7844
7845 let start = envelope
7846 .payload
7847 .start
7848 .and_then(deserialize_anchor)
7849 .context("missing range start")?;
7850 let end = envelope
7851 .payload
7852 .end
7853 .and_then(deserialize_anchor)
7854 .context("missing range end")?;
7855 let buffer_hints = this
7856 .update(&mut cx, |project, cx| {
7857 project.inlay_hints(buffer, start..end, cx)
7858 })?
7859 .await
7860 .context("inlay hints fetch")?;
7861
7862 Ok(this.update(&mut cx, |project, cx| {
7863 InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7864 })?)
7865 }
7866
7867 async fn handle_resolve_inlay_hint(
7868 this: Model<Self>,
7869 envelope: TypedEnvelope<proto::ResolveInlayHint>,
7870 _: Arc<Client>,
7871 mut cx: AsyncAppContext,
7872 ) -> Result<proto::ResolveInlayHintResponse> {
7873 let proto_hint = envelope
7874 .payload
7875 .hint
7876 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7877 let hint = InlayHints::proto_to_project_hint(proto_hint)
7878 .context("resolved proto inlay hint conversion")?;
7879 let buffer = this.update(&mut cx, |this, _cx| {
7880 this.opened_buffers
7881 .get(&envelope.payload.buffer_id)
7882 .and_then(|buffer| buffer.upgrade())
7883 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7884 })??;
7885 let response_hint = this
7886 .update(&mut cx, |project, cx| {
7887 project.resolve_inlay_hint(
7888 hint,
7889 buffer,
7890 LanguageServerId(envelope.payload.language_server_id as usize),
7891 cx,
7892 )
7893 })?
7894 .await
7895 .context("inlay hints fetch")?;
7896 Ok(proto::ResolveInlayHintResponse {
7897 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7898 })
7899 }
7900
7901 async fn handle_refresh_inlay_hints(
7902 this: Model<Self>,
7903 _: TypedEnvelope<proto::RefreshInlayHints>,
7904 _: Arc<Client>,
7905 mut cx: AsyncAppContext,
7906 ) -> Result<proto::Ack> {
7907 this.update(&mut cx, |_, cx| {
7908 cx.emit(Event::RefreshInlayHints);
7909 })?;
7910 Ok(proto::Ack {})
7911 }
7912
7913 async fn handle_lsp_command<T: LspCommand>(
7914 this: Model<Self>,
7915 envelope: TypedEnvelope<T::ProtoRequest>,
7916 _: Arc<Client>,
7917 mut cx: AsyncAppContext,
7918 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7919 where
7920 <T::LspRequest as lsp::request::Request>::Params: Send,
7921 <T::LspRequest as lsp::request::Request>::Result: Send,
7922 {
7923 let sender_id = envelope.original_sender_id()?;
7924 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
7925 let buffer_handle = this.update(&mut cx, |this, _cx| {
7926 this.opened_buffers
7927 .get(&buffer_id)
7928 .and_then(|buffer| buffer.upgrade())
7929 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7930 })??;
7931 let request = T::from_proto(
7932 envelope.payload,
7933 this.clone(),
7934 buffer_handle.clone(),
7935 cx.clone(),
7936 )
7937 .await?;
7938 let buffer_version = buffer_handle.update(&mut cx, |buffer, _| buffer.version())?;
7939 let response = this
7940 .update(&mut cx, |this, cx| {
7941 this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
7942 })?
7943 .await?;
7944 this.update(&mut cx, |this, cx| {
7945 Ok(T::response_to_proto(
7946 response,
7947 this,
7948 sender_id,
7949 &buffer_version,
7950 cx,
7951 ))
7952 })?
7953 }
7954
7955 async fn handle_get_project_symbols(
7956 this: Model<Self>,
7957 envelope: TypedEnvelope<proto::GetProjectSymbols>,
7958 _: Arc<Client>,
7959 mut cx: AsyncAppContext,
7960 ) -> Result<proto::GetProjectSymbolsResponse> {
7961 let symbols = this
7962 .update(&mut cx, |this, cx| {
7963 this.symbols(&envelope.payload.query, cx)
7964 })?
7965 .await?;
7966
7967 Ok(proto::GetProjectSymbolsResponse {
7968 symbols: symbols.iter().map(serialize_symbol).collect(),
7969 })
7970 }
7971
7972 async fn handle_search_project(
7973 this: Model<Self>,
7974 envelope: TypedEnvelope<proto::SearchProject>,
7975 _: Arc<Client>,
7976 mut cx: AsyncAppContext,
7977 ) -> Result<proto::SearchProjectResponse> {
7978 let peer_id = envelope.original_sender_id()?;
7979 let query = SearchQuery::from_proto(envelope.payload)?;
7980 let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
7981
7982 cx.spawn(move |mut cx| async move {
7983 let mut locations = Vec::new();
7984 while let Some((buffer, ranges)) = result.next().await {
7985 for range in ranges {
7986 let start = serialize_anchor(&range.start);
7987 let end = serialize_anchor(&range.end);
7988 let buffer_id = this.update(&mut cx, |this, cx| {
7989 this.create_buffer_for_peer(&buffer, peer_id, cx)
7990 })?;
7991 locations.push(proto::Location {
7992 buffer_id,
7993 start: Some(start),
7994 end: Some(end),
7995 });
7996 }
7997 }
7998 Ok(proto::SearchProjectResponse { locations })
7999 })
8000 .await
8001 }
8002
8003 async fn handle_open_buffer_for_symbol(
8004 this: Model<Self>,
8005 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
8006 _: Arc<Client>,
8007 mut cx: AsyncAppContext,
8008 ) -> Result<proto::OpenBufferForSymbolResponse> {
8009 let peer_id = envelope.original_sender_id()?;
8010 let symbol = envelope
8011 .payload
8012 .symbol
8013 .ok_or_else(|| anyhow!("invalid symbol"))?;
8014 let symbol = this
8015 .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
8016 .await?;
8017 let symbol = this.update(&mut cx, |this, _| {
8018 let signature = this.symbol_signature(&symbol.path);
8019 if signature == symbol.signature {
8020 Ok(symbol)
8021 } else {
8022 Err(anyhow!("invalid symbol signature"))
8023 }
8024 })??;
8025 let buffer = this
8026 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
8027 .await?;
8028
8029 Ok(proto::OpenBufferForSymbolResponse {
8030 buffer_id: this.update(&mut cx, |this, cx| {
8031 this.create_buffer_for_peer(&buffer, peer_id, cx)
8032 })?,
8033 })
8034 }
8035
8036 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
8037 let mut hasher = Sha256::new();
8038 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
8039 hasher.update(project_path.path.to_string_lossy().as_bytes());
8040 hasher.update(self.nonce.to_be_bytes());
8041 hasher.finalize().as_slice().try_into().unwrap()
8042 }
8043
8044 async fn handle_open_buffer_by_id(
8045 this: Model<Self>,
8046 envelope: TypedEnvelope<proto::OpenBufferById>,
8047 _: Arc<Client>,
8048 mut cx: AsyncAppContext,
8049 ) -> Result<proto::OpenBufferResponse> {
8050 let peer_id = envelope.original_sender_id()?;
8051 let buffer = this
8052 .update(&mut cx, |this, cx| {
8053 this.open_buffer_by_id(envelope.payload.id, cx)
8054 })?
8055 .await?;
8056 this.update(&mut cx, |this, cx| {
8057 Ok(proto::OpenBufferResponse {
8058 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
8059 })
8060 })?
8061 }
8062
8063 async fn handle_open_buffer_by_path(
8064 this: Model<Self>,
8065 envelope: TypedEnvelope<proto::OpenBufferByPath>,
8066 _: Arc<Client>,
8067 mut cx: AsyncAppContext,
8068 ) -> Result<proto::OpenBufferResponse> {
8069 let peer_id = envelope.original_sender_id()?;
8070 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8071 let open_buffer = this.update(&mut cx, |this, cx| {
8072 this.open_buffer(
8073 ProjectPath {
8074 worktree_id,
8075 path: PathBuf::from(envelope.payload.path).into(),
8076 },
8077 cx,
8078 )
8079 })?;
8080
8081 let buffer = open_buffer.await?;
8082 this.update(&mut cx, |this, cx| {
8083 Ok(proto::OpenBufferResponse {
8084 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
8085 })
8086 })?
8087 }
8088
8089 fn serialize_project_transaction_for_peer(
8090 &mut self,
8091 project_transaction: ProjectTransaction,
8092 peer_id: proto::PeerId,
8093 cx: &mut AppContext,
8094 ) -> proto::ProjectTransaction {
8095 let mut serialized_transaction = proto::ProjectTransaction {
8096 buffer_ids: Default::default(),
8097 transactions: Default::default(),
8098 };
8099 for (buffer, transaction) in project_transaction.0 {
8100 serialized_transaction
8101 .buffer_ids
8102 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
8103 serialized_transaction
8104 .transactions
8105 .push(language::proto::serialize_transaction(&transaction));
8106 }
8107 serialized_transaction
8108 }
8109
8110 fn deserialize_project_transaction(
8111 &mut self,
8112 message: proto::ProjectTransaction,
8113 push_to_history: bool,
8114 cx: &mut ModelContext<Self>,
8115 ) -> Task<Result<ProjectTransaction>> {
8116 cx.spawn(move |this, mut cx| async move {
8117 let mut project_transaction = ProjectTransaction::default();
8118 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
8119 {
8120 let buffer = this
8121 .update(&mut cx, |this, cx| {
8122 this.wait_for_remote_buffer(buffer_id, cx)
8123 })?
8124 .await?;
8125 let transaction = language::proto::deserialize_transaction(transaction)?;
8126 project_transaction.0.insert(buffer, transaction);
8127 }
8128
8129 for (buffer, transaction) in &project_transaction.0 {
8130 buffer
8131 .update(&mut cx, |buffer, _| {
8132 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
8133 })?
8134 .await?;
8135
8136 if push_to_history {
8137 buffer.update(&mut cx, |buffer, _| {
8138 buffer.push_transaction(transaction.clone(), Instant::now());
8139 })?;
8140 }
8141 }
8142
8143 Ok(project_transaction)
8144 })
8145 }
8146
8147 fn create_buffer_for_peer(
8148 &mut self,
8149 buffer: &Model<Buffer>,
8150 peer_id: proto::PeerId,
8151 cx: &mut AppContext,
8152 ) -> u64 {
8153 let buffer_id = buffer.read(cx).remote_id();
8154 if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
8155 updates_tx
8156 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
8157 .ok();
8158 }
8159 buffer_id
8160 }
8161
8162 fn wait_for_remote_buffer(
8163 &mut self,
8164 id: u64,
8165 cx: &mut ModelContext<Self>,
8166 ) -> Task<Result<Model<Buffer>>> {
8167 let mut opened_buffer_rx = self.opened_buffer.1.clone();
8168
8169 cx.spawn(move |this, mut cx| async move {
8170 let buffer = loop {
8171 let Some(this) = this.upgrade() else {
8172 return Err(anyhow!("project dropped"));
8173 };
8174
8175 let buffer = this.update(&mut cx, |this, _cx| {
8176 this.opened_buffers
8177 .get(&id)
8178 .and_then(|buffer| buffer.upgrade())
8179 })?;
8180
8181 if let Some(buffer) = buffer {
8182 break buffer;
8183 } else if this.update(&mut cx, |this, _| this.is_disconnected())? {
8184 return Err(anyhow!("disconnected before buffer {} could be opened", id));
8185 }
8186
8187 this.update(&mut cx, |this, _| {
8188 this.incomplete_remote_buffers.entry(id).or_default();
8189 })?;
8190 drop(this);
8191
8192 opened_buffer_rx
8193 .next()
8194 .await
8195 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
8196 };
8197
8198 Ok(buffer)
8199 })
8200 }
8201
8202 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
8203 let project_id = match self.client_state {
8204 ProjectClientState::Remote {
8205 sharing_has_stopped,
8206 remote_id,
8207 ..
8208 } => {
8209 if sharing_has_stopped {
8210 return Task::ready(Err(anyhow!(
8211 "can't synchronize remote buffers on a readonly project"
8212 )));
8213 } else {
8214 remote_id
8215 }
8216 }
8217 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
8218 return Task::ready(Err(anyhow!(
8219 "can't synchronize remote buffers on a local project"
8220 )))
8221 }
8222 };
8223
8224 let client = self.client.clone();
8225 cx.spawn(move |this, mut cx| async move {
8226 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
8227 let buffers = this
8228 .opened_buffers
8229 .iter()
8230 .filter_map(|(id, buffer)| {
8231 let buffer = buffer.upgrade()?;
8232 Some(proto::BufferVersion {
8233 id: *id,
8234 version: language::proto::serialize_version(&buffer.read(cx).version),
8235 })
8236 })
8237 .collect();
8238 let incomplete_buffer_ids = this
8239 .incomplete_remote_buffers
8240 .keys()
8241 .copied()
8242 .collect::<Vec<_>>();
8243
8244 (buffers, incomplete_buffer_ids)
8245 })?;
8246 let response = client
8247 .request(proto::SynchronizeBuffers {
8248 project_id,
8249 buffers,
8250 })
8251 .await?;
8252
8253 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8254 response
8255 .buffers
8256 .into_iter()
8257 .map(|buffer| {
8258 let client = client.clone();
8259 let buffer_id = buffer.id;
8260 let remote_version = language::proto::deserialize_version(&buffer.version);
8261 if let Some(buffer) = this.buffer_for_id(buffer_id) {
8262 let operations =
8263 buffer.read(cx).serialize_ops(Some(remote_version), cx);
8264 cx.background_executor().spawn(async move {
8265 let operations = operations.await;
8266 for chunk in split_operations(operations) {
8267 client
8268 .request(proto::UpdateBuffer {
8269 project_id,
8270 buffer_id,
8271 operations: chunk,
8272 })
8273 .await?;
8274 }
8275 anyhow::Ok(())
8276 })
8277 } else {
8278 Task::ready(Ok(()))
8279 }
8280 })
8281 .collect::<Vec<_>>()
8282 })?;
8283
8284 // Any incomplete buffers have open requests waiting. Request that the host sends
8285 // creates these buffers for us again to unblock any waiting futures.
8286 for id in incomplete_buffer_ids {
8287 cx.background_executor()
8288 .spawn(client.request(proto::OpenBufferById { project_id, id }))
8289 .detach();
8290 }
8291
8292 futures::future::join_all(send_updates_for_buffers)
8293 .await
8294 .into_iter()
8295 .collect()
8296 })
8297 }
8298
8299 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8300 self.worktrees()
8301 .map(|worktree| {
8302 let worktree = worktree.read(cx);
8303 proto::WorktreeMetadata {
8304 id: worktree.id().to_proto(),
8305 root_name: worktree.root_name().into(),
8306 visible: worktree.is_visible(),
8307 abs_path: worktree.abs_path().to_string_lossy().into(),
8308 }
8309 })
8310 .collect()
8311 }
8312
8313 fn set_worktrees_from_proto(
8314 &mut self,
8315 worktrees: Vec<proto::WorktreeMetadata>,
8316 cx: &mut ModelContext<Project>,
8317 ) -> Result<()> {
8318 let replica_id = self.replica_id();
8319 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8320
8321 let mut old_worktrees_by_id = self
8322 .worktrees
8323 .drain(..)
8324 .filter_map(|worktree| {
8325 let worktree = worktree.upgrade()?;
8326 Some((worktree.read(cx).id(), worktree))
8327 })
8328 .collect::<HashMap<_, _>>();
8329
8330 for worktree in worktrees {
8331 if let Some(old_worktree) =
8332 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8333 {
8334 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8335 } else {
8336 let worktree =
8337 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8338 let _ = self.add_worktree(&worktree, cx);
8339 }
8340 }
8341
8342 self.metadata_changed(cx);
8343 for id in old_worktrees_by_id.keys() {
8344 cx.emit(Event::WorktreeRemoved(*id));
8345 }
8346
8347 Ok(())
8348 }
8349
8350 fn set_collaborators_from_proto(
8351 &mut self,
8352 messages: Vec<proto::Collaborator>,
8353 cx: &mut ModelContext<Self>,
8354 ) -> Result<()> {
8355 let mut collaborators = HashMap::default();
8356 for message in messages {
8357 let collaborator = Collaborator::from_proto(message)?;
8358 collaborators.insert(collaborator.peer_id, collaborator);
8359 }
8360 for old_peer_id in self.collaborators.keys() {
8361 if !collaborators.contains_key(old_peer_id) {
8362 cx.emit(Event::CollaboratorLeft(*old_peer_id));
8363 }
8364 }
8365 self.collaborators = collaborators;
8366 Ok(())
8367 }
8368
8369 fn deserialize_symbol(
8370 &self,
8371 serialized_symbol: proto::Symbol,
8372 ) -> impl Future<Output = Result<Symbol>> {
8373 let languages = self.languages.clone();
8374 async move {
8375 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8376 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8377 let start = serialized_symbol
8378 .start
8379 .ok_or_else(|| anyhow!("invalid start"))?;
8380 let end = serialized_symbol
8381 .end
8382 .ok_or_else(|| anyhow!("invalid end"))?;
8383 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8384 let path = ProjectPath {
8385 worktree_id,
8386 path: PathBuf::from(serialized_symbol.path).into(),
8387 };
8388 let language = languages
8389 .language_for_file(&path.path, None)
8390 .await
8391 .log_err();
8392 Ok(Symbol {
8393 language_server_name: LanguageServerName(
8394 serialized_symbol.language_server_name.into(),
8395 ),
8396 source_worktree_id,
8397 path,
8398 label: {
8399 match language {
8400 Some(language) => {
8401 language
8402 .label_for_symbol(&serialized_symbol.name, kind)
8403 .await
8404 }
8405 None => None,
8406 }
8407 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8408 },
8409
8410 name: serialized_symbol.name,
8411 range: Unclipped(PointUtf16::new(start.row, start.column))
8412 ..Unclipped(PointUtf16::new(end.row, end.column)),
8413 kind,
8414 signature: serialized_symbol
8415 .signature
8416 .try_into()
8417 .map_err(|_| anyhow!("invalid signature"))?,
8418 })
8419 }
8420 }
8421
8422 async fn handle_buffer_saved(
8423 this: Model<Self>,
8424 envelope: TypedEnvelope<proto::BufferSaved>,
8425 _: Arc<Client>,
8426 mut cx: AsyncAppContext,
8427 ) -> Result<()> {
8428 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8429 let version = deserialize_version(&envelope.payload.version);
8430 let mtime = envelope
8431 .payload
8432 .mtime
8433 .ok_or_else(|| anyhow!("missing mtime"))?
8434 .into();
8435
8436 this.update(&mut cx, |this, cx| {
8437 let buffer = this
8438 .opened_buffers
8439 .get(&envelope.payload.buffer_id)
8440 .and_then(|buffer| buffer.upgrade())
8441 .or_else(|| {
8442 this.incomplete_remote_buffers
8443 .get(&envelope.payload.buffer_id)
8444 .and_then(|b| b.clone())
8445 });
8446 if let Some(buffer) = buffer {
8447 buffer.update(cx, |buffer, cx| {
8448 buffer.did_save(version, fingerprint, mtime, cx);
8449 });
8450 }
8451 Ok(())
8452 })?
8453 }
8454
8455 async fn handle_buffer_reloaded(
8456 this: Model<Self>,
8457 envelope: TypedEnvelope<proto::BufferReloaded>,
8458 _: Arc<Client>,
8459 mut cx: AsyncAppContext,
8460 ) -> Result<()> {
8461 let payload = envelope.payload;
8462 let version = deserialize_version(&payload.version);
8463 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8464 let line_ending = deserialize_line_ending(
8465 proto::LineEnding::from_i32(payload.line_ending)
8466 .ok_or_else(|| anyhow!("missing line ending"))?,
8467 );
8468 let mtime = payload
8469 .mtime
8470 .ok_or_else(|| anyhow!("missing mtime"))?
8471 .into();
8472 this.update(&mut cx, |this, cx| {
8473 let buffer = this
8474 .opened_buffers
8475 .get(&payload.buffer_id)
8476 .and_then(|buffer| buffer.upgrade())
8477 .or_else(|| {
8478 this.incomplete_remote_buffers
8479 .get(&payload.buffer_id)
8480 .cloned()
8481 .flatten()
8482 });
8483 if let Some(buffer) = buffer {
8484 buffer.update(cx, |buffer, cx| {
8485 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8486 });
8487 }
8488 Ok(())
8489 })?
8490 }
8491
8492 #[allow(clippy::type_complexity)]
8493 fn edits_from_lsp(
8494 &mut self,
8495 buffer: &Model<Buffer>,
8496 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8497 server_id: LanguageServerId,
8498 version: Option<i32>,
8499 cx: &mut ModelContext<Self>,
8500 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8501 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8502 cx.background_executor().spawn(async move {
8503 let snapshot = snapshot?;
8504 let mut lsp_edits = lsp_edits
8505 .into_iter()
8506 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8507 .collect::<Vec<_>>();
8508 lsp_edits.sort_by_key(|(range, _)| range.start);
8509
8510 let mut lsp_edits = lsp_edits.into_iter().peekable();
8511 let mut edits = Vec::new();
8512 while let Some((range, mut new_text)) = lsp_edits.next() {
8513 // Clip invalid ranges provided by the language server.
8514 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8515 ..snapshot.clip_point_utf16(range.end, Bias::Left);
8516
8517 // Combine any LSP edits that are adjacent.
8518 //
8519 // Also, combine LSP edits that are separated from each other by only
8520 // a newline. This is important because for some code actions,
8521 // Rust-analyzer rewrites the entire buffer via a series of edits that
8522 // are separated by unchanged newline characters.
8523 //
8524 // In order for the diffing logic below to work properly, any edits that
8525 // cancel each other out must be combined into one.
8526 while let Some((next_range, next_text)) = lsp_edits.peek() {
8527 if next_range.start.0 > range.end {
8528 if next_range.start.0.row > range.end.row + 1
8529 || next_range.start.0.column > 0
8530 || snapshot.clip_point_utf16(
8531 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8532 Bias::Left,
8533 ) > range.end
8534 {
8535 break;
8536 }
8537 new_text.push('\n');
8538 }
8539 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8540 new_text.push_str(next_text);
8541 lsp_edits.next();
8542 }
8543
8544 // For multiline edits, perform a diff of the old and new text so that
8545 // we can identify the changes more precisely, preserving the locations
8546 // of any anchors positioned in the unchanged regions.
8547 if range.end.row > range.start.row {
8548 let mut offset = range.start.to_offset(&snapshot);
8549 let old_text = snapshot.text_for_range(range).collect::<String>();
8550
8551 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8552 let mut moved_since_edit = true;
8553 for change in diff.iter_all_changes() {
8554 let tag = change.tag();
8555 let value = change.value();
8556 match tag {
8557 ChangeTag::Equal => {
8558 offset += value.len();
8559 moved_since_edit = true;
8560 }
8561 ChangeTag::Delete => {
8562 let start = snapshot.anchor_after(offset);
8563 let end = snapshot.anchor_before(offset + value.len());
8564 if moved_since_edit {
8565 edits.push((start..end, String::new()));
8566 } else {
8567 edits.last_mut().unwrap().0.end = end;
8568 }
8569 offset += value.len();
8570 moved_since_edit = false;
8571 }
8572 ChangeTag::Insert => {
8573 if moved_since_edit {
8574 let anchor = snapshot.anchor_after(offset);
8575 edits.push((anchor..anchor, value.to_string()));
8576 } else {
8577 edits.last_mut().unwrap().1.push_str(value);
8578 }
8579 moved_since_edit = false;
8580 }
8581 }
8582 }
8583 } else if range.end == range.start {
8584 let anchor = snapshot.anchor_after(range.start);
8585 edits.push((anchor..anchor, new_text));
8586 } else {
8587 let edit_start = snapshot.anchor_after(range.start);
8588 let edit_end = snapshot.anchor_before(range.end);
8589 edits.push((edit_start..edit_end, new_text));
8590 }
8591 }
8592
8593 Ok(edits)
8594 })
8595 }
8596
8597 fn buffer_snapshot_for_lsp_version(
8598 &mut self,
8599 buffer: &Model<Buffer>,
8600 server_id: LanguageServerId,
8601 version: Option<i32>,
8602 cx: &AppContext,
8603 ) -> Result<TextBufferSnapshot> {
8604 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8605
8606 if let Some(version) = version {
8607 let buffer_id = buffer.read(cx).remote_id();
8608 let snapshots = self
8609 .buffer_snapshots
8610 .get_mut(&buffer_id)
8611 .and_then(|m| m.get_mut(&server_id))
8612 .ok_or_else(|| {
8613 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
8614 })?;
8615
8616 let found_snapshot = snapshots
8617 .binary_search_by_key(&version, |e| e.version)
8618 .map(|ix| snapshots[ix].snapshot.clone())
8619 .map_err(|_| {
8620 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
8621 })?;
8622
8623 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
8624 Ok(found_snapshot)
8625 } else {
8626 Ok((buffer.read(cx)).text_snapshot())
8627 }
8628 }
8629
8630 pub fn language_servers(
8631 &self,
8632 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
8633 self.language_server_ids
8634 .iter()
8635 .map(|((worktree_id, server_name), server_id)| {
8636 (*server_id, server_name.clone(), *worktree_id)
8637 })
8638 }
8639
8640 pub fn supplementary_language_servers(
8641 &self,
8642 ) -> impl '_
8643 + Iterator<
8644 Item = (
8645 &LanguageServerId,
8646 &(LanguageServerName, Arc<LanguageServer>),
8647 ),
8648 > {
8649 self.supplementary_language_servers.iter()
8650 }
8651
8652 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8653 if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
8654 Some(server.clone())
8655 } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
8656 Some(Arc::clone(server))
8657 } else {
8658 None
8659 }
8660 }
8661
8662 pub fn language_servers_for_buffer(
8663 &self,
8664 buffer: &Buffer,
8665 cx: &AppContext,
8666 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8667 self.language_server_ids_for_buffer(buffer, cx)
8668 .into_iter()
8669 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
8670 LanguageServerState::Running {
8671 adapter, server, ..
8672 } => Some((adapter, server)),
8673 _ => None,
8674 })
8675 }
8676
8677 fn primary_language_server_for_buffer(
8678 &self,
8679 buffer: &Buffer,
8680 cx: &AppContext,
8681 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8682 self.language_servers_for_buffer(buffer, cx).next()
8683 }
8684
8685 pub fn language_server_for_buffer(
8686 &self,
8687 buffer: &Buffer,
8688 server_id: LanguageServerId,
8689 cx: &AppContext,
8690 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8691 self.language_servers_for_buffer(buffer, cx)
8692 .find(|(_, s)| s.server_id() == server_id)
8693 }
8694
8695 fn language_server_ids_for_buffer(
8696 &self,
8697 buffer: &Buffer,
8698 cx: &AppContext,
8699 ) -> Vec<LanguageServerId> {
8700 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8701 let worktree_id = file.worktree_id(cx);
8702 language
8703 .lsp_adapters()
8704 .iter()
8705 .flat_map(|adapter| {
8706 let key = (worktree_id, adapter.name.clone());
8707 self.language_server_ids.get(&key).copied()
8708 })
8709 .collect()
8710 } else {
8711 Vec::new()
8712 }
8713 }
8714}
8715
8716fn subscribe_for_copilot_events(
8717 copilot: &Model<Copilot>,
8718 cx: &mut ModelContext<'_, Project>,
8719) -> gpui::Subscription {
8720 cx.subscribe(
8721 copilot,
8722 |project, copilot, copilot_event, cx| match copilot_event {
8723 copilot::Event::CopilotLanguageServerStarted => {
8724 match copilot.read(cx).language_server() {
8725 Some((name, copilot_server)) => {
8726 // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
8727 if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
8728 let new_server_id = copilot_server.server_id();
8729 let weak_project = cx.weak_model();
8730 let copilot_log_subscription = copilot_server
8731 .on_notification::<copilot::request::LogMessage, _>(
8732 move |params, mut cx| {
8733 weak_project.update(&mut cx, |_, cx| {
8734 cx.emit(Event::LanguageServerLog(
8735 new_server_id,
8736 params.message,
8737 ));
8738 }).ok();
8739 },
8740 );
8741 project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
8742 project.copilot_log_subscription = Some(copilot_log_subscription);
8743 cx.emit(Event::LanguageServerAdded(new_server_id));
8744 }
8745 }
8746 None => debug_panic!("Received Copilot language server started event, but no language server is running"),
8747 }
8748 }
8749 },
8750 )
8751}
8752
8753fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8754 let mut literal_end = 0;
8755 for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8756 if part.contains(&['*', '?', '{', '}']) {
8757 break;
8758 } else {
8759 if i > 0 {
8760 // Account for separator prior to this part
8761 literal_end += path::MAIN_SEPARATOR.len_utf8();
8762 }
8763 literal_end += part.len();
8764 }
8765 }
8766 &glob[..literal_end]
8767}
8768
8769impl WorktreeHandle {
8770 pub fn upgrade(&self) -> Option<Model<Worktree>> {
8771 match self {
8772 WorktreeHandle::Strong(handle) => Some(handle.clone()),
8773 WorktreeHandle::Weak(handle) => handle.upgrade(),
8774 }
8775 }
8776
8777 pub fn handle_id(&self) -> usize {
8778 match self {
8779 WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
8780 WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
8781 }
8782 }
8783}
8784
8785impl OpenBuffer {
8786 pub fn upgrade(&self) -> Option<Model<Buffer>> {
8787 match self {
8788 OpenBuffer::Strong(handle) => Some(handle.clone()),
8789 OpenBuffer::Weak(handle) => handle.upgrade(),
8790 OpenBuffer::Operations(_) => None,
8791 }
8792 }
8793}
8794
8795pub struct PathMatchCandidateSet {
8796 pub snapshot: Snapshot,
8797 pub include_ignored: bool,
8798 pub include_root_name: bool,
8799}
8800
8801impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
8802 type Candidates = PathMatchCandidateSetIter<'a>;
8803
8804 fn id(&self) -> usize {
8805 self.snapshot.id().to_usize()
8806 }
8807
8808 fn len(&self) -> usize {
8809 if self.include_ignored {
8810 self.snapshot.file_count()
8811 } else {
8812 self.snapshot.visible_file_count()
8813 }
8814 }
8815
8816 fn prefix(&self) -> Arc<str> {
8817 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
8818 self.snapshot.root_name().into()
8819 } else if self.include_root_name {
8820 format!("{}/", self.snapshot.root_name()).into()
8821 } else {
8822 "".into()
8823 }
8824 }
8825
8826 fn candidates(&'a self, start: usize) -> Self::Candidates {
8827 PathMatchCandidateSetIter {
8828 traversal: self.snapshot.files(self.include_ignored, start),
8829 }
8830 }
8831}
8832
8833pub struct PathMatchCandidateSetIter<'a> {
8834 traversal: Traversal<'a>,
8835}
8836
8837impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8838 type Item = fuzzy::PathMatchCandidate<'a>;
8839
8840 fn next(&mut self) -> Option<Self::Item> {
8841 self.traversal.next().map(|entry| {
8842 if let EntryKind::File(char_bag) = entry.kind {
8843 fuzzy::PathMatchCandidate {
8844 path: &entry.path,
8845 char_bag,
8846 }
8847 } else {
8848 unreachable!()
8849 }
8850 })
8851 }
8852}
8853
8854impl EventEmitter<Event> for Project {}
8855
8856impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8857 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8858 Self {
8859 worktree_id,
8860 path: path.as_ref().into(),
8861 }
8862 }
8863}
8864
8865impl ProjectLspAdapterDelegate {
8866 fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8867 Arc::new(Self {
8868 project: cx.handle(),
8869 http_client: project.client.http_client(),
8870 })
8871 }
8872}
8873
8874impl LspAdapterDelegate for ProjectLspAdapterDelegate {
8875 fn show_notification(&self, message: &str, cx: &mut AppContext) {
8876 self.project
8877 .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
8878 }
8879
8880 fn http_client(&self) -> Arc<dyn HttpClient> {
8881 self.http_client.clone()
8882 }
8883}
8884
8885fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
8886 proto::Symbol {
8887 language_server_name: symbol.language_server_name.0.to_string(),
8888 source_worktree_id: symbol.source_worktree_id.to_proto(),
8889 worktree_id: symbol.path.worktree_id.to_proto(),
8890 path: symbol.path.path.to_string_lossy().to_string(),
8891 name: symbol.name.clone(),
8892 kind: unsafe { mem::transmute(symbol.kind) },
8893 start: Some(proto::PointUtf16 {
8894 row: symbol.range.start.0.row,
8895 column: symbol.range.start.0.column,
8896 }),
8897 end: Some(proto::PointUtf16 {
8898 row: symbol.range.end.0.row,
8899 column: symbol.range.end.0.column,
8900 }),
8901 signature: symbol.signature.to_vec(),
8902 }
8903}
8904
8905fn relativize_path(base: &Path, path: &Path) -> PathBuf {
8906 let mut path_components = path.components();
8907 let mut base_components = base.components();
8908 let mut components: Vec<Component> = Vec::new();
8909 loop {
8910 match (path_components.next(), base_components.next()) {
8911 (None, None) => break,
8912 (Some(a), None) => {
8913 components.push(a);
8914 components.extend(path_components.by_ref());
8915 break;
8916 }
8917 (None, _) => components.push(Component::ParentDir),
8918 (Some(a), Some(b)) if components.is_empty() && a == b => (),
8919 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
8920 (Some(a), Some(_)) => {
8921 components.push(Component::ParentDir);
8922 for _ in base_components {
8923 components.push(Component::ParentDir);
8924 }
8925 components.push(a);
8926 components.extend(path_components.by_ref());
8927 break;
8928 }
8929 }
8930 }
8931 components.iter().map(|c| c.as_os_str()).collect()
8932}
8933
8934fn resolve_path(base: &Path, path: &Path) -> PathBuf {
8935 let mut result = base.to_path_buf();
8936 for component in path.components() {
8937 match component {
8938 Component::ParentDir => {
8939 result.pop();
8940 }
8941 Component::CurDir => (),
8942 _ => result.push(component),
8943 }
8944 }
8945 result
8946}
8947
8948impl Item for Buffer {
8949 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
8950 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
8951 }
8952
8953 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
8954 File::from_dyn(self.file()).map(|file| ProjectPath {
8955 worktree_id: file.worktree_id(cx),
8956 path: file.path().clone(),
8957 })
8958 }
8959}
8960
8961async fn wait_for_loading_buffer(
8962 mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
8963) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
8964 loop {
8965 if let Some(result) = receiver.borrow().as_ref() {
8966 match result {
8967 Ok(buffer) => return Ok(buffer.to_owned()),
8968 Err(e) => return Err(e.to_owned()),
8969 }
8970 }
8971 receiver.next().await;
8972 }
8973}
8974
8975fn include_text(server: &lsp::LanguageServer) -> bool {
8976 server
8977 .capabilities()
8978 .text_document_sync
8979 .as_ref()
8980 .and_then(|sync| match sync {
8981 lsp::TextDocumentSyncCapability::Kind(_) => None,
8982 lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
8983 })
8984 .and_then(|save_options| match save_options {
8985 lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
8986 lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
8987 })
8988 .unwrap_or(false)
8989}