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