buffer_store.rs

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