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