1use crate::{
2 ProjectPath,
3 lsp_store::OpenLspBufferHandle,
4 worktree_store::{WorktreeStore, WorktreeStoreEvent},
5};
6use anyhow::{Context as _, Result, anyhow};
7use client::Client;
8use collections::{HashMap, HashSet, hash_map};
9use futures::{Future, FutureExt as _, channel::oneshot, future::Shared};
10use gpui::{
11 App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Subscription, Task, WeakEntity,
12};
13use language::{
14 Buffer, BufferEvent, Capability, DiskState, File as _, Language, Operation,
15 proto::{
16 deserialize_line_ending, deserialize_version, serialize_line_ending, serialize_version,
17 split_operations,
18 },
19};
20use rpc::{
21 AnyProtoClient, ErrorCode, ErrorExt as _, TypedEnvelope,
22 proto::{self},
23};
24
25use std::{io, sync::Arc, time::Instant};
26use text::{BufferId, ReplicaId};
27use util::{ResultExt as _, TryFutureExt, debug_panic, maybe, paths::PathStyle, rel_path::RelPath};
28use worktree::{File, PathChange, ProjectEntryId, Worktree, WorktreeId};
29
30/// A set of open buffers.
31pub struct BufferStore {
32 state: BufferStoreState,
33 #[allow(clippy::type_complexity)]
34 loading_buffers: HashMap<ProjectPath, Shared<Task<Result<Entity<Buffer>, Arc<anyhow::Error>>>>>,
35 worktree_store: Entity<WorktreeStore>,
36 opened_buffers: HashMap<BufferId, OpenBuffer>,
37 path_to_buffer_id: HashMap<ProjectPath, BufferId>,
38 downstream_client: Option<(AnyProtoClient, u64)>,
39 shared_buffers: HashMap<proto::PeerId, HashMap<BufferId, SharedBuffer>>,
40 non_searchable_buffers: HashSet<BufferId>,
41}
42
43#[derive(Hash, Eq, PartialEq, Clone)]
44struct SharedBuffer {
45 buffer: Entity<Buffer>,
46 lsp_handle: Option<OpenLspBufferHandle>,
47}
48
49enum BufferStoreState {
50 Local(LocalBufferStore),
51 Remote(RemoteBufferStore),
52}
53
54struct RemoteBufferStore {
55 shared_with_me: HashSet<Entity<Buffer>>,
56 upstream_client: AnyProtoClient,
57 project_id: u64,
58 loading_remote_buffers_by_id: HashMap<BufferId, Entity<Buffer>>,
59 remote_buffer_listeners:
60 HashMap<BufferId, Vec<oneshot::Sender<anyhow::Result<Entity<Buffer>>>>>,
61 worktree_store: Entity<WorktreeStore>,
62}
63
64struct LocalBufferStore {
65 local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
66 worktree_store: Entity<WorktreeStore>,
67 _subscription: Subscription,
68}
69
70enum OpenBuffer {
71 Complete { buffer: WeakEntity<Buffer> },
72 Operations(Vec<Operation>),
73}
74
75pub enum BufferStoreEvent {
76 BufferAdded(Entity<Buffer>),
77 BufferOpened {
78 buffer: Entity<Buffer>,
79 project_path: ProjectPath,
80 },
81 SharedBufferClosed(proto::PeerId, BufferId),
82 BufferDropped(BufferId),
83 BufferChangedFilePath {
84 buffer: Entity<Buffer>,
85 old_file: Option<Arc<dyn language::File>>,
86 },
87}
88
89#[derive(Default, Debug, Clone)]
90pub struct ProjectTransaction(pub HashMap<Entity<Buffer>, language::Transaction>);
91
92impl PartialEq for ProjectTransaction {
93 fn eq(&self, other: &Self) -> bool {
94 self.0.len() == other.0.len()
95 && self.0.iter().all(|(buffer, transaction)| {
96 other.0.get(buffer).is_some_and(|t| t.id == transaction.id)
97 })
98 }
99}
100
101impl EventEmitter<BufferStoreEvent> for BufferStore {}
102
103impl RemoteBufferStore {
104 pub fn wait_for_remote_buffer(
105 &mut self,
106 id: BufferId,
107 cx: &mut Context<BufferStore>,
108 ) -> Task<Result<Entity<Buffer>>> {
109 let (tx, rx) = oneshot::channel();
110 self.remote_buffer_listeners.entry(id).or_default().push(tx);
111
112 cx.spawn(async move |this, cx| {
113 if let Some(buffer) = this
114 .read_with(cx, |buffer_store, _| buffer_store.get(id))
115 .ok()
116 .flatten()
117 {
118 return Ok(buffer);
119 }
120
121 cx.background_spawn(async move { rx.await? }).await
122 })
123 }
124
125 fn save_remote_buffer(
126 &self,
127 buffer_handle: Entity<Buffer>,
128 new_path: Option<proto::ProjectPath>,
129 cx: &Context<BufferStore>,
130 ) -> Task<Result<()>> {
131 let buffer = buffer_handle.read(cx);
132 let buffer_id = buffer.remote_id().into();
133 let version = buffer.version();
134 let rpc = self.upstream_client.clone();
135 let project_id = self.project_id;
136 cx.spawn(async move |_, cx| {
137 let response = rpc
138 .request(proto::SaveBuffer {
139 project_id,
140 buffer_id,
141 new_path,
142 version: serialize_version(&version),
143 })
144 .await?;
145 let version = deserialize_version(&response.version);
146 let mtime = response.mtime.map(|mtime| mtime.into());
147
148 buffer_handle.update(cx, |buffer, cx| {
149 buffer.did_save(version.clone(), mtime, cx);
150 })?;
151
152 Ok(())
153 })
154 }
155
156 pub fn handle_create_buffer_for_peer(
157 &mut self,
158 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
159 replica_id: ReplicaId,
160 capability: Capability,
161 cx: &mut Context<BufferStore>,
162 ) -> Result<Option<Entity<Buffer>>> {
163 match envelope.payload.variant.context("missing variant")? {
164 proto::create_buffer_for_peer::Variant::State(mut state) => {
165 let buffer_id = BufferId::new(state.id)?;
166
167 let buffer_result = maybe!({
168 let mut buffer_file = None;
169 if let Some(file) = state.file.take() {
170 let worktree_id = worktree::WorktreeId::from_proto(file.worktree_id);
171 let worktree = self
172 .worktree_store
173 .read(cx)
174 .worktree_for_id(worktree_id, cx)
175 .with_context(|| {
176 format!("no worktree found for id {}", file.worktree_id)
177 })?;
178 buffer_file = Some(Arc::new(File::from_proto(file, worktree, cx)?)
179 as Arc<dyn language::File>);
180 }
181 Buffer::from_proto(replica_id, capability, state, buffer_file)
182 });
183
184 match buffer_result {
185 Ok(buffer) => {
186 let buffer = cx.new(|_| buffer);
187 self.loading_remote_buffers_by_id.insert(buffer_id, buffer);
188 }
189 Err(error) => {
190 if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
191 for listener in listeners {
192 listener.send(Err(anyhow!(error.cloned()))).ok();
193 }
194 }
195 }
196 }
197 }
198 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
199 let buffer_id = BufferId::new(chunk.buffer_id)?;
200 let buffer = self
201 .loading_remote_buffers_by_id
202 .get(&buffer_id)
203 .cloned()
204 .with_context(|| {
205 format!(
206 "received chunk for buffer {} without initial state",
207 chunk.buffer_id
208 )
209 })?;
210
211 let result = maybe!({
212 let operations = chunk
213 .operations
214 .into_iter()
215 .map(language::proto::deserialize_operation)
216 .collect::<Result<Vec<_>>>()?;
217 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx));
218 anyhow::Ok(())
219 });
220
221 if let Err(error) = result {
222 self.loading_remote_buffers_by_id.remove(&buffer_id);
223 if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
224 for listener in listeners {
225 listener.send(Err(error.cloned())).ok();
226 }
227 }
228 } else if chunk.is_last {
229 self.loading_remote_buffers_by_id.remove(&buffer_id);
230 if self.upstream_client.is_via_collab() {
231 // retain buffers sent by peers to avoid races.
232 self.shared_with_me.insert(buffer.clone());
233 }
234
235 if let Some(senders) = self.remote_buffer_listeners.remove(&buffer_id) {
236 for sender in senders {
237 sender.send(Ok(buffer.clone())).ok();
238 }
239 }
240 return Ok(Some(buffer));
241 }
242 }
243 }
244 Ok(None)
245 }
246
247 pub fn incomplete_buffer_ids(&self) -> Vec<BufferId> {
248 self.loading_remote_buffers_by_id
249 .keys()
250 .copied()
251 .collect::<Vec<_>>()
252 }
253
254 pub fn deserialize_project_transaction(
255 &self,
256 message: proto::ProjectTransaction,
257 push_to_history: bool,
258 cx: &mut Context<BufferStore>,
259 ) -> Task<Result<ProjectTransaction>> {
260 cx.spawn(async move |this, cx| {
261 let mut project_transaction = ProjectTransaction::default();
262 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
263 {
264 let buffer_id = BufferId::new(buffer_id)?;
265 let buffer = this
266 .update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
267 .await?;
268 let transaction = language::proto::deserialize_transaction(transaction)?;
269 project_transaction.0.insert(buffer, transaction);
270 }
271
272 for (buffer, transaction) in &project_transaction.0 {
273 buffer
274 .update(cx, |buffer, _| {
275 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
276 })?
277 .await?;
278
279 if push_to_history {
280 buffer.update(cx, |buffer, _| {
281 buffer.push_transaction(transaction.clone(), Instant::now());
282 buffer.finalize_last_transaction();
283 })?;
284 }
285 }
286
287 Ok(project_transaction)
288 })
289 }
290
291 fn open_buffer(
292 &self,
293 path: Arc<RelPath>,
294 worktree: Entity<Worktree>,
295 cx: &mut Context<BufferStore>,
296 ) -> Task<Result<Entity<Buffer>>> {
297 let worktree_id = worktree.read(cx).id().to_proto();
298 let project_id = self.project_id;
299 let client = self.upstream_client.clone();
300 cx.spawn(async move |this, cx| {
301 let response = client
302 .request(proto::OpenBufferByPath {
303 project_id,
304 worktree_id,
305 path: path.to_proto(),
306 })
307 .await?;
308 let buffer_id = BufferId::new(response.buffer_id)?;
309
310 let buffer = this
311 .update(cx, {
312 |this, cx| this.wait_for_remote_buffer(buffer_id, cx)
313 })?
314 .await?;
315
316 Ok(buffer)
317 })
318 }
319
320 fn create_buffer(
321 &self,
322 project_searchable: bool,
323 cx: &mut Context<BufferStore>,
324 ) -> Task<Result<Entity<Buffer>>> {
325 let create = self.upstream_client.request(proto::OpenNewBuffer {
326 project_id: self.project_id,
327 });
328 cx.spawn(async move |this, cx| {
329 let response = create.await?;
330 let buffer_id = BufferId::new(response.buffer_id)?;
331
332 this.update(cx, |this, cx| {
333 if !project_searchable {
334 this.non_searchable_buffers.insert(buffer_id);
335 }
336 this.wait_for_remote_buffer(buffer_id, cx)
337 })?
338 .await
339 })
340 }
341
342 fn reload_buffers(
343 &self,
344 buffers: HashSet<Entity<Buffer>>,
345 push_to_history: bool,
346 cx: &mut Context<BufferStore>,
347 ) -> Task<Result<ProjectTransaction>> {
348 let request = self.upstream_client.request(proto::ReloadBuffers {
349 project_id: self.project_id,
350 buffer_ids: buffers
351 .iter()
352 .map(|buffer| buffer.read(cx).remote_id().to_proto())
353 .collect(),
354 });
355
356 cx.spawn(async move |this, cx| {
357 let response = request.await?.transaction.context("missing transaction")?;
358 this.update(cx, |this, cx| {
359 this.deserialize_project_transaction(response, push_to_history, cx)
360 })?
361 .await
362 })
363 }
364}
365
366impl LocalBufferStore {
367 fn save_local_buffer(
368 &self,
369 buffer_handle: Entity<Buffer>,
370 worktree: Entity<Worktree>,
371 path: Arc<RelPath>,
372 mut has_changed_file: bool,
373 cx: &mut Context<BufferStore>,
374 ) -> Task<Result<()>> {
375 let buffer = buffer_handle.read(cx);
376
377 let text = buffer.as_rope().clone();
378 let line_ending = buffer.line_ending();
379 let version = buffer.version();
380 let buffer_id = buffer.remote_id();
381 let file = buffer.file().cloned();
382 if file
383 .as_ref()
384 .is_some_and(|file| file.disk_state() == DiskState::New)
385 {
386 has_changed_file = true;
387 }
388
389 let save = worktree.update(cx, |worktree, cx| {
390 worktree.write_file(path, text, line_ending, cx)
391 });
392
393 cx.spawn(async move |this, cx| {
394 let new_file = save.await?;
395 let mtime = new_file.disk_state().mtime();
396 this.update(cx, |this, cx| {
397 if let Some((downstream_client, project_id)) = this.downstream_client.clone() {
398 if has_changed_file {
399 downstream_client
400 .send(proto::UpdateBufferFile {
401 project_id,
402 buffer_id: buffer_id.to_proto(),
403 file: Some(language::File::to_proto(&*new_file, cx)),
404 })
405 .log_err();
406 }
407 downstream_client
408 .send(proto::BufferSaved {
409 project_id,
410 buffer_id: buffer_id.to_proto(),
411 version: serialize_version(&version),
412 mtime: mtime.map(|time| time.into()),
413 })
414 .log_err();
415 }
416 })?;
417 buffer_handle.update(cx, |buffer, cx| {
418 if has_changed_file {
419 buffer.file_updated(new_file, cx);
420 }
421 buffer.did_save(version.clone(), mtime, cx);
422 })
423 })
424 }
425
426 fn subscribe_to_worktree(
427 &mut self,
428 worktree: &Entity<Worktree>,
429 cx: &mut Context<BufferStore>,
430 ) {
431 cx.subscribe(worktree, |this, worktree, event, cx| {
432 if worktree.read(cx).is_local()
433 && let worktree::Event::UpdatedEntries(changes) = event
434 {
435 Self::local_worktree_entries_changed(this, &worktree, changes, cx);
436 }
437 })
438 .detach();
439 }
440
441 fn local_worktree_entries_changed(
442 this: &mut BufferStore,
443 worktree_handle: &Entity<Worktree>,
444 changes: &[(Arc<RelPath>, ProjectEntryId, PathChange)],
445 cx: &mut Context<BufferStore>,
446 ) {
447 let snapshot = worktree_handle.read(cx).snapshot();
448 for (path, entry_id, _) in changes {
449 Self::local_worktree_entry_changed(
450 this,
451 *entry_id,
452 path,
453 worktree_handle,
454 &snapshot,
455 cx,
456 );
457 }
458 }
459
460 fn local_worktree_entry_changed(
461 this: &mut BufferStore,
462 entry_id: ProjectEntryId,
463 path: &Arc<RelPath>,
464 worktree: &Entity<worktree::Worktree>,
465 snapshot: &worktree::Snapshot,
466 cx: &mut Context<BufferStore>,
467 ) -> Option<()> {
468 let project_path = ProjectPath {
469 worktree_id: snapshot.id(),
470 path: path.clone(),
471 };
472
473 let buffer_id = this
474 .as_local_mut()
475 .and_then(|local| local.local_buffer_ids_by_entry_id.get(&entry_id))
476 .copied()
477 .or_else(|| this.path_to_buffer_id.get(&project_path).copied())?;
478
479 let buffer = if let Some(buffer) = this.get(buffer_id) {
480 Some(buffer)
481 } else {
482 this.opened_buffers.remove(&buffer_id);
483 this.non_searchable_buffers.remove(&buffer_id);
484 None
485 };
486
487 let buffer = if let Some(buffer) = buffer {
488 buffer
489 } else {
490 this.path_to_buffer_id.remove(&project_path);
491 let this = this.as_local_mut()?;
492 this.local_buffer_ids_by_entry_id.remove(&entry_id);
493 return None;
494 };
495
496 let events = buffer.update(cx, |buffer, cx| {
497 let file = buffer.file()?;
498 let old_file = File::from_dyn(Some(file))?;
499 if old_file.worktree != *worktree {
500 return None;
501 }
502
503 let snapshot_entry = old_file
504 .entry_id
505 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
506 .or_else(|| snapshot.entry_for_path(old_file.path.as_ref()));
507
508 let new_file = if let Some(entry) = snapshot_entry {
509 File {
510 disk_state: match entry.mtime {
511 Some(mtime) => DiskState::Present { mtime },
512 None => old_file.disk_state,
513 },
514 is_local: true,
515 entry_id: Some(entry.id),
516 path: entry.path.clone(),
517 worktree: worktree.clone(),
518 is_private: entry.is_private,
519 }
520 } else {
521 File {
522 disk_state: DiskState::Deleted,
523 is_local: true,
524 entry_id: old_file.entry_id,
525 path: old_file.path.clone(),
526 worktree: worktree.clone(),
527 is_private: old_file.is_private,
528 }
529 };
530
531 if new_file == *old_file {
532 return None;
533 }
534
535 let mut events = Vec::new();
536 if new_file.path != old_file.path {
537 this.path_to_buffer_id.remove(&ProjectPath {
538 path: old_file.path.clone(),
539 worktree_id: old_file.worktree_id(cx),
540 });
541 this.path_to_buffer_id.insert(
542 ProjectPath {
543 worktree_id: new_file.worktree_id(cx),
544 path: new_file.path.clone(),
545 },
546 buffer_id,
547 );
548 events.push(BufferStoreEvent::BufferChangedFilePath {
549 buffer: cx.entity(),
550 old_file: buffer.file().cloned(),
551 });
552 }
553 let local = this.as_local_mut()?;
554 if new_file.entry_id != old_file.entry_id {
555 if let Some(entry_id) = old_file.entry_id {
556 local.local_buffer_ids_by_entry_id.remove(&entry_id);
557 }
558 if let Some(entry_id) = new_file.entry_id {
559 local
560 .local_buffer_ids_by_entry_id
561 .insert(entry_id, buffer_id);
562 }
563 }
564
565 if let Some((client, project_id)) = &this.downstream_client {
566 client
567 .send(proto::UpdateBufferFile {
568 project_id: *project_id,
569 buffer_id: buffer_id.to_proto(),
570 file: Some(new_file.to_proto(cx)),
571 })
572 .ok();
573 }
574
575 buffer.file_updated(Arc::new(new_file), cx);
576 Some(events)
577 })?;
578
579 for event in events {
580 cx.emit(event);
581 }
582
583 None
584 }
585
586 fn save_buffer(
587 &self,
588 buffer: Entity<Buffer>,
589 cx: &mut Context<BufferStore>,
590 ) -> Task<Result<()>> {
591 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
592 return Task::ready(Err(anyhow!("buffer doesn't have a file")));
593 };
594 let worktree = file.worktree.clone();
595 self.save_local_buffer(buffer, worktree, file.path.clone(), false, cx)
596 }
597
598 fn save_buffer_as(
599 &self,
600 buffer: Entity<Buffer>,
601 path: ProjectPath,
602 cx: &mut Context<BufferStore>,
603 ) -> Task<Result<()>> {
604 let Some(worktree) = self
605 .worktree_store
606 .read(cx)
607 .worktree_for_id(path.worktree_id, cx)
608 else {
609 return Task::ready(Err(anyhow!("no such worktree")));
610 };
611 self.save_local_buffer(buffer, worktree, path.path, true, cx)
612 }
613
614 fn open_buffer(
615 &self,
616 path: Arc<RelPath>,
617 worktree: Entity<Worktree>,
618 cx: &mut Context<BufferStore>,
619 ) -> Task<Result<Entity<Buffer>>> {
620 let load_file = worktree.update(cx, |worktree, cx| worktree.load_file(path.as_ref(), cx));
621 cx.spawn(async move |this, cx| {
622 let path = path.clone();
623 let buffer = match load_file.await.with_context(|| {
624 format!("Could not open path: {}", path.display(PathStyle::local()))
625 }) {
626 Ok(loaded) => {
627 let reservation = cx.reserve_entity::<Buffer>()?;
628 let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
629 let text_buffer = cx
630 .background_spawn(async move {
631 text::Buffer::new(ReplicaId::LOCAL, buffer_id, loaded.text)
632 })
633 .await;
634 cx.insert_entity(reservation, |_| {
635 Buffer::build(text_buffer, Some(loaded.file), Capability::ReadWrite)
636 })?
637 }
638 Err(error) if is_not_found_error(&error) => cx.new(|cx| {
639 let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
640 let text_buffer = text::Buffer::new(ReplicaId::LOCAL, buffer_id, "");
641 Buffer::build(
642 text_buffer,
643 Some(Arc::new(File {
644 worktree,
645 path,
646 disk_state: DiskState::New,
647 entry_id: None,
648 is_local: true,
649 is_private: false,
650 })),
651 Capability::ReadWrite,
652 )
653 })?,
654 Err(e) => return Err(e),
655 };
656 this.update(cx, |this, cx| {
657 this.add_buffer(buffer.clone(), cx)?;
658 let buffer_id = buffer.read(cx).remote_id();
659 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
660 this.path_to_buffer_id.insert(
661 ProjectPath {
662 worktree_id: file.worktree_id(cx),
663 path: file.path.clone(),
664 },
665 buffer_id,
666 );
667 let this = this.as_local_mut().unwrap();
668 if let Some(entry_id) = file.entry_id {
669 this.local_buffer_ids_by_entry_id
670 .insert(entry_id, buffer_id);
671 }
672 }
673
674 anyhow::Ok(())
675 })??;
676
677 Ok(buffer)
678 })
679 }
680
681 fn create_buffer(
682 &self,
683 project_searchable: bool,
684 cx: &mut Context<BufferStore>,
685 ) -> Task<Result<Entity<Buffer>>> {
686 cx.spawn(async move |buffer_store, cx| {
687 let buffer =
688 cx.new(|cx| Buffer::local("", cx).with_language(language::PLAIN_TEXT.clone(), cx))?;
689 buffer_store.update(cx, |buffer_store, cx| {
690 buffer_store.add_buffer(buffer.clone(), cx).log_err();
691 if !project_searchable {
692 buffer_store
693 .non_searchable_buffers
694 .insert(buffer.read(cx).remote_id());
695 }
696 })?;
697 Ok(buffer)
698 })
699 }
700
701 fn reload_buffers(
702 &self,
703 buffers: HashSet<Entity<Buffer>>,
704 push_to_history: bool,
705 cx: &mut Context<BufferStore>,
706 ) -> Task<Result<ProjectTransaction>> {
707 cx.spawn(async move |_, cx| {
708 let mut project_transaction = ProjectTransaction::default();
709 for buffer in buffers {
710 let transaction = buffer.update(cx, |buffer, cx| buffer.reload(cx))?.await?;
711 buffer.update(cx, |buffer, cx| {
712 if let Some(transaction) = transaction {
713 if !push_to_history {
714 buffer.forget_transaction(transaction.id);
715 }
716 project_transaction.0.insert(cx.entity(), transaction);
717 }
718 })?;
719 }
720
721 Ok(project_transaction)
722 })
723 }
724}
725
726impl BufferStore {
727 pub fn init(client: &AnyProtoClient) {
728 client.add_entity_message_handler(Self::handle_buffer_reloaded);
729 client.add_entity_message_handler(Self::handle_buffer_saved);
730 client.add_entity_message_handler(Self::handle_update_buffer_file);
731 client.add_entity_request_handler(Self::handle_save_buffer);
732 client.add_entity_request_handler(Self::handle_reload_buffers);
733 }
734
735 /// Creates a buffer store, optionally retaining its buffers.
736 pub fn local(worktree_store: Entity<WorktreeStore>, cx: &mut Context<Self>) -> Self {
737 Self {
738 state: BufferStoreState::Local(LocalBufferStore {
739 local_buffer_ids_by_entry_id: Default::default(),
740 worktree_store: worktree_store.clone(),
741 _subscription: cx.subscribe(&worktree_store, |this, _, event, cx| {
742 if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
743 let this = this.as_local_mut().unwrap();
744 this.subscribe_to_worktree(worktree, cx);
745 }
746 }),
747 }),
748 downstream_client: None,
749 opened_buffers: Default::default(),
750 path_to_buffer_id: Default::default(),
751 shared_buffers: Default::default(),
752 loading_buffers: Default::default(),
753 non_searchable_buffers: Default::default(),
754 worktree_store,
755 }
756 }
757
758 pub fn remote(
759 worktree_store: Entity<WorktreeStore>,
760 upstream_client: AnyProtoClient,
761 remote_id: u64,
762 _cx: &mut Context<Self>,
763 ) -> Self {
764 Self {
765 state: BufferStoreState::Remote(RemoteBufferStore {
766 shared_with_me: Default::default(),
767 loading_remote_buffers_by_id: Default::default(),
768 remote_buffer_listeners: Default::default(),
769 project_id: remote_id,
770 upstream_client,
771 worktree_store: worktree_store.clone(),
772 }),
773 downstream_client: None,
774 opened_buffers: Default::default(),
775 path_to_buffer_id: Default::default(),
776 loading_buffers: Default::default(),
777 shared_buffers: Default::default(),
778 non_searchable_buffers: Default::default(),
779 worktree_store,
780 }
781 }
782
783 fn as_local_mut(&mut self) -> Option<&mut LocalBufferStore> {
784 match &mut self.state {
785 BufferStoreState::Local(state) => Some(state),
786 _ => None,
787 }
788 }
789
790 fn as_remote_mut(&mut self) -> Option<&mut RemoteBufferStore> {
791 match &mut self.state {
792 BufferStoreState::Remote(state) => Some(state),
793 _ => None,
794 }
795 }
796
797 fn as_remote(&self) -> Option<&RemoteBufferStore> {
798 match &self.state {
799 BufferStoreState::Remote(state) => Some(state),
800 _ => None,
801 }
802 }
803
804 pub fn open_buffer(
805 &mut self,
806 project_path: ProjectPath,
807 cx: &mut Context<Self>,
808 ) -> Task<Result<Entity<Buffer>>> {
809 if let Some(buffer) = self.get_by_path(&project_path) {
810 cx.emit(BufferStoreEvent::BufferOpened {
811 buffer: buffer.clone(),
812 project_path,
813 });
814
815 return Task::ready(Ok(buffer));
816 }
817
818 let task = match self.loading_buffers.entry(project_path.clone()) {
819 hash_map::Entry::Occupied(e) => e.get().clone(),
820 hash_map::Entry::Vacant(entry) => {
821 let path = project_path.path.clone();
822 let Some(worktree) = self
823 .worktree_store
824 .read(cx)
825 .worktree_for_id(project_path.worktree_id, cx)
826 else {
827 return Task::ready(Err(anyhow!("no such worktree")));
828 };
829 let load_buffer = match &self.state {
830 BufferStoreState::Local(this) => this.open_buffer(path, worktree, cx),
831 BufferStoreState::Remote(this) => this.open_buffer(path, worktree, cx),
832 };
833
834 entry
835 .insert(
836 // todo(lw): hot foreground spawn
837 cx.spawn(async move |this, cx| {
838 let load_result = load_buffer.await;
839 this.update(cx, |this, cx| {
840 // Record the fact that the buffer is no longer loading.
841 this.loading_buffers.remove(&project_path);
842
843 let buffer = load_result.map_err(Arc::new)?;
844 cx.emit(BufferStoreEvent::BufferOpened {
845 buffer: buffer.clone(),
846 project_path,
847 });
848
849 Ok(buffer)
850 })?
851 })
852 .shared(),
853 )
854 .clone()
855 }
856 };
857
858 cx.background_spawn(async move {
859 task.await.map_err(|e| {
860 if e.error_code() != ErrorCode::Internal {
861 anyhow!(e.error_code())
862 } else {
863 anyhow!("{e}")
864 }
865 })
866 })
867 }
868
869 pub fn create_buffer(
870 &mut self,
871 project_searchable: bool,
872 cx: &mut Context<Self>,
873 ) -> Task<Result<Entity<Buffer>>> {
874 match &self.state {
875 BufferStoreState::Local(this) => this.create_buffer(project_searchable, cx),
876 BufferStoreState::Remote(this) => this.create_buffer(project_searchable, cx),
877 }
878 }
879
880 pub fn save_buffer(
881 &mut self,
882 buffer: Entity<Buffer>,
883 cx: &mut Context<Self>,
884 ) -> Task<Result<()>> {
885 match &mut self.state {
886 BufferStoreState::Local(this) => this.save_buffer(buffer, cx),
887 BufferStoreState::Remote(this) => this.save_remote_buffer(buffer, None, cx),
888 }
889 }
890
891 pub fn save_buffer_as(
892 &mut self,
893 buffer: Entity<Buffer>,
894 path: ProjectPath,
895 cx: &mut Context<Self>,
896 ) -> Task<Result<()>> {
897 let old_file = buffer.read(cx).file().cloned();
898 let task = match &self.state {
899 BufferStoreState::Local(this) => this.save_buffer_as(buffer.clone(), path, cx),
900 BufferStoreState::Remote(this) => {
901 this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
902 }
903 };
904 cx.spawn(async move |this, cx| {
905 task.await?;
906 this.update(cx, |this, cx| {
907 old_file.clone().and_then(|file| {
908 this.path_to_buffer_id.remove(&ProjectPath {
909 worktree_id: file.worktree_id(cx),
910 path: file.path().clone(),
911 })
912 });
913
914 cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
915 })
916 })
917 }
918
919 fn add_buffer(&mut self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
920 let buffer = buffer_entity.read(cx);
921 let remote_id = buffer.remote_id();
922 let path = File::from_dyn(buffer.file()).map(|file| ProjectPath {
923 path: file.path.clone(),
924 worktree_id: file.worktree_id(cx),
925 });
926 let is_remote = buffer.replica_id().is_remote();
927 let open_buffer = OpenBuffer::Complete {
928 buffer: buffer_entity.downgrade(),
929 };
930
931 let handle = cx.entity().downgrade();
932 buffer_entity.update(cx, move |_, cx| {
933 cx.on_release(move |buffer, cx| {
934 handle
935 .update(cx, |_, cx| {
936 cx.emit(BufferStoreEvent::BufferDropped(buffer.remote_id()))
937 })
938 .ok();
939 })
940 .detach()
941 });
942 let _expect_path_to_exist;
943 match self.opened_buffers.entry(remote_id) {
944 hash_map::Entry::Vacant(entry) => {
945 entry.insert(open_buffer);
946 _expect_path_to_exist = false;
947 }
948 hash_map::Entry::Occupied(mut entry) => {
949 if let OpenBuffer::Operations(operations) = entry.get_mut() {
950 buffer_entity.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx));
951 } else if entry.get().upgrade().is_some() {
952 if is_remote {
953 return Ok(());
954 } else {
955 debug_panic!("buffer {remote_id} was already registered");
956 anyhow::bail!("buffer {remote_id} was already registered");
957 }
958 }
959 entry.insert(open_buffer);
960 _expect_path_to_exist = true;
961 }
962 }
963
964 if let Some(path) = path {
965 self.path_to_buffer_id.insert(path, remote_id);
966 }
967
968 cx.subscribe(&buffer_entity, Self::on_buffer_event).detach();
969 cx.emit(BufferStoreEvent::BufferAdded(buffer_entity));
970 Ok(())
971 }
972
973 pub fn buffers(&self) -> impl '_ + Iterator<Item = Entity<Buffer>> {
974 self.opened_buffers
975 .values()
976 .filter_map(|buffer| buffer.upgrade())
977 }
978
979 pub(crate) fn is_searchable(&self, id: &BufferId) -> bool {
980 !self.non_searchable_buffers.contains(&id)
981 }
982
983 pub fn loading_buffers(
984 &self,
985 ) -> impl Iterator<Item = (&ProjectPath, impl Future<Output = Result<Entity<Buffer>>>)> {
986 self.loading_buffers.iter().map(|(path, task)| {
987 let task = task.clone();
988 (path, async move {
989 task.await.map_err(|e| {
990 if e.error_code() != ErrorCode::Internal {
991 anyhow!(e.error_code())
992 } else {
993 anyhow!("{e}")
994 }
995 })
996 })
997 })
998 }
999
1000 pub fn buffer_id_for_project_path(&self, project_path: &ProjectPath) -> Option<&BufferId> {
1001 self.path_to_buffer_id.get(project_path)
1002 }
1003
1004 pub fn get_by_path(&self, path: &ProjectPath) -> Option<Entity<Buffer>> {
1005 self.path_to_buffer_id
1006 .get(path)
1007 .and_then(|buffer_id| self.get(*buffer_id))
1008 }
1009
1010 pub fn get(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1011 self.opened_buffers.get(&buffer_id)?.upgrade()
1012 }
1013
1014 pub fn get_existing(&self, buffer_id: BufferId) -> Result<Entity<Buffer>> {
1015 self.get(buffer_id)
1016 .with_context(|| format!("unknown buffer id {buffer_id}"))
1017 }
1018
1019 pub fn get_possibly_incomplete(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1020 self.get(buffer_id).or_else(|| {
1021 self.as_remote()
1022 .and_then(|remote| remote.loading_remote_buffers_by_id.get(&buffer_id).cloned())
1023 })
1024 }
1025
1026 pub fn buffer_version_info(&self, cx: &App) -> (Vec<proto::BufferVersion>, Vec<BufferId>) {
1027 let buffers = self
1028 .buffers()
1029 .map(|buffer| {
1030 let buffer = buffer.read(cx);
1031 proto::BufferVersion {
1032 id: buffer.remote_id().into(),
1033 version: language::proto::serialize_version(&buffer.version),
1034 }
1035 })
1036 .collect();
1037 let incomplete_buffer_ids = self
1038 .as_remote()
1039 .map(|remote| remote.incomplete_buffer_ids())
1040 .unwrap_or_default();
1041 (buffers, incomplete_buffer_ids)
1042 }
1043
1044 pub fn disconnected_from_host(&mut self, cx: &mut App) {
1045 for open_buffer in self.opened_buffers.values_mut() {
1046 if let Some(buffer) = open_buffer.upgrade() {
1047 buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1048 }
1049 }
1050
1051 for buffer in self.buffers() {
1052 buffer.update(cx, |buffer, cx| {
1053 buffer.set_capability(Capability::ReadOnly, cx)
1054 });
1055 }
1056
1057 if let Some(remote) = self.as_remote_mut() {
1058 // Wake up all futures currently waiting on a buffer to get opened,
1059 // to give them a chance to fail now that we've disconnected.
1060 remote.remote_buffer_listeners.clear()
1061 }
1062 }
1063
1064 pub fn shared(&mut self, remote_id: u64, downstream_client: AnyProtoClient, _cx: &mut App) {
1065 self.downstream_client = Some((downstream_client, remote_id));
1066 }
1067
1068 pub fn unshared(&mut self, _cx: &mut Context<Self>) {
1069 self.downstream_client.take();
1070 self.forget_shared_buffers();
1071 }
1072
1073 pub fn discard_incomplete(&mut self) {
1074 self.opened_buffers
1075 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
1076 }
1077
1078 fn buffer_changed_file(&mut self, buffer: Entity<Buffer>, cx: &mut App) -> Option<()> {
1079 let file = File::from_dyn(buffer.read(cx).file())?;
1080
1081 let remote_id = buffer.read(cx).remote_id();
1082 if let Some(entry_id) = file.entry_id {
1083 if let Some(local) = self.as_local_mut() {
1084 match local.local_buffer_ids_by_entry_id.get(&entry_id) {
1085 Some(_) => {
1086 return None;
1087 }
1088 None => {
1089 local
1090 .local_buffer_ids_by_entry_id
1091 .insert(entry_id, remote_id);
1092 }
1093 }
1094 }
1095 self.path_to_buffer_id.insert(
1096 ProjectPath {
1097 worktree_id: file.worktree_id(cx),
1098 path: file.path.clone(),
1099 },
1100 remote_id,
1101 );
1102 };
1103
1104 Some(())
1105 }
1106
1107 fn on_buffer_event(
1108 &mut self,
1109 buffer: Entity<Buffer>,
1110 event: &BufferEvent,
1111 cx: &mut Context<Self>,
1112 ) {
1113 match event {
1114 BufferEvent::FileHandleChanged => {
1115 self.buffer_changed_file(buffer, cx);
1116 }
1117 BufferEvent::Reloaded => {
1118 let Some((downstream_client, project_id)) = self.downstream_client.as_ref() else {
1119 return;
1120 };
1121 let buffer = buffer.read(cx);
1122 downstream_client
1123 .send(proto::BufferReloaded {
1124 project_id: *project_id,
1125 buffer_id: buffer.remote_id().to_proto(),
1126 version: serialize_version(&buffer.version()),
1127 mtime: buffer.saved_mtime().map(|t| t.into()),
1128 line_ending: serialize_line_ending(buffer.line_ending()) as i32,
1129 })
1130 .log_err();
1131 }
1132 BufferEvent::LanguageChanged => {}
1133 _ => {}
1134 }
1135 }
1136
1137 pub async fn handle_update_buffer(
1138 this: Entity<Self>,
1139 envelope: TypedEnvelope<proto::UpdateBuffer>,
1140 mut cx: AsyncApp,
1141 ) -> Result<proto::Ack> {
1142 let payload = envelope.payload;
1143 let buffer_id = BufferId::new(payload.buffer_id)?;
1144 let ops = payload
1145 .operations
1146 .into_iter()
1147 .map(language::proto::deserialize_operation)
1148 .collect::<Result<Vec<_>, _>>()?;
1149 this.update(&mut cx, |this, cx| {
1150 match this.opened_buffers.entry(buffer_id) {
1151 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
1152 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
1153 OpenBuffer::Complete { buffer, .. } => {
1154 if let Some(buffer) = buffer.upgrade() {
1155 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx));
1156 }
1157 }
1158 },
1159 hash_map::Entry::Vacant(e) => {
1160 e.insert(OpenBuffer::Operations(ops));
1161 }
1162 }
1163 Ok(proto::Ack {})
1164 })?
1165 }
1166
1167 pub fn register_shared_lsp_handle(
1168 &mut self,
1169 peer_id: proto::PeerId,
1170 buffer_id: BufferId,
1171 handle: OpenLspBufferHandle,
1172 ) {
1173 if let Some(shared_buffers) = self.shared_buffers.get_mut(&peer_id)
1174 && let Some(buffer) = shared_buffers.get_mut(&buffer_id)
1175 {
1176 buffer.lsp_handle = Some(handle);
1177 return;
1178 }
1179 debug_panic!("tried to register shared lsp handle, but buffer was not shared")
1180 }
1181
1182 pub fn handle_synchronize_buffers(
1183 &mut self,
1184 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
1185 cx: &mut Context<Self>,
1186 client: Arc<Client>,
1187 ) -> Result<proto::SynchronizeBuffersResponse> {
1188 let project_id = envelope.payload.project_id;
1189 let mut response = proto::SynchronizeBuffersResponse {
1190 buffers: Default::default(),
1191 };
1192 let Some(guest_id) = envelope.original_sender_id else {
1193 anyhow::bail!("missing original_sender_id on SynchronizeBuffers request");
1194 };
1195
1196 self.shared_buffers.entry(guest_id).or_default().clear();
1197 for buffer in envelope.payload.buffers {
1198 let buffer_id = BufferId::new(buffer.id)?;
1199 let remote_version = language::proto::deserialize_version(&buffer.version);
1200 if let Some(buffer) = self.get(buffer_id) {
1201 self.shared_buffers
1202 .entry(guest_id)
1203 .or_default()
1204 .entry(buffer_id)
1205 .or_insert_with(|| SharedBuffer {
1206 buffer: buffer.clone(),
1207 lsp_handle: None,
1208 });
1209
1210 let buffer = buffer.read(cx);
1211 response.buffers.push(proto::BufferVersion {
1212 id: buffer_id.into(),
1213 version: language::proto::serialize_version(&buffer.version),
1214 });
1215
1216 let operations = buffer.serialize_ops(Some(remote_version), cx);
1217 let client = client.clone();
1218 if let Some(file) = buffer.file() {
1219 client
1220 .send(proto::UpdateBufferFile {
1221 project_id,
1222 buffer_id: buffer_id.into(),
1223 file: Some(file.to_proto(cx)),
1224 })
1225 .log_err();
1226 }
1227
1228 // TODO(max): do something
1229 // client
1230 // .send(proto::UpdateStagedText {
1231 // project_id,
1232 // buffer_id: buffer_id.into(),
1233 // diff_base: buffer.diff_base().map(ToString::to_string),
1234 // })
1235 // .log_err();
1236
1237 client
1238 .send(proto::BufferReloaded {
1239 project_id,
1240 buffer_id: buffer_id.into(),
1241 version: language::proto::serialize_version(buffer.saved_version()),
1242 mtime: buffer.saved_mtime().map(|time| time.into()),
1243 line_ending: language::proto::serialize_line_ending(buffer.line_ending())
1244 as i32,
1245 })
1246 .log_err();
1247
1248 cx.background_spawn(
1249 async move {
1250 let operations = operations.await;
1251 for chunk in split_operations(operations) {
1252 client
1253 .request(proto::UpdateBuffer {
1254 project_id,
1255 buffer_id: buffer_id.into(),
1256 operations: chunk,
1257 })
1258 .await?;
1259 }
1260 anyhow::Ok(())
1261 }
1262 .log_err(),
1263 )
1264 .detach();
1265 }
1266 }
1267 Ok(response)
1268 }
1269
1270 pub fn handle_create_buffer_for_peer(
1271 &mut self,
1272 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
1273 replica_id: ReplicaId,
1274 capability: Capability,
1275 cx: &mut Context<Self>,
1276 ) -> Result<()> {
1277 let remote = self
1278 .as_remote_mut()
1279 .context("buffer store is not a remote")?;
1280
1281 if let Some(buffer) =
1282 remote.handle_create_buffer_for_peer(envelope, replica_id, capability, cx)?
1283 {
1284 self.add_buffer(buffer, cx)?;
1285 }
1286
1287 Ok(())
1288 }
1289
1290 pub async fn handle_update_buffer_file(
1291 this: Entity<Self>,
1292 envelope: TypedEnvelope<proto::UpdateBufferFile>,
1293 mut cx: AsyncApp,
1294 ) -> Result<()> {
1295 let buffer_id = envelope.payload.buffer_id;
1296 let buffer_id = BufferId::new(buffer_id)?;
1297
1298 this.update(&mut cx, |this, cx| {
1299 let payload = envelope.payload.clone();
1300 if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1301 let file = payload.file.context("invalid file")?;
1302 let worktree = this
1303 .worktree_store
1304 .read(cx)
1305 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
1306 .context("no such worktree")?;
1307 let file = File::from_proto(file, worktree, cx)?;
1308 let old_file = buffer.update(cx, |buffer, cx| {
1309 let old_file = buffer.file().cloned();
1310 let new_path = file.path.clone();
1311
1312 buffer.file_updated(Arc::new(file), cx);
1313 if old_file.as_ref().is_none_or(|old| *old.path() != new_path) {
1314 Some(old_file)
1315 } else {
1316 None
1317 }
1318 });
1319 if let Some(old_file) = old_file {
1320 cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
1321 }
1322 }
1323 if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1324 downstream_client
1325 .send(proto::UpdateBufferFile {
1326 project_id: *project_id,
1327 buffer_id: buffer_id.into(),
1328 file: envelope.payload.file,
1329 })
1330 .log_err();
1331 }
1332 Ok(())
1333 })?
1334 }
1335
1336 pub async fn handle_save_buffer(
1337 this: Entity<Self>,
1338 envelope: TypedEnvelope<proto::SaveBuffer>,
1339 mut cx: AsyncApp,
1340 ) -> Result<proto::BufferSaved> {
1341 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1342 let (buffer, project_id) = this.read_with(&cx, |this, _| {
1343 anyhow::Ok((
1344 this.get_existing(buffer_id)?,
1345 this.downstream_client
1346 .as_ref()
1347 .map(|(_, project_id)| *project_id)
1348 .context("project is not shared")?,
1349 ))
1350 })??;
1351 buffer
1352 .update(&mut cx, |buffer, _| {
1353 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
1354 })?
1355 .await?;
1356 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id())?;
1357
1358 if let Some(new_path) = envelope.payload.new_path
1359 && let Some(new_path) = ProjectPath::from_proto(new_path)
1360 {
1361 this.update(&mut cx, |this, cx| {
1362 this.save_buffer_as(buffer.clone(), new_path, cx)
1363 })?
1364 .await?;
1365 } else {
1366 this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
1367 .await?;
1368 }
1369
1370 buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
1371 project_id,
1372 buffer_id: buffer_id.into(),
1373 version: serialize_version(buffer.saved_version()),
1374 mtime: buffer.saved_mtime().map(|time| time.into()),
1375 })
1376 }
1377
1378 pub async fn handle_close_buffer(
1379 this: Entity<Self>,
1380 envelope: TypedEnvelope<proto::CloseBuffer>,
1381 mut cx: AsyncApp,
1382 ) -> Result<()> {
1383 let peer_id = envelope.sender_id;
1384 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1385 this.update(&mut cx, |this, cx| {
1386 if let Some(shared) = this.shared_buffers.get_mut(&peer_id)
1387 && shared.remove(&buffer_id).is_some()
1388 {
1389 cx.emit(BufferStoreEvent::SharedBufferClosed(peer_id, buffer_id));
1390 if shared.is_empty() {
1391 this.shared_buffers.remove(&peer_id);
1392 }
1393 return;
1394 }
1395 debug_panic!(
1396 "peer_id {} closed buffer_id {} which was either not open or already closed",
1397 peer_id,
1398 buffer_id
1399 )
1400 })
1401 }
1402
1403 pub async fn handle_buffer_saved(
1404 this: Entity<Self>,
1405 envelope: TypedEnvelope<proto::BufferSaved>,
1406 mut cx: AsyncApp,
1407 ) -> Result<()> {
1408 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1409 let version = deserialize_version(&envelope.payload.version);
1410 let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1411 this.update(&mut cx, move |this, cx| {
1412 if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1413 buffer.update(cx, |buffer, cx| {
1414 buffer.did_save(version, mtime, cx);
1415 });
1416 }
1417
1418 if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1419 downstream_client
1420 .send(proto::BufferSaved {
1421 project_id: *project_id,
1422 buffer_id: buffer_id.into(),
1423 mtime: envelope.payload.mtime,
1424 version: envelope.payload.version,
1425 })
1426 .log_err();
1427 }
1428 })
1429 }
1430
1431 pub async fn handle_buffer_reloaded(
1432 this: Entity<Self>,
1433 envelope: TypedEnvelope<proto::BufferReloaded>,
1434 mut cx: AsyncApp,
1435 ) -> Result<()> {
1436 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1437 let version = deserialize_version(&envelope.payload.version);
1438 let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1439 let line_ending = deserialize_line_ending(
1440 proto::LineEnding::from_i32(envelope.payload.line_ending)
1441 .context("missing line ending")?,
1442 );
1443 this.update(&mut cx, |this, cx| {
1444 if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1445 buffer.update(cx, |buffer, cx| {
1446 buffer.did_reload(version, line_ending, mtime, cx);
1447 });
1448 }
1449
1450 if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1451 downstream_client
1452 .send(proto::BufferReloaded {
1453 project_id: *project_id,
1454 buffer_id: buffer_id.into(),
1455 mtime: envelope.payload.mtime,
1456 version: envelope.payload.version,
1457 line_ending: envelope.payload.line_ending,
1458 })
1459 .log_err();
1460 }
1461 })
1462 }
1463
1464 pub fn reload_buffers(
1465 &self,
1466 buffers: HashSet<Entity<Buffer>>,
1467 push_to_history: bool,
1468 cx: &mut Context<Self>,
1469 ) -> Task<Result<ProjectTransaction>> {
1470 if buffers.is_empty() {
1471 return Task::ready(Ok(ProjectTransaction::default()));
1472 }
1473 match &self.state {
1474 BufferStoreState::Local(this) => this.reload_buffers(buffers, push_to_history, cx),
1475 BufferStoreState::Remote(this) => this.reload_buffers(buffers, push_to_history, cx),
1476 }
1477 }
1478
1479 async fn handle_reload_buffers(
1480 this: Entity<Self>,
1481 envelope: TypedEnvelope<proto::ReloadBuffers>,
1482 mut cx: AsyncApp,
1483 ) -> Result<proto::ReloadBuffersResponse> {
1484 let sender_id = envelope.original_sender_id().unwrap_or_default();
1485 let reload = this.update(&mut cx, |this, cx| {
1486 let mut buffers = HashSet::default();
1487 for buffer_id in &envelope.payload.buffer_ids {
1488 let buffer_id = BufferId::new(*buffer_id)?;
1489 buffers.insert(this.get_existing(buffer_id)?);
1490 }
1491 anyhow::Ok(this.reload_buffers(buffers, false, cx))
1492 })??;
1493
1494 let project_transaction = reload.await?;
1495 let project_transaction = this.update(&mut cx, |this, cx| {
1496 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
1497 })?;
1498 Ok(proto::ReloadBuffersResponse {
1499 transaction: Some(project_transaction),
1500 })
1501 }
1502
1503 pub fn create_buffer_for_peer(
1504 &mut self,
1505 buffer: &Entity<Buffer>,
1506 peer_id: proto::PeerId,
1507 cx: &mut Context<Self>,
1508 ) -> Task<Result<()>> {
1509 let buffer_id = buffer.read(cx).remote_id();
1510 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
1511 if shared_buffers.contains_key(&buffer_id) {
1512 return Task::ready(Ok(()));
1513 }
1514 shared_buffers.insert(
1515 buffer_id,
1516 SharedBuffer {
1517 buffer: buffer.clone(),
1518 lsp_handle: None,
1519 },
1520 );
1521
1522 let Some((client, project_id)) = self.downstream_client.clone() else {
1523 return Task::ready(Ok(()));
1524 };
1525
1526 cx.spawn(async move |this, cx| {
1527 let Some(buffer) = this.read_with(cx, |this, _| this.get(buffer_id))? else {
1528 return anyhow::Ok(());
1529 };
1530
1531 let operations = buffer.update(cx, |b, cx| b.serialize_ops(None, cx))?;
1532 let operations = operations.await;
1533 let state = buffer.update(cx, |buffer, cx| buffer.to_proto(cx))?;
1534
1535 let initial_state = proto::CreateBufferForPeer {
1536 project_id,
1537 peer_id: Some(peer_id),
1538 variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1539 };
1540
1541 if client.send(initial_state).log_err().is_some() {
1542 let client = client.clone();
1543 cx.background_spawn(async move {
1544 let mut chunks = split_operations(operations).peekable();
1545 while let Some(chunk) = chunks.next() {
1546 let is_last = chunks.peek().is_none();
1547 client.send(proto::CreateBufferForPeer {
1548 project_id,
1549 peer_id: Some(peer_id),
1550 variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
1551 proto::BufferChunk {
1552 buffer_id: buffer_id.into(),
1553 operations: chunk,
1554 is_last,
1555 },
1556 )),
1557 })?;
1558 }
1559 anyhow::Ok(())
1560 })
1561 .await
1562 .log_err();
1563 }
1564 Ok(())
1565 })
1566 }
1567
1568 pub fn forget_shared_buffers(&mut self) {
1569 self.shared_buffers.clear();
1570 }
1571
1572 pub fn forget_shared_buffers_for(&mut self, peer_id: &proto::PeerId) {
1573 self.shared_buffers.remove(peer_id);
1574 }
1575
1576 pub fn update_peer_id(&mut self, old_peer_id: &proto::PeerId, new_peer_id: proto::PeerId) {
1577 if let Some(buffers) = self.shared_buffers.remove(old_peer_id) {
1578 self.shared_buffers.insert(new_peer_id, buffers);
1579 }
1580 }
1581
1582 pub fn has_shared_buffers(&self) -> bool {
1583 !self.shared_buffers.is_empty()
1584 }
1585
1586 pub fn create_local_buffer(
1587 &mut self,
1588 text: &str,
1589 language: Option<Arc<Language>>,
1590 project_searchable: bool,
1591 cx: &mut Context<Self>,
1592 ) -> Entity<Buffer> {
1593 let buffer = cx.new(|cx| {
1594 Buffer::local(text, cx)
1595 .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1596 });
1597
1598 self.add_buffer(buffer.clone(), cx).log_err();
1599 let buffer_id = buffer.read(cx).remote_id();
1600 if !project_searchable {
1601 self.non_searchable_buffers.insert(buffer_id);
1602 }
1603
1604 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1605 self.path_to_buffer_id.insert(
1606 ProjectPath {
1607 worktree_id: file.worktree_id(cx),
1608 path: file.path.clone(),
1609 },
1610 buffer_id,
1611 );
1612 let this = self
1613 .as_local_mut()
1614 .expect("local-only method called in a non-local context");
1615 if let Some(entry_id) = file.entry_id {
1616 this.local_buffer_ids_by_entry_id
1617 .insert(entry_id, buffer_id);
1618 }
1619 }
1620 buffer
1621 }
1622
1623 pub fn deserialize_project_transaction(
1624 &mut self,
1625 message: proto::ProjectTransaction,
1626 push_to_history: bool,
1627 cx: &mut Context<Self>,
1628 ) -> Task<Result<ProjectTransaction>> {
1629 if let Some(this) = self.as_remote_mut() {
1630 this.deserialize_project_transaction(message, push_to_history, cx)
1631 } else {
1632 debug_panic!("not a remote buffer store");
1633 Task::ready(Err(anyhow!("not a remote buffer store")))
1634 }
1635 }
1636
1637 pub fn wait_for_remote_buffer(
1638 &mut self,
1639 id: BufferId,
1640 cx: &mut Context<BufferStore>,
1641 ) -> Task<Result<Entity<Buffer>>> {
1642 if let Some(this) = self.as_remote_mut() {
1643 this.wait_for_remote_buffer(id, cx)
1644 } else {
1645 debug_panic!("not a remote buffer store");
1646 Task::ready(Err(anyhow!("not a remote buffer store")))
1647 }
1648 }
1649
1650 pub fn serialize_project_transaction_for_peer(
1651 &mut self,
1652 project_transaction: ProjectTransaction,
1653 peer_id: proto::PeerId,
1654 cx: &mut Context<Self>,
1655 ) -> proto::ProjectTransaction {
1656 let mut serialized_transaction = proto::ProjectTransaction {
1657 buffer_ids: Default::default(),
1658 transactions: Default::default(),
1659 };
1660 for (buffer, transaction) in project_transaction.0 {
1661 self.create_buffer_for_peer(&buffer, peer_id, cx)
1662 .detach_and_log_err(cx);
1663 serialized_transaction
1664 .buffer_ids
1665 .push(buffer.read(cx).remote_id().into());
1666 serialized_transaction
1667 .transactions
1668 .push(language::proto::serialize_transaction(&transaction));
1669 }
1670 serialized_transaction
1671 }
1672}
1673
1674impl OpenBuffer {
1675 fn upgrade(&self) -> Option<Entity<Buffer>> {
1676 match self {
1677 OpenBuffer::Complete { buffer, .. } => buffer.upgrade(),
1678 OpenBuffer::Operations(_) => None,
1679 }
1680 }
1681}
1682
1683fn is_not_found_error(error: &anyhow::Error) -> bool {
1684 error
1685 .root_cause()
1686 .downcast_ref::<io::Error>()
1687 .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
1688}