buffer_store.rs

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