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