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