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    non_searchable_buffers: HashSet<BufferId>,
  43}
  44
  45#[derive(Hash, Eq, PartialEq, Clone)]
  46struct SharedBuffer {
  47    buffer: Entity<Buffer>,
  48    lsp_handle: Option<OpenLspBufferHandle>,
  49}
  50
  51enum BufferStoreState {
  52    Local(LocalBufferStore),
  53    Remote(RemoteBufferStore),
  54}
  55
  56struct RemoteBufferStore {
  57    shared_with_me: HashSet<Entity<Buffer>>,
  58    upstream_client: AnyProtoClient,
  59    project_id: u64,
  60    loading_remote_buffers_by_id: HashMap<BufferId, Entity<Buffer>>,
  61    remote_buffer_listeners:
  62        HashMap<BufferId, Vec<oneshot::Sender<anyhow::Result<Entity<Buffer>>>>>,
  63    worktree_store: Entity<WorktreeStore>,
  64}
  65
  66struct LocalBufferStore {
  67    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
  68    worktree_store: Entity<WorktreeStore>,
  69    _subscription: Subscription,
  70}
  71
  72enum OpenBuffer {
  73    Complete { buffer: WeakEntity<Buffer> },
  74    Operations(Vec<Operation>),
  75}
  76
  77pub enum BufferStoreEvent {
  78    BufferAdded(Entity<Buffer>),
  79    BufferOpened {
  80        buffer: Entity<Buffer>,
  81        project_path: ProjectPath,
  82    },
  83    SharedBufferClosed(proto::PeerId, BufferId),
  84    BufferDropped(BufferId),
  85    BufferChangedFilePath {
  86        buffer: Entity<Buffer>,
  87        old_file: Option<Arc<dyn language::File>>,
  88    },
  89}
  90
  91#[derive(Default, Debug)]
  92pub struct ProjectTransaction(pub HashMap<Entity<Buffer>, language::Transaction>);
  93
  94impl EventEmitter<BufferStoreEvent> for BufferStore {}
  95
  96impl RemoteBufferStore {
  97    pub fn wait_for_remote_buffer(
  98        &mut self,
  99        id: BufferId,
 100        cx: &mut Context<BufferStore>,
 101    ) -> Task<Result<Entity<Buffer>>> {
 102        let (tx, rx) = oneshot::channel();
 103        self.remote_buffer_listeners.entry(id).or_default().push(tx);
 104
 105        cx.spawn(async move |this, cx| {
 106            if let Some(buffer) = this
 107                .read_with(cx, |buffer_store, _| buffer_store.get(id))
 108                .ok()
 109                .flatten()
 110            {
 111                return Ok(buffer);
 112            }
 113
 114            cx.background_spawn(async move { rx.await? }).await
 115        })
 116    }
 117
 118    fn save_remote_buffer(
 119        &self,
 120        buffer_handle: Entity<Buffer>,
 121        new_path: Option<proto::ProjectPath>,
 122        cx: &Context<BufferStore>,
 123    ) -> Task<Result<()>> {
 124        let buffer = buffer_handle.read(cx);
 125        let buffer_id = buffer.remote_id().into();
 126        let version = buffer.version();
 127        let rpc = self.upstream_client.clone();
 128        let project_id = self.project_id;
 129        drop(buffer);
 130        cx.spawn(async move |_, cx| {
 131            let response = rpc
 132                .request(proto::SaveBuffer {
 133                    project_id,
 134                    buffer_id,
 135                    new_path,
 136                    version: serialize_version(&version),
 137                })
 138                .await?;
 139            let version = deserialize_version(&response.version);
 140            let mtime = response.mtime.map(|mtime| mtime.into());
 141
 142            buffer_handle.update(cx, |buffer, cx| {
 143                buffer.did_save(version.clone(), mtime, cx);
 144            })?;
 145
 146            Ok(())
 147        })
 148    }
 149
 150    pub fn handle_create_buffer_for_peer(
 151        &mut self,
 152        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 153        replica_id: u16,
 154        capability: Capability,
 155        cx: &mut Context<BufferStore>,
 156    ) -> Result<Option<Entity<Buffer>>> {
 157        match envelope.payload.variant.context("missing variant")? {
 158            proto::create_buffer_for_peer::Variant::State(mut state) => {
 159                let buffer_id = BufferId::new(state.id)?;
 160
 161                let buffer_result = maybe!({
 162                    let mut buffer_file = None;
 163                    if let Some(file) = state.file.take() {
 164                        let worktree_id = worktree::WorktreeId::from_proto(file.worktree_id);
 165                        let worktree = self
 166                            .worktree_store
 167                            .read(cx)
 168                            .worktree_for_id(worktree_id, cx)
 169                            .with_context(|| {
 170                                format!("no worktree found for id {}", file.worktree_id)
 171                            })?;
 172                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
 173                            as Arc<dyn language::File>);
 174                    }
 175                    Buffer::from_proto(replica_id, capability, state, buffer_file)
 176                });
 177
 178                match buffer_result {
 179                    Ok(buffer) => {
 180                        let buffer = cx.new(|_| buffer);
 181                        self.loading_remote_buffers_by_id.insert(buffer_id, buffer);
 182                    }
 183                    Err(error) => {
 184                        if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
 185                            for listener in listeners {
 186                                listener.send(Err(anyhow!(error.cloned()))).ok();
 187                            }
 188                        }
 189                    }
 190                }
 191            }
 192            proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
 193                let buffer_id = BufferId::new(chunk.buffer_id)?;
 194                let buffer = self
 195                    .loading_remote_buffers_by_id
 196                    .get(&buffer_id)
 197                    .cloned()
 198                    .with_context(|| {
 199                        format!(
 200                            "received chunk for buffer {} without initial state",
 201                            chunk.buffer_id
 202                        )
 203                    })?;
 204
 205                let result = maybe!({
 206                    let operations = chunk
 207                        .operations
 208                        .into_iter()
 209                        .map(language::proto::deserialize_operation)
 210                        .collect::<Result<Vec<_>>>()?;
 211                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx));
 212                    anyhow::Ok(())
 213                });
 214
 215                if let Err(error) = result {
 216                    self.loading_remote_buffers_by_id.remove(&buffer_id);
 217                    if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
 218                        for listener in listeners {
 219                            listener.send(Err(error.cloned())).ok();
 220                        }
 221                    }
 222                } else if chunk.is_last {
 223                    self.loading_remote_buffers_by_id.remove(&buffer_id);
 224                    if self.upstream_client.is_via_collab() {
 225                        // retain buffers sent by peers to avoid races.
 226                        self.shared_with_me.insert(buffer.clone());
 227                    }
 228
 229                    if let Some(senders) = self.remote_buffer_listeners.remove(&buffer_id) {
 230                        for sender in senders {
 231                            sender.send(Ok(buffer.clone())).ok();
 232                        }
 233                    }
 234                    return Ok(Some(buffer));
 235                }
 236            }
 237        }
 238        return Ok(None);
 239    }
 240
 241    pub fn incomplete_buffer_ids(&self) -> Vec<BufferId> {
 242        self.loading_remote_buffers_by_id
 243            .keys()
 244            .copied()
 245            .collect::<Vec<_>>()
 246    }
 247
 248    pub fn deserialize_project_transaction(
 249        &self,
 250        message: proto::ProjectTransaction,
 251        push_to_history: bool,
 252        cx: &mut Context<BufferStore>,
 253    ) -> Task<Result<ProjectTransaction>> {
 254        cx.spawn(async move |this, cx| {
 255            let mut project_transaction = ProjectTransaction::default();
 256            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
 257            {
 258                let buffer_id = BufferId::new(buffer_id)?;
 259                let buffer = this
 260                    .update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
 261                    .await?;
 262                let transaction = language::proto::deserialize_transaction(transaction)?;
 263                project_transaction.0.insert(buffer, transaction);
 264            }
 265
 266            for (buffer, transaction) in &project_transaction.0 {
 267                buffer
 268                    .update(cx, |buffer, _| {
 269                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 270                    })?
 271                    .await?;
 272
 273                if push_to_history {
 274                    buffer.update(cx, |buffer, _| {
 275                        buffer.push_transaction(transaction.clone(), Instant::now());
 276                        buffer.finalize_last_transaction();
 277                    })?;
 278                }
 279            }
 280
 281            Ok(project_transaction)
 282        })
 283    }
 284
 285    fn open_buffer(
 286        &self,
 287        path: Arc<Path>,
 288        worktree: Entity<Worktree>,
 289        cx: &mut Context<BufferStore>,
 290    ) -> Task<Result<Entity<Buffer>>> {
 291        let worktree_id = worktree.read(cx).id().to_proto();
 292        let project_id = self.project_id;
 293        let client = self.upstream_client.clone();
 294        cx.spawn(async move |this, cx| {
 295            let response = client
 296                .request(proto::OpenBufferByPath {
 297                    project_id,
 298                    worktree_id,
 299                    path: path.to_proto(),
 300                })
 301                .await?;
 302            let buffer_id = BufferId::new(response.buffer_id)?;
 303
 304            let buffer = this
 305                .update(cx, {
 306                    |this, cx| this.wait_for_remote_buffer(buffer_id, cx)
 307                })?
 308                .await?;
 309
 310            Ok(buffer)
 311        })
 312    }
 313
 314    fn create_buffer(&self, cx: &mut Context<BufferStore>) -> Task<Result<Entity<Buffer>>> {
 315        let create = self.upstream_client.request(proto::OpenNewBuffer {
 316            project_id: self.project_id,
 317        });
 318        cx.spawn(async move |this, cx| {
 319            let response = create.await?;
 320            let buffer_id = BufferId::new(response.buffer_id)?;
 321
 322            this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
 323                .await
 324        })
 325    }
 326
 327    fn reload_buffers(
 328        &self,
 329        buffers: HashSet<Entity<Buffer>>,
 330        push_to_history: bool,
 331        cx: &mut Context<BufferStore>,
 332    ) -> Task<Result<ProjectTransaction>> {
 333        let request = self.upstream_client.request(proto::ReloadBuffers {
 334            project_id: self.project_id,
 335            buffer_ids: buffers
 336                .iter()
 337                .map(|buffer| buffer.read(cx).remote_id().to_proto())
 338                .collect(),
 339        });
 340
 341        cx.spawn(async move |this, cx| {
 342            let response = request.await?.transaction.context("missing transaction")?;
 343            this.update(cx, |this, cx| {
 344                this.deserialize_project_transaction(response, push_to_history, cx)
 345            })?
 346            .await
 347        })
 348    }
 349}
 350
 351impl LocalBufferStore {
 352    fn save_local_buffer(
 353        &self,
 354        buffer_handle: Entity<Buffer>,
 355        worktree: Entity<Worktree>,
 356        path: Arc<Path>,
 357        mut has_changed_file: bool,
 358        cx: &mut Context<BufferStore>,
 359    ) -> Task<Result<()>> {
 360        let buffer = buffer_handle.read(cx);
 361
 362        let text = buffer.as_rope().clone();
 363        let line_ending = buffer.line_ending();
 364        let version = buffer.version();
 365        let buffer_id = buffer.remote_id();
 366        let file = buffer.file().cloned();
 367        if file
 368            .as_ref()
 369            .is_some_and(|file| file.disk_state() == DiskState::New)
 370        {
 371            has_changed_file = true;
 372        }
 373
 374        let save = worktree.update(cx, |worktree, cx| {
 375            worktree.write_file(path.as_ref(), text, line_ending, cx)
 376        });
 377        drop(buffer);
 378
 379        cx.spawn(async move |this, cx| {
 380            let new_file = save.await?;
 381            let mtime = new_file.disk_state().mtime();
 382            this.update(cx, |this, cx| {
 383                if let Some((downstream_client, project_id)) = this.downstream_client.clone() {
 384                    if has_changed_file {
 385                        downstream_client
 386                            .send(proto::UpdateBufferFile {
 387                                project_id,
 388                                buffer_id: buffer_id.to_proto(),
 389                                file: Some(language::File::to_proto(&*new_file, cx)),
 390                            })
 391                            .log_err();
 392                    }
 393                    downstream_client
 394                        .send(proto::BufferSaved {
 395                            project_id,
 396                            buffer_id: buffer_id.to_proto(),
 397                            version: serialize_version(&version),
 398                            mtime: mtime.map(|time| time.into()),
 399                        })
 400                        .log_err();
 401                }
 402            })?;
 403            buffer_handle.update(cx, |buffer, cx| {
 404                if has_changed_file {
 405                    buffer.file_updated(new_file, cx);
 406                }
 407                buffer.did_save(version.clone(), mtime, cx);
 408            })
 409        })
 410    }
 411
 412    fn subscribe_to_worktree(
 413        &mut self,
 414        worktree: &Entity<Worktree>,
 415        cx: &mut Context<BufferStore>,
 416    ) {
 417        cx.subscribe(worktree, |this, worktree, event, cx| {
 418            if worktree.read(cx).is_local() {
 419                match event {
 420                    worktree::Event::UpdatedEntries(changes) => {
 421                        Self::local_worktree_entries_changed(this, &worktree, changes, cx);
 422                    }
 423                    _ => {}
 424                }
 425            }
 426        })
 427        .detach();
 428    }
 429
 430    fn local_worktree_entries_changed(
 431        this: &mut BufferStore,
 432        worktree_handle: &Entity<Worktree>,
 433        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 434        cx: &mut Context<BufferStore>,
 435    ) {
 436        let snapshot = worktree_handle.read(cx).snapshot();
 437        for (path, entry_id, _) in changes {
 438            Self::local_worktree_entry_changed(
 439                this,
 440                *entry_id,
 441                path,
 442                worktree_handle,
 443                &snapshot,
 444                cx,
 445            );
 446        }
 447    }
 448
 449    fn local_worktree_entry_changed(
 450        this: &mut BufferStore,
 451        entry_id: ProjectEntryId,
 452        path: &Arc<Path>,
 453        worktree: &Entity<worktree::Worktree>,
 454        snapshot: &worktree::Snapshot,
 455        cx: &mut Context<BufferStore>,
 456    ) -> Option<()> {
 457        let project_path = ProjectPath {
 458            worktree_id: snapshot.id(),
 459            path: path.clone(),
 460        };
 461
 462        let buffer_id = this
 463            .as_local_mut()
 464            .and_then(|local| local.local_buffer_ids_by_entry_id.get(&entry_id))
 465            .copied()
 466            .or_else(|| this.path_to_buffer_id.get(&project_path).copied())?;
 467
 468        let buffer = if let Some(buffer) = this.get(buffer_id) {
 469            Some(buffer)
 470        } else {
 471            this.opened_buffers.remove(&buffer_id);
 472            None
 473        };
 474
 475        let buffer = if let Some(buffer) = buffer {
 476            buffer
 477        } else {
 478            this.path_to_buffer_id.remove(&project_path);
 479            let this = this.as_local_mut()?;
 480            this.local_buffer_ids_by_entry_id.remove(&entry_id);
 481            return None;
 482        };
 483
 484        let events = buffer.update(cx, |buffer, cx| {
 485            let file = buffer.file()?;
 486            let old_file = File::from_dyn(Some(file))?;
 487            if old_file.worktree != *worktree {
 488                return None;
 489            }
 490
 491            let snapshot_entry = old_file
 492                .entry_id
 493                .and_then(|entry_id| snapshot.entry_for_id(entry_id))
 494                .or_else(|| snapshot.entry_for_path(old_file.path.as_ref()));
 495
 496            let new_file = if let Some(entry) = snapshot_entry {
 497                File {
 498                    disk_state: match entry.mtime {
 499                        Some(mtime) => DiskState::Present { mtime },
 500                        None => old_file.disk_state,
 501                    },
 502                    is_local: true,
 503                    entry_id: Some(entry.id),
 504                    path: entry.path.clone(),
 505                    worktree: worktree.clone(),
 506                    is_private: entry.is_private,
 507                }
 508            } else {
 509                File {
 510                    disk_state: DiskState::Deleted,
 511                    is_local: true,
 512                    entry_id: old_file.entry_id,
 513                    path: old_file.path.clone(),
 514                    worktree: worktree.clone(),
 515                    is_private: old_file.is_private,
 516                }
 517            };
 518
 519            if new_file == *old_file {
 520                return None;
 521            }
 522
 523            let mut events = Vec::new();
 524            if new_file.path != old_file.path {
 525                this.path_to_buffer_id.remove(&ProjectPath {
 526                    path: old_file.path.clone(),
 527                    worktree_id: old_file.worktree_id(cx),
 528                });
 529                this.path_to_buffer_id.insert(
 530                    ProjectPath {
 531                        worktree_id: new_file.worktree_id(cx),
 532                        path: new_file.path.clone(),
 533                    },
 534                    buffer_id,
 535                );
 536                events.push(BufferStoreEvent::BufferChangedFilePath {
 537                    buffer: cx.entity(),
 538                    old_file: buffer.file().cloned(),
 539                });
 540            }
 541            let local = this.as_local_mut()?;
 542            if new_file.entry_id != old_file.entry_id {
 543                if let Some(entry_id) = old_file.entry_id {
 544                    local.local_buffer_ids_by_entry_id.remove(&entry_id);
 545                }
 546                if let Some(entry_id) = new_file.entry_id {
 547                    local
 548                        .local_buffer_ids_by_entry_id
 549                        .insert(entry_id, buffer_id);
 550                }
 551            }
 552
 553            if let Some((client, project_id)) = &this.downstream_client {
 554                client
 555                    .send(proto::UpdateBufferFile {
 556                        project_id: *project_id,
 557                        buffer_id: buffer_id.to_proto(),
 558                        file: Some(new_file.to_proto(cx)),
 559                    })
 560                    .ok();
 561            }
 562
 563            buffer.file_updated(Arc::new(new_file), cx);
 564            Some(events)
 565        })?;
 566
 567        for event in events {
 568            cx.emit(event);
 569        }
 570
 571        None
 572    }
 573
 574    fn save_buffer(
 575        &self,
 576        buffer: Entity<Buffer>,
 577        cx: &mut Context<BufferStore>,
 578    ) -> Task<Result<()>> {
 579        let buffer_ref = buffer.read(cx);
 580        let Some(file) = File::from_dyn(buffer_ref.file()) else {
 581            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 582        };
 583        let worktree = file.worktree.clone();
 584        self.save_local_buffer(buffer, worktree, file.path.clone(), false, cx)
 585    }
 586
 587    fn save_buffer_as(
 588        &self,
 589        buffer: Entity<Buffer>,
 590        path: ProjectPath,
 591        cx: &mut Context<BufferStore>,
 592    ) -> Task<Result<()>> {
 593        let Some(worktree) = self
 594            .worktree_store
 595            .read(cx)
 596            .worktree_for_id(path.worktree_id, cx)
 597        else {
 598            return Task::ready(Err(anyhow!("no such worktree")));
 599        };
 600        self.save_local_buffer(buffer, worktree, path.path.clone(), true, cx)
 601    }
 602
 603    fn open_buffer(
 604        &self,
 605        path: Arc<Path>,
 606        worktree: Entity<Worktree>,
 607        cx: &mut Context<BufferStore>,
 608    ) -> Task<Result<Entity<Buffer>>> {
 609        let load_buffer = worktree.update(cx, |worktree, cx| {
 610            let load_file = worktree.load_file(path.as_ref(), cx);
 611            let entity_id = cx.reserve_entity();
 612            let buffer_id = BufferId::from(entity_id.as_non_zero_u64());
 613            cx.spawn(async move |_, cx| {
 614                let loaded = load_file.await?;
 615                let text_buffer = cx
 616                    .background_spawn(async move { text::Buffer::new(0, buffer_id, loaded.text) })
 617                    .await;
 618                cx.insert_entity(entity_id, |_| {
 619                    Buffer::build(text_buffer, Some(loaded.file), Capability::ReadWrite)
 620                })
 621            })
 622        });
 623
 624        cx.spawn(async move |this, cx| {
 625            let buffer = match load_buffer.await {
 626                Ok(buffer) => Ok(buffer),
 627                Err(error) if is_not_found_error(&error) => cx.new(|cx| {
 628                    let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
 629                    let text_buffer = text::Buffer::new(0, buffer_id, "");
 630                    Buffer::build(
 631                        text_buffer,
 632                        Some(Arc::new(File {
 633                            worktree,
 634                            path,
 635                            disk_state: DiskState::New,
 636                            entry_id: None,
 637                            is_local: true,
 638                            is_private: false,
 639                        })),
 640                        Capability::ReadWrite,
 641                    )
 642                }),
 643                Err(e) => Err(e),
 644            }?;
 645            this.update(cx, |this, cx| {
 646                this.add_buffer(buffer.clone(), cx)?;
 647                let buffer_id = buffer.read(cx).remote_id();
 648                if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 649                    this.path_to_buffer_id.insert(
 650                        ProjectPath {
 651                            worktree_id: file.worktree_id(cx),
 652                            path: file.path.clone(),
 653                        },
 654                        buffer_id,
 655                    );
 656                    let this = this.as_local_mut().unwrap();
 657                    if let Some(entry_id) = file.entry_id {
 658                        this.local_buffer_ids_by_entry_id
 659                            .insert(entry_id, buffer_id);
 660                    }
 661                }
 662
 663                anyhow::Ok(())
 664            })??;
 665
 666            Ok(buffer)
 667        })
 668    }
 669
 670    fn create_buffer(&self, cx: &mut Context<BufferStore>) -> Task<Result<Entity<Buffer>>> {
 671        cx.spawn(async move |buffer_store, cx| {
 672            let buffer =
 673                cx.new(|cx| Buffer::local("", cx).with_language(language::PLAIN_TEXT.clone(), cx))?;
 674            buffer_store.update(cx, |buffer_store, cx| {
 675                buffer_store.add_buffer(buffer.clone(), cx).log_err();
 676            })?;
 677            Ok(buffer)
 678        })
 679    }
 680
 681    fn reload_buffers(
 682        &self,
 683        buffers: HashSet<Entity<Buffer>>,
 684        push_to_history: bool,
 685        cx: &mut Context<BufferStore>,
 686    ) -> Task<Result<ProjectTransaction>> {
 687        cx.spawn(async move |_, cx| {
 688            let mut project_transaction = ProjectTransaction::default();
 689            for buffer in buffers {
 690                let transaction = buffer.update(cx, |buffer, cx| buffer.reload(cx))?.await?;
 691                buffer.update(cx, |buffer, cx| {
 692                    if let Some(transaction) = transaction {
 693                        if !push_to_history {
 694                            buffer.forget_transaction(transaction.id);
 695                        }
 696                        project_transaction.0.insert(cx.entity(), transaction);
 697                    }
 698                })?;
 699            }
 700
 701            Ok(project_transaction)
 702        })
 703    }
 704}
 705
 706impl BufferStore {
 707    pub fn init(client: &AnyProtoClient) {
 708        client.add_entity_message_handler(Self::handle_buffer_reloaded);
 709        client.add_entity_message_handler(Self::handle_buffer_saved);
 710        client.add_entity_message_handler(Self::handle_update_buffer_file);
 711        client.add_entity_request_handler(Self::handle_save_buffer);
 712        client.add_entity_request_handler(Self::handle_reload_buffers);
 713    }
 714
 715    /// Creates a buffer store, optionally retaining its buffers.
 716    pub fn local(worktree_store: Entity<WorktreeStore>, cx: &mut Context<Self>) -> Self {
 717        Self {
 718            state: BufferStoreState::Local(LocalBufferStore {
 719                local_buffer_ids_by_entry_id: Default::default(),
 720                worktree_store: worktree_store.clone(),
 721                _subscription: cx.subscribe(&worktree_store, |this, _, event, cx| {
 722                    if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
 723                        let this = this.as_local_mut().unwrap();
 724                        this.subscribe_to_worktree(worktree, cx);
 725                    }
 726                }),
 727            }),
 728            downstream_client: None,
 729            opened_buffers: Default::default(),
 730            path_to_buffer_id: Default::default(),
 731            shared_buffers: Default::default(),
 732            loading_buffers: Default::default(),
 733            non_searchable_buffers: Default::default(),
 734            worktree_store,
 735        }
 736    }
 737
 738    pub fn remote(
 739        worktree_store: Entity<WorktreeStore>,
 740        upstream_client: AnyProtoClient,
 741        remote_id: u64,
 742        _cx: &mut Context<Self>,
 743    ) -> Self {
 744        Self {
 745            state: BufferStoreState::Remote(RemoteBufferStore {
 746                shared_with_me: Default::default(),
 747                loading_remote_buffers_by_id: Default::default(),
 748                remote_buffer_listeners: Default::default(),
 749                project_id: remote_id,
 750                upstream_client,
 751                worktree_store: worktree_store.clone(),
 752            }),
 753            downstream_client: None,
 754            opened_buffers: Default::default(),
 755            path_to_buffer_id: Default::default(),
 756            loading_buffers: Default::default(),
 757            shared_buffers: Default::default(),
 758            non_searchable_buffers: Default::default(),
 759            worktree_store,
 760        }
 761    }
 762
 763    fn as_local_mut(&mut self) -> Option<&mut LocalBufferStore> {
 764        match &mut self.state {
 765            BufferStoreState::Local(state) => Some(state),
 766            _ => None,
 767        }
 768    }
 769
 770    fn as_remote_mut(&mut self) -> Option<&mut RemoteBufferStore> {
 771        match &mut self.state {
 772            BufferStoreState::Remote(state) => Some(state),
 773            _ => None,
 774        }
 775    }
 776
 777    fn as_remote(&self) -> Option<&RemoteBufferStore> {
 778        match &self.state {
 779            BufferStoreState::Remote(state) => Some(state),
 780            _ => None,
 781        }
 782    }
 783
 784    pub fn open_buffer(
 785        &mut self,
 786        project_path: ProjectPath,
 787        cx: &mut Context<Self>,
 788    ) -> Task<Result<Entity<Buffer>>> {
 789        if let Some(buffer) = self.get_by_path(&project_path) {
 790            cx.emit(BufferStoreEvent::BufferOpened {
 791                buffer: buffer.clone(),
 792                project_path,
 793            });
 794
 795            return Task::ready(Ok(buffer));
 796        }
 797
 798        let task = match self.loading_buffers.entry(project_path.clone()) {
 799            hash_map::Entry::Occupied(e) => e.get().clone(),
 800            hash_map::Entry::Vacant(entry) => {
 801                let path = project_path.path.clone();
 802                let Some(worktree) = self
 803                    .worktree_store
 804                    .read(cx)
 805                    .worktree_for_id(project_path.worktree_id, cx)
 806                else {
 807                    return Task::ready(Err(anyhow!("no such worktree")));
 808                };
 809                let load_buffer = match &self.state {
 810                    BufferStoreState::Local(this) => this.open_buffer(path, worktree, cx),
 811                    BufferStoreState::Remote(this) => this.open_buffer(path, worktree, cx),
 812                };
 813
 814                entry
 815                    .insert(
 816                        cx.spawn(async move |this, cx| {
 817                            let load_result = load_buffer.await;
 818                            this.update(cx, |this, cx| {
 819                                // Record the fact that the buffer is no longer loading.
 820                                this.loading_buffers.remove(&project_path);
 821
 822                                let buffer = load_result.map_err(Arc::new)?;
 823                                cx.emit(BufferStoreEvent::BufferOpened {
 824                                    buffer: buffer.clone(),
 825                                    project_path,
 826                                });
 827
 828                                Ok(buffer)
 829                            })?
 830                        })
 831                        .shared(),
 832                    )
 833                    .clone()
 834            }
 835        };
 836
 837        cx.background_spawn(async move { task.await.map_err(|e| anyhow!("{e}")) })
 838    }
 839
 840    pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
 841        match &self.state {
 842            BufferStoreState::Local(this) => this.create_buffer(cx),
 843            BufferStoreState::Remote(this) => this.create_buffer(cx),
 844        }
 845    }
 846
 847    pub fn save_buffer(
 848        &mut self,
 849        buffer: Entity<Buffer>,
 850        cx: &mut Context<Self>,
 851    ) -> Task<Result<()>> {
 852        match &mut self.state {
 853            BufferStoreState::Local(this) => this.save_buffer(buffer, cx),
 854            BufferStoreState::Remote(this) => this.save_remote_buffer(buffer.clone(), None, cx),
 855        }
 856    }
 857
 858    pub fn save_buffer_as(
 859        &mut self,
 860        buffer: Entity<Buffer>,
 861        path: ProjectPath,
 862        cx: &mut Context<Self>,
 863    ) -> Task<Result<()>> {
 864        let old_file = buffer.read(cx).file().cloned();
 865        let task = match &self.state {
 866            BufferStoreState::Local(this) => this.save_buffer_as(buffer.clone(), path, cx),
 867            BufferStoreState::Remote(this) => {
 868                this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
 869            }
 870        };
 871        cx.spawn(async move |this, cx| {
 872            task.await?;
 873            this.update(cx, |_, cx| {
 874                cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
 875            })
 876        })
 877    }
 878
 879    fn add_buffer(&mut self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
 880        let buffer = buffer_entity.read(cx);
 881        let remote_id = buffer.remote_id();
 882        let path = File::from_dyn(buffer.file()).map(|file| ProjectPath {
 883            path: file.path.clone(),
 884            worktree_id: file.worktree_id(cx),
 885        });
 886        let is_remote = buffer.replica_id() != 0;
 887        let open_buffer = OpenBuffer::Complete {
 888            buffer: buffer_entity.downgrade(),
 889        };
 890
 891        let handle = cx.entity().downgrade();
 892        buffer_entity.update(cx, move |_, cx| {
 893            cx.on_release(move |buffer, cx| {
 894                handle
 895                    .update(cx, |_, cx| {
 896                        cx.emit(BufferStoreEvent::BufferDropped(buffer.remote_id()))
 897                    })
 898                    .ok();
 899            })
 900            .detach()
 901        });
 902        let _expect_path_to_exist;
 903        match self.opened_buffers.entry(remote_id) {
 904            hash_map::Entry::Vacant(entry) => {
 905                entry.insert(open_buffer);
 906                _expect_path_to_exist = false;
 907            }
 908            hash_map::Entry::Occupied(mut entry) => {
 909                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 910                    buffer_entity.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx));
 911                } else if entry.get().upgrade().is_some() {
 912                    if is_remote {
 913                        return Ok(());
 914                    } else {
 915                        debug_panic!("buffer {remote_id} was already registered");
 916                        anyhow::bail!("buffer {remote_id} was already registered");
 917                    }
 918                }
 919                entry.insert(open_buffer);
 920                _expect_path_to_exist = true;
 921            }
 922        }
 923
 924        if let Some(path) = path {
 925            self.path_to_buffer_id.insert(path, remote_id);
 926        }
 927
 928        drop(buffer);
 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) -> 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            .with_context(|| format!("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 self.non_searchable_buffers.contains(&buffer.remote_id()) {
1070                continue;
1071            } else if let Some(entry_id) = buffer.entry_id(cx) {
1072                open_buffers.insert(entry_id);
1073            } else {
1074                limit = limit.saturating_sub(1);
1075                unnamed_buffers.push(handle)
1076            };
1077        }
1078
1079        const MAX_CONCURRENT_BUFFER_OPENS: usize = 64;
1080        let project_paths_rx = self
1081            .worktree_store
1082            .update(cx, |worktree_store, cx| {
1083                worktree_store.find_search_candidates(query.clone(), limit, open_buffers, fs, cx)
1084            })
1085            .chunks(MAX_CONCURRENT_BUFFER_OPENS);
1086
1087        cx.spawn(async move |this, cx| {
1088            for buffer in unnamed_buffers {
1089                tx.send(buffer).await.ok();
1090            }
1091
1092            let mut project_paths_rx = pin!(project_paths_rx);
1093            while let Some(project_paths) = project_paths_rx.next().await {
1094                let buffers = this.update(cx, |this, cx| {
1095                    project_paths
1096                        .into_iter()
1097                        .map(|project_path| this.open_buffer(project_path, cx))
1098                        .collect::<Vec<_>>()
1099                })?;
1100                for buffer_task in buffers {
1101                    if let Some(buffer) = buffer_task.await.log_err() {
1102                        if tx.send(buffer).await.is_err() {
1103                            return anyhow::Ok(());
1104                        }
1105                    }
1106                }
1107            }
1108            anyhow::Ok(())
1109        })
1110        .detach();
1111        rx
1112    }
1113
1114    fn on_buffer_event(
1115        &mut self,
1116        buffer: Entity<Buffer>,
1117        event: &BufferEvent,
1118        cx: &mut Context<Self>,
1119    ) {
1120        match event {
1121            BufferEvent::FileHandleChanged => {
1122                self.buffer_changed_file(buffer, cx);
1123            }
1124            BufferEvent::Reloaded => {
1125                let Some((downstream_client, project_id)) = self.downstream_client.as_ref() else {
1126                    return;
1127                };
1128                let buffer = buffer.read(cx);
1129                downstream_client
1130                    .send(proto::BufferReloaded {
1131                        project_id: *project_id,
1132                        buffer_id: buffer.remote_id().to_proto(),
1133                        version: serialize_version(&buffer.version()),
1134                        mtime: buffer.saved_mtime().map(|t| t.into()),
1135                        line_ending: serialize_line_ending(buffer.line_ending()) as i32,
1136                    })
1137                    .log_err();
1138            }
1139            BufferEvent::LanguageChanged => {}
1140            _ => {}
1141        }
1142    }
1143
1144    pub async fn handle_update_buffer(
1145        this: Entity<Self>,
1146        envelope: TypedEnvelope<proto::UpdateBuffer>,
1147        mut cx: AsyncApp,
1148    ) -> Result<proto::Ack> {
1149        let payload = envelope.payload.clone();
1150        let buffer_id = BufferId::new(payload.buffer_id)?;
1151        let ops = payload
1152            .operations
1153            .into_iter()
1154            .map(language::proto::deserialize_operation)
1155            .collect::<Result<Vec<_>, _>>()?;
1156        this.update(&mut cx, |this, cx| {
1157            match this.opened_buffers.entry(buffer_id) {
1158                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
1159                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
1160                    OpenBuffer::Complete { buffer, .. } => {
1161                        if let Some(buffer) = buffer.upgrade() {
1162                            buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx));
1163                        }
1164                    }
1165                },
1166                hash_map::Entry::Vacant(e) => {
1167                    e.insert(OpenBuffer::Operations(ops));
1168                }
1169            }
1170            Ok(proto::Ack {})
1171        })?
1172    }
1173
1174    pub fn register_shared_lsp_handle(
1175        &mut self,
1176        peer_id: proto::PeerId,
1177        buffer_id: BufferId,
1178        handle: OpenLspBufferHandle,
1179    ) {
1180        if let Some(shared_buffers) = self.shared_buffers.get_mut(&peer_id) {
1181            if let Some(buffer) = shared_buffers.get_mut(&buffer_id) {
1182                buffer.lsp_handle = Some(handle);
1183                return;
1184            }
1185        }
1186        debug_panic!("tried to register shared lsp handle, but buffer was not shared")
1187    }
1188
1189    pub fn handle_synchronize_buffers(
1190        &mut self,
1191        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
1192        cx: &mut Context<Self>,
1193        client: Arc<Client>,
1194    ) -> Result<proto::SynchronizeBuffersResponse> {
1195        let project_id = envelope.payload.project_id;
1196        let mut response = proto::SynchronizeBuffersResponse {
1197            buffers: Default::default(),
1198        };
1199        let Some(guest_id) = envelope.original_sender_id else {
1200            anyhow::bail!("missing original_sender_id on SynchronizeBuffers request");
1201        };
1202
1203        self.shared_buffers.entry(guest_id).or_default().clear();
1204        for buffer in envelope.payload.buffers {
1205            let buffer_id = BufferId::new(buffer.id)?;
1206            let remote_version = language::proto::deserialize_version(&buffer.version);
1207            if let Some(buffer) = self.get(buffer_id) {
1208                self.shared_buffers
1209                    .entry(guest_id)
1210                    .or_default()
1211                    .entry(buffer_id)
1212                    .or_insert_with(|| SharedBuffer {
1213                        buffer: buffer.clone(),
1214                        lsp_handle: None,
1215                    });
1216
1217                let buffer = buffer.read(cx);
1218                response.buffers.push(proto::BufferVersion {
1219                    id: buffer_id.into(),
1220                    version: language::proto::serialize_version(&buffer.version),
1221                });
1222
1223                let operations = buffer.serialize_ops(Some(remote_version), cx);
1224                let client = client.clone();
1225                if let Some(file) = buffer.file() {
1226                    client
1227                        .send(proto::UpdateBufferFile {
1228                            project_id,
1229                            buffer_id: buffer_id.into(),
1230                            file: Some(file.to_proto(cx)),
1231                        })
1232                        .log_err();
1233                }
1234
1235                // TODO(max): do something
1236                // client
1237                //     .send(proto::UpdateStagedText {
1238                //         project_id,
1239                //         buffer_id: buffer_id.into(),
1240                //         diff_base: buffer.diff_base().map(ToString::to_string),
1241                //     })
1242                //     .log_err();
1243
1244                client
1245                    .send(proto::BufferReloaded {
1246                        project_id,
1247                        buffer_id: buffer_id.into(),
1248                        version: language::proto::serialize_version(buffer.saved_version()),
1249                        mtime: buffer.saved_mtime().map(|time| time.into()),
1250                        line_ending: language::proto::serialize_line_ending(buffer.line_ending())
1251                            as i32,
1252                    })
1253                    .log_err();
1254
1255                cx.background_spawn(
1256                    async move {
1257                        let operations = operations.await;
1258                        for chunk in split_operations(operations) {
1259                            client
1260                                .request(proto::UpdateBuffer {
1261                                    project_id,
1262                                    buffer_id: buffer_id.into(),
1263                                    operations: chunk,
1264                                })
1265                                .await?;
1266                        }
1267                        anyhow::Ok(())
1268                    }
1269                    .log_err(),
1270                )
1271                .detach();
1272            }
1273        }
1274        Ok(response)
1275    }
1276
1277    pub fn handle_create_buffer_for_peer(
1278        &mut self,
1279        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
1280        replica_id: u16,
1281        capability: Capability,
1282        cx: &mut Context<Self>,
1283    ) -> Result<()> {
1284        let remote = self
1285            .as_remote_mut()
1286            .context("buffer store is not a remote")?;
1287
1288        if let Some(buffer) =
1289            remote.handle_create_buffer_for_peer(envelope, replica_id, capability, cx)?
1290        {
1291            self.add_buffer(buffer, cx)?;
1292        }
1293
1294        Ok(())
1295    }
1296
1297    pub async fn handle_update_buffer_file(
1298        this: Entity<Self>,
1299        envelope: TypedEnvelope<proto::UpdateBufferFile>,
1300        mut cx: AsyncApp,
1301    ) -> Result<()> {
1302        let buffer_id = envelope.payload.buffer_id;
1303        let buffer_id = BufferId::new(buffer_id)?;
1304
1305        this.update(&mut cx, |this, cx| {
1306            let payload = envelope.payload.clone();
1307            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1308                let file = payload.file.context("invalid file")?;
1309                let worktree = this
1310                    .worktree_store
1311                    .read(cx)
1312                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
1313                    .context("no such worktree")?;
1314                let file = File::from_proto(file, worktree, cx)?;
1315                let old_file = buffer.update(cx, |buffer, cx| {
1316                    let old_file = buffer.file().cloned();
1317                    let new_path = file.path.clone();
1318
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.read_with(&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.read_with(&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.read_with(&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                .context("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            anyhow::Ok(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.read_with(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        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1610            self.path_to_buffer_id.insert(
1611                ProjectPath {
1612                    worktree_id: file.worktree_id(cx),
1613                    path: file.path.clone(),
1614                },
1615                buffer_id,
1616            );
1617            let this = self
1618                .as_local_mut()
1619                .expect("local-only method called in a non-local context");
1620            if let Some(entry_id) = file.entry_id {
1621                this.local_buffer_ids_by_entry_id
1622                    .insert(entry_id, buffer_id);
1623            }
1624        }
1625        buffer
1626    }
1627
1628    pub fn deserialize_project_transaction(
1629        &mut self,
1630        message: proto::ProjectTransaction,
1631        push_to_history: bool,
1632        cx: &mut Context<Self>,
1633    ) -> Task<Result<ProjectTransaction>> {
1634        if let Some(this) = self.as_remote_mut() {
1635            this.deserialize_project_transaction(message, push_to_history, cx)
1636        } else {
1637            debug_panic!("not a remote buffer store");
1638            Task::ready(Err(anyhow!("not a remote buffer store")))
1639        }
1640    }
1641
1642    pub fn wait_for_remote_buffer(
1643        &mut self,
1644        id: BufferId,
1645        cx: &mut Context<BufferStore>,
1646    ) -> Task<Result<Entity<Buffer>>> {
1647        if let Some(this) = self.as_remote_mut() {
1648            this.wait_for_remote_buffer(id, cx)
1649        } else {
1650            debug_panic!("not a remote buffer store");
1651            Task::ready(Err(anyhow!("not a remote buffer store")))
1652        }
1653    }
1654
1655    pub fn serialize_project_transaction_for_peer(
1656        &mut self,
1657        project_transaction: ProjectTransaction,
1658        peer_id: proto::PeerId,
1659        cx: &mut Context<Self>,
1660    ) -> proto::ProjectTransaction {
1661        let mut serialized_transaction = proto::ProjectTransaction {
1662            buffer_ids: Default::default(),
1663            transactions: Default::default(),
1664        };
1665        for (buffer, transaction) in project_transaction.0 {
1666            self.create_buffer_for_peer(&buffer, peer_id, cx)
1667                .detach_and_log_err(cx);
1668            serialized_transaction
1669                .buffer_ids
1670                .push(buffer.read(cx).remote_id().into());
1671            serialized_transaction
1672                .transactions
1673                .push(language::proto::serialize_transaction(&transaction));
1674        }
1675        serialized_transaction
1676    }
1677
1678    pub(crate) fn mark_buffer_as_non_searchable(&mut self, buffer_id: BufferId) {
1679        self.non_searchable_buffers.insert(buffer_id);
1680    }
1681}
1682
1683impl OpenBuffer {
1684    fn upgrade(&self) -> Option<Entity<Buffer>> {
1685        match self {
1686            OpenBuffer::Complete { buffer, .. } => buffer.upgrade(),
1687            OpenBuffer::Operations(_) => None,
1688        }
1689    }
1690}
1691
1692fn is_not_found_error(error: &anyhow::Error) -> bool {
1693    error
1694        .root_cause()
1695        .downcast_ref::<io::Error>()
1696        .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
1697}