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