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