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