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