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