buffer_store.rs

   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};
  24use smol::channel::Receiver;
  25use std::{io, pin::pin, 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_buffer = worktree.update(cx, |worktree, cx| {
 621            let load_file = worktree.load_file(path.as_ref(), cx);
 622            let reservation = cx.reserve_entity();
 623            let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
 624            let path = path.clone();
 625            cx.spawn(async move |_, cx| {
 626                let loaded = load_file.await.with_context(|| {
 627                    format!("Could not open path: {}", path.display(PathStyle::local()))
 628                })?;
 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        });
 639
 640        cx.spawn(async move |this, cx| {
 641            let buffer = match load_buffer.await {
 642                Ok(buffer) => Ok(buffer),
 643                Err(error) if is_not_found_error(&error) => cx.new(|cx| {
 644                    let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
 645                    let text_buffer = text::Buffer::new(ReplicaId::LOCAL, buffer_id, "");
 646                    Buffer::build(
 647                        text_buffer,
 648                        Some(Arc::new(File {
 649                            worktree,
 650                            path,
 651                            disk_state: DiskState::New,
 652                            entry_id: None,
 653                            is_local: true,
 654                            is_private: false,
 655                        })),
 656                        Capability::ReadWrite,
 657                    )
 658                }),
 659                Err(e) => Err(e),
 660            }?;
 661            this.update(cx, |this, cx| {
 662                this.add_buffer(buffer.clone(), cx)?;
 663                let buffer_id = buffer.read(cx).remote_id();
 664                if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 665                    this.path_to_buffer_id.insert(
 666                        ProjectPath {
 667                            worktree_id: file.worktree_id(cx),
 668                            path: file.path.clone(),
 669                        },
 670                        buffer_id,
 671                    );
 672                    let this = this.as_local_mut().unwrap();
 673                    if let Some(entry_id) = file.entry_id {
 674                        this.local_buffer_ids_by_entry_id
 675                            .insert(entry_id, buffer_id);
 676                    }
 677                }
 678
 679                anyhow::Ok(())
 680            })??;
 681
 682            Ok(buffer)
 683        })
 684    }
 685
 686    fn create_buffer(
 687        &self,
 688        project_searchable: bool,
 689        cx: &mut Context<BufferStore>,
 690    ) -> Task<Result<Entity<Buffer>>> {
 691        cx.spawn(async move |buffer_store, cx| {
 692            let buffer =
 693                cx.new(|cx| Buffer::local("", cx).with_language(language::PLAIN_TEXT.clone(), cx))?;
 694            buffer_store.update(cx, |buffer_store, cx| {
 695                buffer_store.add_buffer(buffer.clone(), cx).log_err();
 696                if !project_searchable {
 697                    buffer_store
 698                        .non_searchable_buffers
 699                        .insert(buffer.read(cx).remote_id());
 700                }
 701            })?;
 702            Ok(buffer)
 703        })
 704    }
 705
 706    fn reload_buffers(
 707        &self,
 708        buffers: HashSet<Entity<Buffer>>,
 709        push_to_history: bool,
 710        cx: &mut Context<BufferStore>,
 711    ) -> Task<Result<ProjectTransaction>> {
 712        cx.spawn(async move |_, cx| {
 713            let mut project_transaction = ProjectTransaction::default();
 714            for buffer in buffers {
 715                let transaction = buffer.update(cx, |buffer, cx| buffer.reload(cx))?.await?;
 716                buffer.update(cx, |buffer, cx| {
 717                    if let Some(transaction) = transaction {
 718                        if !push_to_history {
 719                            buffer.forget_transaction(transaction.id);
 720                        }
 721                        project_transaction.0.insert(cx.entity(), transaction);
 722                    }
 723                })?;
 724            }
 725
 726            Ok(project_transaction)
 727        })
 728    }
 729}
 730
 731impl BufferStore {
 732    pub fn init(client: &AnyProtoClient) {
 733        client.add_entity_message_handler(Self::handle_buffer_reloaded);
 734        client.add_entity_message_handler(Self::handle_buffer_saved);
 735        client.add_entity_message_handler(Self::handle_update_buffer_file);
 736        client.add_entity_request_handler(Self::handle_save_buffer);
 737        client.add_entity_request_handler(Self::handle_reload_buffers);
 738    }
 739
 740    /// Creates a buffer store, optionally retaining its buffers.
 741    pub fn local(worktree_store: Entity<WorktreeStore>, cx: &mut Context<Self>) -> Self {
 742        Self {
 743            state: BufferStoreState::Local(LocalBufferStore {
 744                local_buffer_ids_by_entry_id: Default::default(),
 745                worktree_store: worktree_store.clone(),
 746                _subscription: cx.subscribe(&worktree_store, |this, _, event, cx| {
 747                    if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
 748                        let this = this.as_local_mut().unwrap();
 749                        this.subscribe_to_worktree(worktree, cx);
 750                    }
 751                }),
 752            }),
 753            downstream_client: None,
 754            opened_buffers: Default::default(),
 755            path_to_buffer_id: Default::default(),
 756            shared_buffers: Default::default(),
 757            loading_buffers: Default::default(),
 758            non_searchable_buffers: Default::default(),
 759            worktree_store,
 760        }
 761    }
 762
 763    pub fn remote(
 764        worktree_store: Entity<WorktreeStore>,
 765        upstream_client: AnyProtoClient,
 766        remote_id: u64,
 767        _cx: &mut Context<Self>,
 768    ) -> Self {
 769        Self {
 770            state: BufferStoreState::Remote(RemoteBufferStore {
 771                shared_with_me: Default::default(),
 772                loading_remote_buffers_by_id: Default::default(),
 773                remote_buffer_listeners: Default::default(),
 774                project_id: remote_id,
 775                upstream_client,
 776                worktree_store: worktree_store.clone(),
 777            }),
 778            downstream_client: None,
 779            opened_buffers: Default::default(),
 780            path_to_buffer_id: Default::default(),
 781            loading_buffers: Default::default(),
 782            shared_buffers: Default::default(),
 783            non_searchable_buffers: Default::default(),
 784            worktree_store,
 785        }
 786    }
 787
 788    fn as_local_mut(&mut self) -> Option<&mut LocalBufferStore> {
 789        match &mut self.state {
 790            BufferStoreState::Local(state) => Some(state),
 791            _ => None,
 792        }
 793    }
 794
 795    fn as_remote_mut(&mut self) -> Option<&mut RemoteBufferStore> {
 796        match &mut self.state {
 797            BufferStoreState::Remote(state) => Some(state),
 798            _ => None,
 799        }
 800    }
 801
 802    fn as_remote(&self) -> Option<&RemoteBufferStore> {
 803        match &self.state {
 804            BufferStoreState::Remote(state) => Some(state),
 805            _ => None,
 806        }
 807    }
 808
 809    pub fn open_buffer(
 810        &mut self,
 811        project_path: ProjectPath,
 812        cx: &mut Context<Self>,
 813    ) -> Task<Result<Entity<Buffer>>> {
 814        if let Some(buffer) = self.get_by_path(&project_path) {
 815            cx.emit(BufferStoreEvent::BufferOpened {
 816                buffer: buffer.clone(),
 817                project_path,
 818            });
 819
 820            return Task::ready(Ok(buffer));
 821        }
 822
 823        let task = match self.loading_buffers.entry(project_path.clone()) {
 824            hash_map::Entry::Occupied(e) => e.get().clone(),
 825            hash_map::Entry::Vacant(entry) => {
 826                let path = project_path.path.clone();
 827                let Some(worktree) = self
 828                    .worktree_store
 829                    .read(cx)
 830                    .worktree_for_id(project_path.worktree_id, cx)
 831                else {
 832                    return Task::ready(Err(anyhow!("no such worktree")));
 833                };
 834                let load_buffer = match &self.state {
 835                    BufferStoreState::Local(this) => this.open_buffer(path, worktree, cx),
 836                    BufferStoreState::Remote(this) => this.open_buffer(path, worktree, cx),
 837                };
 838
 839                entry
 840                    .insert(
 841                        cx.spawn(async move |this, cx| {
 842                            let load_result = load_buffer.await;
 843                            this.update(cx, |this, cx| {
 844                                // Record the fact that the buffer is no longer loading.
 845                                this.loading_buffers.remove(&project_path);
 846
 847                                let buffer = load_result.map_err(Arc::new)?;
 848                                cx.emit(BufferStoreEvent::BufferOpened {
 849                                    buffer: buffer.clone(),
 850                                    project_path,
 851                                });
 852
 853                                Ok(buffer)
 854                            })?
 855                        })
 856                        .shared(),
 857                    )
 858                    .clone()
 859            }
 860        };
 861
 862        cx.background_spawn(async move {
 863            task.await.map_err(|e| {
 864                if e.error_code() != ErrorCode::Internal {
 865                    anyhow!(e.error_code())
 866                } else {
 867                    anyhow!("{e}")
 868                }
 869            })
 870        })
 871    }
 872
 873    pub fn create_buffer(
 874        &mut self,
 875        project_searchable: bool,
 876        cx: &mut Context<Self>,
 877    ) -> Task<Result<Entity<Buffer>>> {
 878        match &self.state {
 879            BufferStoreState::Local(this) => this.create_buffer(project_searchable, cx),
 880            BufferStoreState::Remote(this) => this.create_buffer(project_searchable, cx),
 881        }
 882    }
 883
 884    pub fn save_buffer(
 885        &mut self,
 886        buffer: Entity<Buffer>,
 887        cx: &mut Context<Self>,
 888    ) -> Task<Result<()>> {
 889        match &mut self.state {
 890            BufferStoreState::Local(this) => this.save_buffer(buffer, cx),
 891            BufferStoreState::Remote(this) => this.save_remote_buffer(buffer, None, cx),
 892        }
 893    }
 894
 895    pub fn save_buffer_as(
 896        &mut self,
 897        buffer: Entity<Buffer>,
 898        path: ProjectPath,
 899        cx: &mut Context<Self>,
 900    ) -> Task<Result<()>> {
 901        let old_file = buffer.read(cx).file().cloned();
 902        let task = match &self.state {
 903            BufferStoreState::Local(this) => this.save_buffer_as(buffer.clone(), path, cx),
 904            BufferStoreState::Remote(this) => {
 905                this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
 906            }
 907        };
 908        cx.spawn(async move |this, cx| {
 909            task.await?;
 910            this.update(cx, |_, cx| {
 911                cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
 912            })
 913        })
 914    }
 915
 916    fn add_buffer(&mut self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
 917        let buffer = buffer_entity.read(cx);
 918        let remote_id = buffer.remote_id();
 919        let path = File::from_dyn(buffer.file()).map(|file| ProjectPath {
 920            path: file.path.clone(),
 921            worktree_id: file.worktree_id(cx),
 922        });
 923        let is_remote = buffer.replica_id().is_remote();
 924        let open_buffer = OpenBuffer::Complete {
 925            buffer: buffer_entity.downgrade(),
 926        };
 927
 928        let handle = cx.entity().downgrade();
 929        buffer_entity.update(cx, move |_, cx| {
 930            cx.on_release(move |buffer, cx| {
 931                handle
 932                    .update(cx, |_, cx| {
 933                        cx.emit(BufferStoreEvent::BufferDropped(buffer.remote_id()))
 934                    })
 935                    .ok();
 936            })
 937            .detach()
 938        });
 939        let _expect_path_to_exist;
 940        match self.opened_buffers.entry(remote_id) {
 941            hash_map::Entry::Vacant(entry) => {
 942                entry.insert(open_buffer);
 943                _expect_path_to_exist = false;
 944            }
 945            hash_map::Entry::Occupied(mut entry) => {
 946                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 947                    buffer_entity.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx));
 948                } else if entry.get().upgrade().is_some() {
 949                    if is_remote {
 950                        return Ok(());
 951                    } else {
 952                        debug_panic!("buffer {remote_id} was already registered");
 953                        anyhow::bail!("buffer {remote_id} was already registered");
 954                    }
 955                }
 956                entry.insert(open_buffer);
 957                _expect_path_to_exist = true;
 958            }
 959        }
 960
 961        if let Some(path) = path {
 962            self.path_to_buffer_id.insert(path, remote_id);
 963        }
 964
 965        cx.subscribe(&buffer_entity, Self::on_buffer_event).detach();
 966        cx.emit(BufferStoreEvent::BufferAdded(buffer_entity));
 967        Ok(())
 968    }
 969
 970    pub fn buffers(&self) -> impl '_ + Iterator<Item = Entity<Buffer>> {
 971        self.opened_buffers
 972            .values()
 973            .filter_map(|buffer| buffer.upgrade())
 974    }
 975
 976    pub(crate) fn is_searchable(&self, id: &BufferId) -> bool {
 977        !self.non_searchable_buffers.contains(&id)
 978    }
 979
 980    pub fn loading_buffers(
 981        &self,
 982    ) -> impl Iterator<Item = (&ProjectPath, impl Future<Output = Result<Entity<Buffer>>>)> {
 983        self.loading_buffers.iter().map(|(path, task)| {
 984            let task = task.clone();
 985            (path, async move {
 986                task.await.map_err(|e| {
 987                    if e.error_code() != ErrorCode::Internal {
 988                        anyhow!(e.error_code())
 989                    } else {
 990                        anyhow!("{e}")
 991                    }
 992                })
 993            })
 994        })
 995    }
 996
 997    pub fn buffer_id_for_project_path(&self, project_path: &ProjectPath) -> Option<&BufferId> {
 998        self.path_to_buffer_id.get(project_path)
 999    }
1000
1001    pub fn get_by_path(&self, path: &ProjectPath) -> Option<Entity<Buffer>> {
1002        self.path_to_buffer_id
1003            .get(path)
1004            .and_then(|buffer_id| self.get(*buffer_id))
1005    }
1006
1007    pub fn get(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1008        self.opened_buffers.get(&buffer_id)?.upgrade()
1009    }
1010
1011    pub fn get_existing(&self, buffer_id: BufferId) -> Result<Entity<Buffer>> {
1012        self.get(buffer_id)
1013            .with_context(|| format!("unknown buffer id {buffer_id}"))
1014    }
1015
1016    pub fn get_possibly_incomplete(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1017        self.get(buffer_id).or_else(|| {
1018            self.as_remote()
1019                .and_then(|remote| remote.loading_remote_buffers_by_id.get(&buffer_id).cloned())
1020        })
1021    }
1022
1023    pub fn buffer_version_info(&self, cx: &App) -> (Vec<proto::BufferVersion>, Vec<BufferId>) {
1024        let buffers = self
1025            .buffers()
1026            .map(|buffer| {
1027                let buffer = buffer.read(cx);
1028                proto::BufferVersion {
1029                    id: buffer.remote_id().into(),
1030                    version: language::proto::serialize_version(&buffer.version),
1031                }
1032            })
1033            .collect();
1034        let incomplete_buffer_ids = self
1035            .as_remote()
1036            .map(|remote| remote.incomplete_buffer_ids())
1037            .unwrap_or_default();
1038        (buffers, incomplete_buffer_ids)
1039    }
1040
1041    pub fn disconnected_from_host(&mut self, cx: &mut App) {
1042        for open_buffer in self.opened_buffers.values_mut() {
1043            if let Some(buffer) = open_buffer.upgrade() {
1044                buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1045            }
1046        }
1047
1048        for buffer in self.buffers() {
1049            buffer.update(cx, |buffer, cx| {
1050                buffer.set_capability(Capability::ReadOnly, cx)
1051            });
1052        }
1053
1054        if let Some(remote) = self.as_remote_mut() {
1055            // Wake up all futures currently waiting on a buffer to get opened,
1056            // to give them a chance to fail now that we've disconnected.
1057            remote.remote_buffer_listeners.clear()
1058        }
1059    }
1060
1061    pub fn shared(&mut self, remote_id: u64, downstream_client: AnyProtoClient, _cx: &mut App) {
1062        self.downstream_client = Some((downstream_client, remote_id));
1063    }
1064
1065    pub fn unshared(&mut self, _cx: &mut Context<Self>) {
1066        self.downstream_client.take();
1067        self.forget_shared_buffers();
1068    }
1069
1070    pub fn discard_incomplete(&mut self) {
1071        self.opened_buffers
1072            .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
1073    }
1074
1075    fn buffer_changed_file(&mut self, buffer: Entity<Buffer>, cx: &mut App) -> Option<()> {
1076        let file = File::from_dyn(buffer.read(cx).file())?;
1077
1078        let remote_id = buffer.read(cx).remote_id();
1079        if let Some(entry_id) = file.entry_id {
1080            if let Some(local) = self.as_local_mut() {
1081                match local.local_buffer_ids_by_entry_id.get(&entry_id) {
1082                    Some(_) => {
1083                        return None;
1084                    }
1085                    None => {
1086                        local
1087                            .local_buffer_ids_by_entry_id
1088                            .insert(entry_id, remote_id);
1089                    }
1090                }
1091            }
1092            self.path_to_buffer_id.insert(
1093                ProjectPath {
1094                    worktree_id: file.worktree_id(cx),
1095                    path: file.path.clone(),
1096                },
1097                remote_id,
1098            );
1099        };
1100
1101        Some(())
1102    }
1103
1104    fn on_buffer_event(
1105        &mut self,
1106        buffer: Entity<Buffer>,
1107        event: &BufferEvent,
1108        cx: &mut Context<Self>,
1109    ) {
1110        match event {
1111            BufferEvent::FileHandleChanged => {
1112                self.buffer_changed_file(buffer, cx);
1113            }
1114            BufferEvent::Reloaded => {
1115                let Some((downstream_client, project_id)) = self.downstream_client.as_ref() else {
1116                    return;
1117                };
1118                let buffer = buffer.read(cx);
1119                downstream_client
1120                    .send(proto::BufferReloaded {
1121                        project_id: *project_id,
1122                        buffer_id: buffer.remote_id().to_proto(),
1123                        version: serialize_version(&buffer.version()),
1124                        mtime: buffer.saved_mtime().map(|t| t.into()),
1125                        line_ending: serialize_line_ending(buffer.line_ending()) as i32,
1126                    })
1127                    .log_err();
1128            }
1129            BufferEvent::LanguageChanged => {}
1130            _ => {}
1131        }
1132    }
1133
1134    pub async fn handle_update_buffer(
1135        this: Entity<Self>,
1136        envelope: TypedEnvelope<proto::UpdateBuffer>,
1137        mut cx: AsyncApp,
1138    ) -> Result<proto::Ack> {
1139        let payload = envelope.payload;
1140        let buffer_id = BufferId::new(payload.buffer_id)?;
1141        let ops = payload
1142            .operations
1143            .into_iter()
1144            .map(language::proto::deserialize_operation)
1145            .collect::<Result<Vec<_>, _>>()?;
1146        this.update(&mut cx, |this, cx| {
1147            match this.opened_buffers.entry(buffer_id) {
1148                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
1149                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
1150                    OpenBuffer::Complete { buffer, .. } => {
1151                        if let Some(buffer) = buffer.upgrade() {
1152                            buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx));
1153                        }
1154                    }
1155                },
1156                hash_map::Entry::Vacant(e) => {
1157                    e.insert(OpenBuffer::Operations(ops));
1158                }
1159            }
1160            Ok(proto::Ack {})
1161        })?
1162    }
1163
1164    pub fn register_shared_lsp_handle(
1165        &mut self,
1166        peer_id: proto::PeerId,
1167        buffer_id: BufferId,
1168        handle: OpenLspBufferHandle,
1169    ) {
1170        if let Some(shared_buffers) = self.shared_buffers.get_mut(&peer_id)
1171            && let Some(buffer) = shared_buffers.get_mut(&buffer_id)
1172        {
1173            buffer.lsp_handle = Some(handle);
1174            return;
1175        }
1176        debug_panic!("tried to register shared lsp handle, but buffer was not shared")
1177    }
1178
1179    pub fn handle_synchronize_buffers(
1180        &mut self,
1181        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
1182        cx: &mut Context<Self>,
1183        client: Arc<Client>,
1184    ) -> Result<proto::SynchronizeBuffersResponse> {
1185        let project_id = envelope.payload.project_id;
1186        let mut response = proto::SynchronizeBuffersResponse {
1187            buffers: Default::default(),
1188        };
1189        let Some(guest_id) = envelope.original_sender_id else {
1190            anyhow::bail!("missing original_sender_id on SynchronizeBuffers request");
1191        };
1192
1193        self.shared_buffers.entry(guest_id).or_default().clear();
1194        for buffer in envelope.payload.buffers {
1195            let buffer_id = BufferId::new(buffer.id)?;
1196            let remote_version = language::proto::deserialize_version(&buffer.version);
1197            if let Some(buffer) = self.get(buffer_id) {
1198                self.shared_buffers
1199                    .entry(guest_id)
1200                    .or_default()
1201                    .entry(buffer_id)
1202                    .or_insert_with(|| SharedBuffer {
1203                        buffer: buffer.clone(),
1204                        lsp_handle: None,
1205                    });
1206
1207                let buffer = buffer.read(cx);
1208                response.buffers.push(proto::BufferVersion {
1209                    id: buffer_id.into(),
1210                    version: language::proto::serialize_version(&buffer.version),
1211                });
1212
1213                let operations = buffer.serialize_ops(Some(remote_version), cx);
1214                let client = client.clone();
1215                if let Some(file) = buffer.file() {
1216                    client
1217                        .send(proto::UpdateBufferFile {
1218                            project_id,
1219                            buffer_id: buffer_id.into(),
1220                            file: Some(file.to_proto(cx)),
1221                        })
1222                        .log_err();
1223                }
1224
1225                // TODO(max): do something
1226                // client
1227                //     .send(proto::UpdateStagedText {
1228                //         project_id,
1229                //         buffer_id: buffer_id.into(),
1230                //         diff_base: buffer.diff_base().map(ToString::to_string),
1231                //     })
1232                //     .log_err();
1233
1234                client
1235                    .send(proto::BufferReloaded {
1236                        project_id,
1237                        buffer_id: buffer_id.into(),
1238                        version: language::proto::serialize_version(buffer.saved_version()),
1239                        mtime: buffer.saved_mtime().map(|time| time.into()),
1240                        line_ending: language::proto::serialize_line_ending(buffer.line_ending())
1241                            as i32,
1242                    })
1243                    .log_err();
1244
1245                cx.background_spawn(
1246                    async move {
1247                        let operations = operations.await;
1248                        for chunk in split_operations(operations) {
1249                            client
1250                                .request(proto::UpdateBuffer {
1251                                    project_id,
1252                                    buffer_id: buffer_id.into(),
1253                                    operations: chunk,
1254                                })
1255                                .await?;
1256                        }
1257                        anyhow::Ok(())
1258                    }
1259                    .log_err(),
1260                )
1261                .detach();
1262            }
1263        }
1264        Ok(response)
1265    }
1266
1267    pub fn handle_create_buffer_for_peer(
1268        &mut self,
1269        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
1270        replica_id: ReplicaId,
1271        capability: Capability,
1272        cx: &mut Context<Self>,
1273    ) -> Result<()> {
1274        let remote = self
1275            .as_remote_mut()
1276            .context("buffer store is not a remote")?;
1277
1278        if let Some(buffer) =
1279            remote.handle_create_buffer_for_peer(envelope, replica_id, capability, cx)?
1280        {
1281            self.add_buffer(buffer, cx)?;
1282        }
1283
1284        Ok(())
1285    }
1286
1287    pub async fn handle_update_buffer_file(
1288        this: Entity<Self>,
1289        envelope: TypedEnvelope<proto::UpdateBufferFile>,
1290        mut cx: AsyncApp,
1291    ) -> Result<()> {
1292        let buffer_id = envelope.payload.buffer_id;
1293        let buffer_id = BufferId::new(buffer_id)?;
1294
1295        this.update(&mut cx, |this, cx| {
1296            let payload = envelope.payload.clone();
1297            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1298                let file = payload.file.context("invalid file")?;
1299                let worktree = this
1300                    .worktree_store
1301                    .read(cx)
1302                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
1303                    .context("no such worktree")?;
1304                let file = File::from_proto(file, worktree, cx)?;
1305                let old_file = buffer.update(cx, |buffer, cx| {
1306                    let old_file = buffer.file().cloned();
1307                    let new_path = file.path.clone();
1308
1309                    buffer.file_updated(Arc::new(file), cx);
1310                    if old_file.as_ref().is_none_or(|old| *old.path() != new_path) {
1311                        Some(old_file)
1312                    } else {
1313                        None
1314                    }
1315                });
1316                if let Some(old_file) = old_file {
1317                    cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
1318                }
1319            }
1320            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1321                downstream_client
1322                    .send(proto::UpdateBufferFile {
1323                        project_id: *project_id,
1324                        buffer_id: buffer_id.into(),
1325                        file: envelope.payload.file,
1326                    })
1327                    .log_err();
1328            }
1329            Ok(())
1330        })?
1331    }
1332
1333    pub async fn handle_save_buffer(
1334        this: Entity<Self>,
1335        envelope: TypedEnvelope<proto::SaveBuffer>,
1336        mut cx: AsyncApp,
1337    ) -> Result<proto::BufferSaved> {
1338        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1339        let (buffer, project_id) = this.read_with(&cx, |this, _| {
1340            anyhow::Ok((
1341                this.get_existing(buffer_id)?,
1342                this.downstream_client
1343                    .as_ref()
1344                    .map(|(_, project_id)| *project_id)
1345                    .context("project is not shared")?,
1346            ))
1347        })??;
1348        buffer
1349            .update(&mut cx, |buffer, _| {
1350                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
1351            })?
1352            .await?;
1353        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id())?;
1354
1355        if let Some(new_path) = envelope.payload.new_path
1356            && let Some(new_path) = ProjectPath::from_proto(new_path)
1357        {
1358            this.update(&mut cx, |this, cx| {
1359                this.save_buffer_as(buffer.clone(), new_path, cx)
1360            })?
1361            .await?;
1362        } else {
1363            this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
1364                .await?;
1365        }
1366
1367        buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
1368            project_id,
1369            buffer_id: buffer_id.into(),
1370            version: serialize_version(buffer.saved_version()),
1371            mtime: buffer.saved_mtime().map(|time| time.into()),
1372        })
1373    }
1374
1375    pub async fn handle_close_buffer(
1376        this: Entity<Self>,
1377        envelope: TypedEnvelope<proto::CloseBuffer>,
1378        mut cx: AsyncApp,
1379    ) -> Result<()> {
1380        let peer_id = envelope.sender_id;
1381        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1382        this.update(&mut cx, |this, cx| {
1383            if let Some(shared) = this.shared_buffers.get_mut(&peer_id)
1384                && shared.remove(&buffer_id).is_some()
1385            {
1386                cx.emit(BufferStoreEvent::SharedBufferClosed(peer_id, buffer_id));
1387                if shared.is_empty() {
1388                    this.shared_buffers.remove(&peer_id);
1389                }
1390                return;
1391            }
1392            debug_panic!(
1393                "peer_id {} closed buffer_id {} which was either not open or already closed",
1394                peer_id,
1395                buffer_id
1396            )
1397        })
1398    }
1399
1400    pub async fn handle_buffer_saved(
1401        this: Entity<Self>,
1402        envelope: TypedEnvelope<proto::BufferSaved>,
1403        mut cx: AsyncApp,
1404    ) -> Result<()> {
1405        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1406        let version = deserialize_version(&envelope.payload.version);
1407        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1408        this.update(&mut cx, move |this, cx| {
1409            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1410                buffer.update(cx, |buffer, cx| {
1411                    buffer.did_save(version, mtime, cx);
1412                });
1413            }
1414
1415            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1416                downstream_client
1417                    .send(proto::BufferSaved {
1418                        project_id: *project_id,
1419                        buffer_id: buffer_id.into(),
1420                        mtime: envelope.payload.mtime,
1421                        version: envelope.payload.version,
1422                    })
1423                    .log_err();
1424            }
1425        })
1426    }
1427
1428    pub async fn handle_buffer_reloaded(
1429        this: Entity<Self>,
1430        envelope: TypedEnvelope<proto::BufferReloaded>,
1431        mut cx: AsyncApp,
1432    ) -> Result<()> {
1433        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1434        let version = deserialize_version(&envelope.payload.version);
1435        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1436        let line_ending = deserialize_line_ending(
1437            proto::LineEnding::from_i32(envelope.payload.line_ending)
1438                .context("missing line ending")?,
1439        );
1440        this.update(&mut cx, |this, cx| {
1441            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1442                buffer.update(cx, |buffer, cx| {
1443                    buffer.did_reload(version, line_ending, mtime, cx);
1444                });
1445            }
1446
1447            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1448                downstream_client
1449                    .send(proto::BufferReloaded {
1450                        project_id: *project_id,
1451                        buffer_id: buffer_id.into(),
1452                        mtime: envelope.payload.mtime,
1453                        version: envelope.payload.version,
1454                        line_ending: envelope.payload.line_ending,
1455                    })
1456                    .log_err();
1457            }
1458        })
1459    }
1460
1461    pub fn reload_buffers(
1462        &self,
1463        buffers: HashSet<Entity<Buffer>>,
1464        push_to_history: bool,
1465        cx: &mut Context<Self>,
1466    ) -> Task<Result<ProjectTransaction>> {
1467        if buffers.is_empty() {
1468            return Task::ready(Ok(ProjectTransaction::default()));
1469        }
1470        match &self.state {
1471            BufferStoreState::Local(this) => this.reload_buffers(buffers, push_to_history, cx),
1472            BufferStoreState::Remote(this) => this.reload_buffers(buffers, push_to_history, cx),
1473        }
1474    }
1475
1476    async fn handle_reload_buffers(
1477        this: Entity<Self>,
1478        envelope: TypedEnvelope<proto::ReloadBuffers>,
1479        mut cx: AsyncApp,
1480    ) -> Result<proto::ReloadBuffersResponse> {
1481        let sender_id = envelope.original_sender_id().unwrap_or_default();
1482        let reload = this.update(&mut cx, |this, cx| {
1483            let mut buffers = HashSet::default();
1484            for buffer_id in &envelope.payload.buffer_ids {
1485                let buffer_id = BufferId::new(*buffer_id)?;
1486                buffers.insert(this.get_existing(buffer_id)?);
1487            }
1488            anyhow::Ok(this.reload_buffers(buffers, false, cx))
1489        })??;
1490
1491        let project_transaction = reload.await?;
1492        let project_transaction = this.update(&mut cx, |this, cx| {
1493            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
1494        })?;
1495        Ok(proto::ReloadBuffersResponse {
1496            transaction: Some(project_transaction),
1497        })
1498    }
1499
1500    pub fn create_buffer_for_peer(
1501        &mut self,
1502        buffer: &Entity<Buffer>,
1503        peer_id: proto::PeerId,
1504        cx: &mut Context<Self>,
1505    ) -> Task<Result<()>> {
1506        let buffer_id = buffer.read(cx).remote_id();
1507        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
1508        if shared_buffers.contains_key(&buffer_id) {
1509            return Task::ready(Ok(()));
1510        }
1511        shared_buffers.insert(
1512            buffer_id,
1513            SharedBuffer {
1514                buffer: buffer.clone(),
1515                lsp_handle: None,
1516            },
1517        );
1518
1519        let Some((client, project_id)) = self.downstream_client.clone() else {
1520            return Task::ready(Ok(()));
1521        };
1522
1523        cx.spawn(async move |this, cx| {
1524            let Some(buffer) = this.read_with(cx, |this, _| this.get(buffer_id))? else {
1525                return anyhow::Ok(());
1526            };
1527
1528            let operations = buffer.update(cx, |b, cx| b.serialize_ops(None, cx))?;
1529            let operations = operations.await;
1530            let state = buffer.update(cx, |buffer, cx| buffer.to_proto(cx))?;
1531
1532            let initial_state = proto::CreateBufferForPeer {
1533                project_id,
1534                peer_id: Some(peer_id),
1535                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1536            };
1537
1538            if client.send(initial_state).log_err().is_some() {
1539                let client = client.clone();
1540                cx.background_spawn(async move {
1541                    let mut chunks = split_operations(operations).peekable();
1542                    while let Some(chunk) = chunks.next() {
1543                        let is_last = chunks.peek().is_none();
1544                        client.send(proto::CreateBufferForPeer {
1545                            project_id,
1546                            peer_id: Some(peer_id),
1547                            variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
1548                                proto::BufferChunk {
1549                                    buffer_id: buffer_id.into(),
1550                                    operations: chunk,
1551                                    is_last,
1552                                },
1553                            )),
1554                        })?;
1555                    }
1556                    anyhow::Ok(())
1557                })
1558                .await
1559                .log_err();
1560            }
1561            Ok(())
1562        })
1563    }
1564
1565    pub fn forget_shared_buffers(&mut self) {
1566        self.shared_buffers.clear();
1567    }
1568
1569    pub fn forget_shared_buffers_for(&mut self, peer_id: &proto::PeerId) {
1570        self.shared_buffers.remove(peer_id);
1571    }
1572
1573    pub fn update_peer_id(&mut self, old_peer_id: &proto::PeerId, new_peer_id: proto::PeerId) {
1574        if let Some(buffers) = self.shared_buffers.remove(old_peer_id) {
1575            self.shared_buffers.insert(new_peer_id, buffers);
1576        }
1577    }
1578
1579    pub fn has_shared_buffers(&self) -> bool {
1580        !self.shared_buffers.is_empty()
1581    }
1582
1583    pub fn create_local_buffer(
1584        &mut self,
1585        text: &str,
1586        language: Option<Arc<Language>>,
1587        project_searchable: bool,
1588        cx: &mut Context<Self>,
1589    ) -> Entity<Buffer> {
1590        let buffer = cx.new(|cx| {
1591            Buffer::local(text, cx)
1592                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1593        });
1594
1595        self.add_buffer(buffer.clone(), cx).log_err();
1596        let buffer_id = buffer.read(cx).remote_id();
1597        if !project_searchable {
1598            self.non_searchable_buffers.insert(buffer_id);
1599        }
1600
1601        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1602            self.path_to_buffer_id.insert(
1603                ProjectPath {
1604                    worktree_id: file.worktree_id(cx),
1605                    path: file.path.clone(),
1606                },
1607                buffer_id,
1608            );
1609            let this = self
1610                .as_local_mut()
1611                .expect("local-only method called in a non-local context");
1612            if let Some(entry_id) = file.entry_id {
1613                this.local_buffer_ids_by_entry_id
1614                    .insert(entry_id, buffer_id);
1615            }
1616        }
1617        buffer
1618    }
1619
1620    pub fn deserialize_project_transaction(
1621        &mut self,
1622        message: proto::ProjectTransaction,
1623        push_to_history: bool,
1624        cx: &mut Context<Self>,
1625    ) -> Task<Result<ProjectTransaction>> {
1626        if let Some(this) = self.as_remote_mut() {
1627            this.deserialize_project_transaction(message, push_to_history, cx)
1628        } else {
1629            debug_panic!("not a remote buffer store");
1630            Task::ready(Err(anyhow!("not a remote buffer store")))
1631        }
1632    }
1633
1634    pub fn wait_for_remote_buffer(
1635        &mut self,
1636        id: BufferId,
1637        cx: &mut Context<BufferStore>,
1638    ) -> Task<Result<Entity<Buffer>>> {
1639        if let Some(this) = self.as_remote_mut() {
1640            this.wait_for_remote_buffer(id, cx)
1641        } else {
1642            debug_panic!("not a remote buffer store");
1643            Task::ready(Err(anyhow!("not a remote buffer store")))
1644        }
1645    }
1646
1647    pub fn serialize_project_transaction_for_peer(
1648        &mut self,
1649        project_transaction: ProjectTransaction,
1650        peer_id: proto::PeerId,
1651        cx: &mut Context<Self>,
1652    ) -> proto::ProjectTransaction {
1653        let mut serialized_transaction = proto::ProjectTransaction {
1654            buffer_ids: Default::default(),
1655            transactions: Default::default(),
1656        };
1657        for (buffer, transaction) in project_transaction.0 {
1658            self.create_buffer_for_peer(&buffer, peer_id, cx)
1659                .detach_and_log_err(cx);
1660            serialized_transaction
1661                .buffer_ids
1662                .push(buffer.read(cx).remote_id().into());
1663            serialized_transaction
1664                .transactions
1665                .push(language::proto::serialize_transaction(&transaction));
1666        }
1667        serialized_transaction
1668    }
1669}
1670
1671impl OpenBuffer {
1672    fn upgrade(&self) -> Option<Entity<Buffer>> {
1673        match self {
1674            OpenBuffer::Complete { buffer, .. } => buffer.upgrade(),
1675            OpenBuffer::Operations(_) => None,
1676        }
1677    }
1678}
1679
1680fn is_not_found_error(error: &anyhow::Error) -> bool {
1681    error
1682        .root_cause()
1683        .downcast_ref::<io::Error>()
1684        .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
1685}