buffer_store.rs

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