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