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