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