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