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