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