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                    })?;
 279                }
 280            }
 281
 282            Ok(project_transaction)
 283        })
 284    }
 285
 286    fn open_buffer(
 287        &self,
 288        path: Arc<Path>,
 289        worktree: Entity<Worktree>,
 290        cx: &mut Context<BufferStore>,
 291    ) -> Task<Result<Entity<Buffer>>> {
 292        let worktree_id = worktree.read(cx).id().to_proto();
 293        let project_id = self.project_id;
 294        let client = self.upstream_client.clone();
 295        cx.spawn(async move |this, cx| {
 296            let response = client
 297                .request(proto::OpenBufferByPath {
 298                    project_id,
 299                    worktree_id,
 300                    path: path.to_proto(),
 301                })
 302                .await?;
 303            let buffer_id = BufferId::new(response.buffer_id)?;
 304
 305            let buffer = this
 306                .update(cx, {
 307                    |this, cx| this.wait_for_remote_buffer(buffer_id, cx)
 308                })?
 309                .await?;
 310
 311            Ok(buffer)
 312        })
 313    }
 314
 315    fn create_buffer(&self, cx: &mut Context<BufferStore>) -> Task<Result<Entity<Buffer>>> {
 316        let create = self.upstream_client.request(proto::OpenNewBuffer {
 317            project_id: self.project_id,
 318        });
 319        cx.spawn(async move |this, cx| {
 320            let response = create.await?;
 321            let buffer_id = BufferId::new(response.buffer_id)?;
 322
 323            this.update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
 324                .await
 325        })
 326    }
 327
 328    fn reload_buffers(
 329        &self,
 330        buffers: HashSet<Entity<Buffer>>,
 331        push_to_history: bool,
 332        cx: &mut Context<BufferStore>,
 333    ) -> Task<Result<ProjectTransaction>> {
 334        let request = self.upstream_client.request(proto::ReloadBuffers {
 335            project_id: self.project_id,
 336            buffer_ids: buffers
 337                .iter()
 338                .map(|buffer| buffer.read(cx).remote_id().to_proto())
 339                .collect(),
 340        });
 341
 342        cx.spawn(async move |this, cx| {
 343            let response = request
 344                .await?
 345                .transaction
 346                .ok_or_else(|| anyhow!("missing transaction"))?;
 347            this.update(cx, |this, cx| {
 348                this.deserialize_project_transaction(response, push_to_history, cx)
 349            })?
 350            .await
 351        })
 352    }
 353}
 354
 355impl LocalBufferStore {
 356    fn save_local_buffer(
 357        &self,
 358        buffer_handle: Entity<Buffer>,
 359        worktree: Entity<Worktree>,
 360        path: Arc<Path>,
 361        mut has_changed_file: bool,
 362        cx: &mut Context<BufferStore>,
 363    ) -> Task<Result<()>> {
 364        let buffer = buffer_handle.read(cx);
 365
 366        let text = buffer.as_rope().clone();
 367        let line_ending = buffer.line_ending();
 368        let version = buffer.version();
 369        let buffer_id = buffer.remote_id();
 370        if buffer
 371            .file()
 372            .is_some_and(|file| file.disk_state() == DiskState::New)
 373        {
 374            has_changed_file = true;
 375        }
 376
 377        let save = worktree.update(cx, |worktree, cx| {
 378            worktree.write_file(path.as_ref(), text, line_ending, cx)
 379        });
 380
 381        cx.spawn(async move |this, cx| {
 382            let new_file = save.await?;
 383            let mtime = new_file.disk_state().mtime();
 384            this.update(cx, |this, cx| {
 385                if let Some((downstream_client, project_id)) = this.downstream_client.clone() {
 386                    if has_changed_file {
 387                        downstream_client
 388                            .send(proto::UpdateBufferFile {
 389                                project_id,
 390                                buffer_id: buffer_id.to_proto(),
 391                                file: Some(language::File::to_proto(&*new_file, cx)),
 392                            })
 393                            .log_err();
 394                    }
 395                    downstream_client
 396                        .send(proto::BufferSaved {
 397                            project_id,
 398                            buffer_id: buffer_id.to_proto(),
 399                            version: serialize_version(&version),
 400                            mtime: mtime.map(|time| time.into()),
 401                        })
 402                        .log_err();
 403                }
 404            })?;
 405            buffer_handle.update(cx, |buffer, cx| {
 406                if has_changed_file {
 407                    buffer.file_updated(new_file, cx);
 408                }
 409                buffer.did_save(version.clone(), mtime, cx);
 410            })
 411        })
 412    }
 413
 414    fn subscribe_to_worktree(
 415        &mut self,
 416        worktree: &Entity<Worktree>,
 417        cx: &mut Context<BufferStore>,
 418    ) {
 419        cx.subscribe(worktree, |this, worktree, event, cx| {
 420            if worktree.read(cx).is_local() {
 421                match event {
 422                    worktree::Event::UpdatedEntries(changes) => {
 423                        Self::local_worktree_entries_changed(this, &worktree, changes, cx);
 424                    }
 425                    _ => {}
 426                }
 427            }
 428        })
 429        .detach();
 430    }
 431
 432    fn local_worktree_entries_changed(
 433        this: &mut BufferStore,
 434        worktree_handle: &Entity<Worktree>,
 435        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 436        cx: &mut Context<BufferStore>,
 437    ) {
 438        let snapshot = worktree_handle.read(cx).snapshot();
 439        for (path, entry_id, _) in changes {
 440            Self::local_worktree_entry_changed(
 441                this,
 442                *entry_id,
 443                path,
 444                worktree_handle,
 445                &snapshot,
 446                cx,
 447            );
 448        }
 449    }
 450
 451    fn local_worktree_entry_changed(
 452        this: &mut BufferStore,
 453        entry_id: ProjectEntryId,
 454        path: &Arc<Path>,
 455        worktree: &Entity<worktree::Worktree>,
 456        snapshot: &worktree::Snapshot,
 457        cx: &mut Context<BufferStore>,
 458    ) -> Option<()> {
 459        let project_path = ProjectPath {
 460            worktree_id: snapshot.id(),
 461            path: path.clone(),
 462        };
 463
 464        let buffer_id = {
 465            let local = this.as_local_mut()?;
 466            match local.local_buffer_ids_by_entry_id.get(&entry_id) {
 467                Some(&buffer_id) => buffer_id,
 468                None => local.local_buffer_ids_by_path.get(&project_path).copied()?,
 469            }
 470        };
 471
 472        let buffer = if let Some(buffer) = this.get(buffer_id) {
 473            Some(buffer)
 474        } else {
 475            this.opened_buffers.remove(&buffer_id);
 476            None
 477        };
 478
 479        let buffer = if let Some(buffer) = buffer {
 480            buffer
 481        } else {
 482            let this = this.as_local_mut()?;
 483            this.local_buffer_ids_by_path.remove(&project_path);
 484            this.local_buffer_ids_by_entry_id.remove(&entry_id);
 485            return None;
 486        };
 487
 488        let events = buffer.update(cx, |buffer, cx| {
 489            let local = this.as_local_mut()?;
 490            let file = buffer.file()?;
 491            let old_file = File::from_dyn(Some(file))?;
 492            if old_file.worktree != *worktree {
 493                return None;
 494            }
 495
 496            let snapshot_entry = old_file
 497                .entry_id
 498                .and_then(|entry_id| snapshot.entry_for_id(entry_id))
 499                .or_else(|| snapshot.entry_for_path(old_file.path.as_ref()));
 500
 501            let new_file = if let Some(entry) = snapshot_entry {
 502                File {
 503                    disk_state: match entry.mtime {
 504                        Some(mtime) => DiskState::Present { mtime },
 505                        None => old_file.disk_state,
 506                    },
 507                    is_local: true,
 508                    entry_id: Some(entry.id),
 509                    path: entry.path.clone(),
 510                    worktree: worktree.clone(),
 511                    is_private: entry.is_private,
 512                }
 513            } else {
 514                File {
 515                    disk_state: DiskState::Deleted,
 516                    is_local: true,
 517                    entry_id: old_file.entry_id,
 518                    path: old_file.path.clone(),
 519                    worktree: worktree.clone(),
 520                    is_private: old_file.is_private,
 521                }
 522            };
 523
 524            if new_file == *old_file {
 525                return None;
 526            }
 527
 528            let mut events = Vec::new();
 529            if new_file.path != old_file.path {
 530                local.local_buffer_ids_by_path.remove(&ProjectPath {
 531                    path: old_file.path.clone(),
 532                    worktree_id: old_file.worktree_id(cx),
 533                });
 534                local.local_buffer_ids_by_path.insert(
 535                    ProjectPath {
 536                        worktree_id: new_file.worktree_id(cx),
 537                        path: new_file.path.clone(),
 538                    },
 539                    buffer_id,
 540                );
 541                events.push(BufferStoreEvent::BufferChangedFilePath {
 542                    buffer: cx.entity(),
 543                    old_file: buffer.file().cloned(),
 544                });
 545            }
 546
 547            if new_file.entry_id != old_file.entry_id {
 548                if let Some(entry_id) = old_file.entry_id {
 549                    local.local_buffer_ids_by_entry_id.remove(&entry_id);
 550                }
 551                if let Some(entry_id) = new_file.entry_id {
 552                    local
 553                        .local_buffer_ids_by_entry_id
 554                        .insert(entry_id, buffer_id);
 555                }
 556            }
 557
 558            if let Some((client, project_id)) = &this.downstream_client {
 559                client
 560                    .send(proto::UpdateBufferFile {
 561                        project_id: *project_id,
 562                        buffer_id: buffer_id.to_proto(),
 563                        file: Some(new_file.to_proto(cx)),
 564                    })
 565                    .ok();
 566            }
 567
 568            buffer.file_updated(Arc::new(new_file), cx);
 569            Some(events)
 570        })?;
 571
 572        for event in events {
 573            cx.emit(event);
 574        }
 575
 576        None
 577    }
 578
 579    fn buffer_changed_file(&mut self, buffer: Entity<Buffer>, cx: &mut App) -> Option<()> {
 580        let file = File::from_dyn(buffer.read(cx).file())?;
 581
 582        let remote_id = buffer.read(cx).remote_id();
 583        if let Some(entry_id) = file.entry_id {
 584            match self.local_buffer_ids_by_entry_id.get(&entry_id) {
 585                Some(_) => {
 586                    return None;
 587                }
 588                None => {
 589                    self.local_buffer_ids_by_entry_id
 590                        .insert(entry_id, remote_id);
 591                }
 592            }
 593        };
 594        self.local_buffer_ids_by_path.insert(
 595            ProjectPath {
 596                worktree_id: file.worktree_id(cx),
 597                path: file.path.clone(),
 598            },
 599            remote_id,
 600        );
 601
 602        Some(())
 603    }
 604
 605    fn save_buffer(
 606        &self,
 607        buffer: Entity<Buffer>,
 608        cx: &mut Context<BufferStore>,
 609    ) -> Task<Result<()>> {
 610        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 611            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 612        };
 613        let worktree = file.worktree.clone();
 614        self.save_local_buffer(buffer, worktree, file.path.clone(), false, cx)
 615    }
 616
 617    fn save_buffer_as(
 618        &self,
 619        buffer: Entity<Buffer>,
 620        path: ProjectPath,
 621        cx: &mut Context<BufferStore>,
 622    ) -> Task<Result<()>> {
 623        let Some(worktree) = self
 624            .worktree_store
 625            .read(cx)
 626            .worktree_for_id(path.worktree_id, cx)
 627        else {
 628            return Task::ready(Err(anyhow!("no such worktree")));
 629        };
 630        self.save_local_buffer(buffer, worktree, path.path.clone(), true, cx)
 631    }
 632
 633    fn open_buffer(
 634        &self,
 635        path: Arc<Path>,
 636        worktree: Entity<Worktree>,
 637        cx: &mut Context<BufferStore>,
 638    ) -> Task<Result<Entity<Buffer>>> {
 639        let load_buffer = worktree.update(cx, |worktree, cx| {
 640            let load_file = worktree.load_file(path.as_ref(), cx);
 641            let reservation = cx.reserve_entity();
 642            let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
 643            cx.spawn(async move |_, cx| {
 644                let loaded = load_file.await?;
 645                let text_buffer = cx
 646                    .background_spawn(async move { text::Buffer::new(0, buffer_id, loaded.text) })
 647                    .await;
 648                cx.insert_entity(reservation, |_| {
 649                    Buffer::build(text_buffer, Some(loaded.file), Capability::ReadWrite)
 650                })
 651            })
 652        });
 653
 654        cx.spawn(async move |this, cx| {
 655            let buffer = match load_buffer.await {
 656                Ok(buffer) => Ok(buffer),
 657                Err(error) if is_not_found_error(&error) => cx.new(|cx| {
 658                    let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
 659                    let text_buffer = text::Buffer::new(0, buffer_id, "".into());
 660                    Buffer::build(
 661                        text_buffer,
 662                        Some(Arc::new(File {
 663                            worktree,
 664                            path,
 665                            disk_state: DiskState::New,
 666                            entry_id: None,
 667                            is_local: true,
 668                            is_private: false,
 669                        })),
 670                        Capability::ReadWrite,
 671                    )
 672                }),
 673                Err(e) => Err(e),
 674            }?;
 675            this.update(cx, |this, cx| {
 676                this.add_buffer(buffer.clone(), cx)?;
 677                let buffer_id = buffer.read(cx).remote_id();
 678                if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 679                    let this = this.as_local_mut().unwrap();
 680                    this.local_buffer_ids_by_path.insert(
 681                        ProjectPath {
 682                            worktree_id: file.worktree_id(cx),
 683                            path: file.path.clone(),
 684                        },
 685                        buffer_id,
 686                    );
 687
 688                    if let Some(entry_id) = file.entry_id {
 689                        this.local_buffer_ids_by_entry_id
 690                            .insert(entry_id, buffer_id);
 691                    }
 692                }
 693
 694                anyhow::Ok(())
 695            })??;
 696
 697            Ok(buffer)
 698        })
 699    }
 700
 701    fn create_buffer(&self, cx: &mut Context<BufferStore>) -> Task<Result<Entity<Buffer>>> {
 702        cx.spawn(async move |buffer_store, cx| {
 703            let buffer =
 704                cx.new(|cx| Buffer::local("", cx).with_language(language::PLAIN_TEXT.clone(), cx))?;
 705            buffer_store.update(cx, |buffer_store, cx| {
 706                buffer_store.add_buffer(buffer.clone(), cx).log_err();
 707            })?;
 708            Ok(buffer)
 709        })
 710    }
 711
 712    fn reload_buffers(
 713        &self,
 714        buffers: HashSet<Entity<Buffer>>,
 715        push_to_history: bool,
 716        cx: &mut Context<BufferStore>,
 717    ) -> Task<Result<ProjectTransaction>> {
 718        cx.spawn(async move |_, cx| {
 719            let mut project_transaction = ProjectTransaction::default();
 720            for buffer in buffers {
 721                let transaction = buffer.update(cx, |buffer, cx| buffer.reload(cx))?.await?;
 722                buffer.update(cx, |buffer, cx| {
 723                    if let Some(transaction) = transaction {
 724                        if !push_to_history {
 725                            buffer.forget_transaction(transaction.id);
 726                        }
 727                        project_transaction.0.insert(cx.entity(), transaction);
 728                    }
 729                })?;
 730            }
 731
 732            Ok(project_transaction)
 733        })
 734    }
 735}
 736
 737impl BufferStore {
 738    pub fn init(client: &AnyProtoClient) {
 739        client.add_entity_message_handler(Self::handle_buffer_reloaded);
 740        client.add_entity_message_handler(Self::handle_buffer_saved);
 741        client.add_entity_message_handler(Self::handle_update_buffer_file);
 742        client.add_entity_request_handler(Self::handle_save_buffer);
 743        client.add_entity_request_handler(Self::handle_reload_buffers);
 744    }
 745
 746    /// Creates a buffer store, optionally retaining its buffers.
 747    pub fn local(worktree_store: Entity<WorktreeStore>, cx: &mut Context<Self>) -> Self {
 748        Self {
 749            state: BufferStoreState::Local(LocalBufferStore {
 750                local_buffer_ids_by_path: Default::default(),
 751                local_buffer_ids_by_entry_id: Default::default(),
 752                worktree_store: worktree_store.clone(),
 753                _subscription: cx.subscribe(&worktree_store, |this, _, event, cx| {
 754                    if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
 755                        let this = this.as_local_mut().unwrap();
 756                        this.subscribe_to_worktree(worktree, cx);
 757                    }
 758                }),
 759            }),
 760            downstream_client: None,
 761            opened_buffers: Default::default(),
 762            shared_buffers: Default::default(),
 763            loading_buffers: Default::default(),
 764            worktree_store,
 765        }
 766    }
 767
 768    pub fn remote(
 769        worktree_store: Entity<WorktreeStore>,
 770        upstream_client: AnyProtoClient,
 771        remote_id: u64,
 772        _cx: &mut Context<Self>,
 773    ) -> Self {
 774        Self {
 775            state: BufferStoreState::Remote(RemoteBufferStore {
 776                shared_with_me: Default::default(),
 777                loading_remote_buffers_by_id: Default::default(),
 778                remote_buffer_listeners: Default::default(),
 779                project_id: remote_id,
 780                upstream_client,
 781                worktree_store: worktree_store.clone(),
 782            }),
 783            downstream_client: None,
 784            opened_buffers: Default::default(),
 785            loading_buffers: Default::default(),
 786            shared_buffers: Default::default(),
 787            worktree_store,
 788        }
 789    }
 790
 791    fn as_local(&self) -> Option<&LocalBufferStore> {
 792        match &self.state {
 793            BufferStoreState::Local(state) => Some(state),
 794            _ => None,
 795        }
 796    }
 797
 798    fn as_local_mut(&mut self) -> Option<&mut LocalBufferStore> {
 799        match &mut self.state {
 800            BufferStoreState::Local(state) => Some(state),
 801            _ => None,
 802        }
 803    }
 804
 805    fn as_remote_mut(&mut self) -> Option<&mut RemoteBufferStore> {
 806        match &mut self.state {
 807            BufferStoreState::Remote(state) => Some(state),
 808            _ => None,
 809        }
 810    }
 811
 812    fn as_remote(&self) -> Option<&RemoteBufferStore> {
 813        match &self.state {
 814            BufferStoreState::Remote(state) => Some(state),
 815            _ => None,
 816        }
 817    }
 818
 819    pub fn open_buffer(
 820        &mut self,
 821        project_path: ProjectPath,
 822        cx: &mut Context<Self>,
 823    ) -> Task<Result<Entity<Buffer>>> {
 824        if let Some(buffer) = self.get_by_path(&project_path, cx) {
 825            cx.emit(BufferStoreEvent::BufferOpened {
 826                buffer: buffer.clone(),
 827                project_path,
 828            });
 829
 830            return Task::ready(Ok(buffer));
 831        }
 832
 833        let task = match self.loading_buffers.entry(project_path.clone()) {
 834            hash_map::Entry::Occupied(e) => e.get().clone(),
 835            hash_map::Entry::Vacant(entry) => {
 836                let path = project_path.path.clone();
 837                let Some(worktree) = self
 838                    .worktree_store
 839                    .read(cx)
 840                    .worktree_for_id(project_path.worktree_id, cx)
 841                else {
 842                    return Task::ready(Err(anyhow!("no such worktree")));
 843                };
 844                let load_buffer = match &self.state {
 845                    BufferStoreState::Local(this) => this.open_buffer(path, worktree, cx),
 846                    BufferStoreState::Remote(this) => this.open_buffer(path, worktree, cx),
 847                };
 848
 849                entry
 850                    .insert(
 851                        cx.spawn(async move |this, cx| {
 852                            let load_result = load_buffer.await;
 853                            this.update(cx, |this, cx| {
 854                                // Record the fact that the buffer is no longer loading.
 855                                this.loading_buffers.remove(&project_path);
 856
 857                                let buffer = load_result.map_err(Arc::new)?;
 858                                cx.emit(BufferStoreEvent::BufferOpened {
 859                                    buffer: buffer.clone(),
 860                                    project_path,
 861                                });
 862
 863                                Ok(buffer)
 864                            })?
 865                        })
 866                        .shared(),
 867                    )
 868                    .clone()
 869            }
 870        };
 871
 872        cx.background_spawn(async move { task.await.map_err(|e| anyhow!("{e}")) })
 873    }
 874
 875    pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
 876        match &self.state {
 877            BufferStoreState::Local(this) => this.create_buffer(cx),
 878            BufferStoreState::Remote(this) => this.create_buffer(cx),
 879        }
 880    }
 881
 882    pub fn save_buffer(
 883        &mut self,
 884        buffer: Entity<Buffer>,
 885        cx: &mut Context<Self>,
 886    ) -> Task<Result<()>> {
 887        match &mut self.state {
 888            BufferStoreState::Local(this) => this.save_buffer(buffer, cx),
 889            BufferStoreState::Remote(this) => this.save_remote_buffer(buffer.clone(), None, cx),
 890        }
 891    }
 892
 893    pub fn save_buffer_as(
 894        &mut self,
 895        buffer: Entity<Buffer>,
 896        path: ProjectPath,
 897        cx: &mut Context<Self>,
 898    ) -> Task<Result<()>> {
 899        let old_file = buffer.read(cx).file().cloned();
 900        let task = match &self.state {
 901            BufferStoreState::Local(this) => this.save_buffer_as(buffer.clone(), path, cx),
 902            BufferStoreState::Remote(this) => {
 903                this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
 904            }
 905        };
 906        cx.spawn(async move |this, cx| {
 907            task.await?;
 908            this.update(cx, |_, cx| {
 909                cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
 910            })
 911        })
 912    }
 913
 914    fn add_buffer(&mut self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
 915        let buffer = buffer_entity.read(cx);
 916        let remote_id = buffer.remote_id();
 917        let is_remote = buffer.replica_id() != 0;
 918        let open_buffer = OpenBuffer::Complete {
 919            buffer: buffer_entity.downgrade(),
 920        };
 921
 922        let handle = cx.entity().downgrade();
 923        buffer_entity.update(cx, move |_, cx| {
 924            cx.on_release(move |buffer, cx| {
 925                handle
 926                    .update(cx, |_, cx| {
 927                        cx.emit(BufferStoreEvent::BufferDropped(buffer.remote_id()))
 928                    })
 929                    .ok();
 930            })
 931            .detach()
 932        });
 933
 934        match self.opened_buffers.entry(remote_id) {
 935            hash_map::Entry::Vacant(entry) => {
 936                entry.insert(open_buffer);
 937            }
 938            hash_map::Entry::Occupied(mut entry) => {
 939                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 940                    buffer_entity.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx));
 941                } else if entry.get().upgrade().is_some() {
 942                    if is_remote {
 943                        return Ok(());
 944                    } else {
 945                        debug_panic!("buffer {} was already registered", remote_id);
 946                        Err(anyhow!("buffer {} was already registered", remote_id))?;
 947                    }
 948                }
 949                entry.insert(open_buffer);
 950            }
 951        }
 952
 953        cx.subscribe(&buffer_entity, Self::on_buffer_event).detach();
 954        cx.emit(BufferStoreEvent::BufferAdded(buffer_entity));
 955        Ok(())
 956    }
 957
 958    pub fn buffers(&self) -> impl '_ + Iterator<Item = Entity<Buffer>> {
 959        self.opened_buffers
 960            .values()
 961            .filter_map(|buffer| buffer.upgrade())
 962    }
 963
 964    pub fn loading_buffers(
 965        &self,
 966    ) -> impl Iterator<Item = (&ProjectPath, impl Future<Output = Result<Entity<Buffer>>>)> {
 967        self.loading_buffers.iter().map(|(path, task)| {
 968            let task = task.clone();
 969            (path, async move { task.await.map_err(|e| anyhow!("{e}")) })
 970        })
 971    }
 972
 973    pub fn buffer_id_for_project_path(&self, project_path: &ProjectPath) -> Option<&BufferId> {
 974        self.as_local()
 975            .and_then(|state| state.local_buffer_ids_by_path.get(project_path))
 976    }
 977
 978    pub fn get_by_path(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
 979        self.buffers().find_map(|buffer| {
 980            let file = File::from_dyn(buffer.read(cx).file())?;
 981            if file.worktree_id(cx) == path.worktree_id && file.path == path.path {
 982                Some(buffer)
 983            } else {
 984                None
 985            }
 986        })
 987    }
 988
 989    pub fn get(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
 990        self.opened_buffers.get(&buffer_id)?.upgrade()
 991    }
 992
 993    pub fn get_existing(&self, buffer_id: BufferId) -> Result<Entity<Buffer>> {
 994        self.get(buffer_id)
 995            .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 996    }
 997
 998    pub fn get_possibly_incomplete(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
 999        self.get(buffer_id).or_else(|| {
1000            self.as_remote()
1001                .and_then(|remote| remote.loading_remote_buffers_by_id.get(&buffer_id).cloned())
1002        })
1003    }
1004
1005    pub fn buffer_version_info(&self, cx: &App) -> (Vec<proto::BufferVersion>, Vec<BufferId>) {
1006        let buffers = self
1007            .buffers()
1008            .map(|buffer| {
1009                let buffer = buffer.read(cx);
1010                proto::BufferVersion {
1011                    id: buffer.remote_id().into(),
1012                    version: language::proto::serialize_version(&buffer.version),
1013                }
1014            })
1015            .collect();
1016        let incomplete_buffer_ids = self
1017            .as_remote()
1018            .map(|remote| remote.incomplete_buffer_ids())
1019            .unwrap_or_default();
1020        (buffers, incomplete_buffer_ids)
1021    }
1022
1023    pub fn disconnected_from_host(&mut self, cx: &mut App) {
1024        for open_buffer in self.opened_buffers.values_mut() {
1025            if let Some(buffer) = open_buffer.upgrade() {
1026                buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1027            }
1028        }
1029
1030        for buffer in self.buffers() {
1031            buffer.update(cx, |buffer, cx| {
1032                buffer.set_capability(Capability::ReadOnly, cx)
1033            });
1034        }
1035
1036        if let Some(remote) = self.as_remote_mut() {
1037            // Wake up all futures currently waiting on a buffer to get opened,
1038            // to give them a chance to fail now that we've disconnected.
1039            remote.remote_buffer_listeners.clear()
1040        }
1041    }
1042
1043    pub fn shared(&mut self, remote_id: u64, downstream_client: AnyProtoClient, _cx: &mut App) {
1044        self.downstream_client = Some((downstream_client, remote_id));
1045    }
1046
1047    pub fn unshared(&mut self, _cx: &mut Context<Self>) {
1048        self.downstream_client.take();
1049        self.forget_shared_buffers();
1050    }
1051
1052    pub fn discard_incomplete(&mut self) {
1053        self.opened_buffers
1054            .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
1055    }
1056
1057    pub fn find_search_candidates(
1058        &mut self,
1059        query: &SearchQuery,
1060        mut limit: usize,
1061        fs: Arc<dyn Fs>,
1062        cx: &mut Context<Self>,
1063    ) -> Receiver<Entity<Buffer>> {
1064        let (tx, rx) = smol::channel::unbounded();
1065        let mut open_buffers = HashSet::default();
1066        let mut unnamed_buffers = Vec::new();
1067        for handle in self.buffers() {
1068            let buffer = handle.read(cx);
1069            if let Some(entry_id) = buffer.entry_id(cx) {
1070                open_buffers.insert(entry_id);
1071            } else {
1072                limit = limit.saturating_sub(1);
1073                unnamed_buffers.push(handle)
1074            };
1075        }
1076
1077        const MAX_CONCURRENT_BUFFER_OPENS: usize = 64;
1078        let project_paths_rx = self
1079            .worktree_store
1080            .update(cx, |worktree_store, cx| {
1081                worktree_store.find_search_candidates(query.clone(), limit, open_buffers, fs, cx)
1082            })
1083            .chunks(MAX_CONCURRENT_BUFFER_OPENS);
1084
1085        cx.spawn(async move |this, cx| {
1086            for buffer in unnamed_buffers {
1087                tx.send(buffer).await.ok();
1088            }
1089
1090            let mut project_paths_rx = pin!(project_paths_rx);
1091            while let Some(project_paths) = project_paths_rx.next().await {
1092                let buffers = this.update(cx, |this, cx| {
1093                    project_paths
1094                        .into_iter()
1095                        .map(|project_path| this.open_buffer(project_path, cx))
1096                        .collect::<Vec<_>>()
1097                })?;
1098                for buffer_task in buffers {
1099                    if let Some(buffer) = buffer_task.await.log_err() {
1100                        if tx.send(buffer).await.is_err() {
1101                            return anyhow::Ok(());
1102                        }
1103                    }
1104                }
1105            }
1106            anyhow::Ok(())
1107        })
1108        .detach();
1109        rx
1110    }
1111
1112    fn on_buffer_event(
1113        &mut self,
1114        buffer: Entity<Buffer>,
1115        event: &BufferEvent,
1116        cx: &mut Context<Self>,
1117    ) {
1118        match event {
1119            BufferEvent::FileHandleChanged => {
1120                if let Some(local) = self.as_local_mut() {
1121                    local.buffer_changed_file(buffer, cx);
1122                }
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 Some(remote) = self.as_remote_mut() else {
1285            return Err(anyhow!("buffer store is not a remote"));
1286        };
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.ok_or_else(|| anyhow!("invalid file"))?;
1309                let worktree = this
1310                    .worktree_store
1311                    .read(cx)
1312                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
1313                    .ok_or_else(|| anyhow!("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                    buffer.file_updated(Arc::new(file), cx);
1319                    if old_file
1320                        .as_ref()
1321                        .map_or(true, |old| *old.path() != new_path)
1322                    {
1323                        Some(old_file)
1324                    } else {
1325                        None
1326                    }
1327                });
1328                if let Some(old_file) = old_file {
1329                    cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
1330                }
1331            }
1332            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1333                downstream_client
1334                    .send(proto::UpdateBufferFile {
1335                        project_id: *project_id,
1336                        buffer_id: buffer_id.into(),
1337                        file: envelope.payload.file,
1338                    })
1339                    .log_err();
1340            }
1341            Ok(())
1342        })?
1343    }
1344
1345    pub async fn handle_save_buffer(
1346        this: Entity<Self>,
1347        envelope: TypedEnvelope<proto::SaveBuffer>,
1348        mut cx: AsyncApp,
1349    ) -> Result<proto::BufferSaved> {
1350        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1351        let (buffer, project_id) = this.update(&mut cx, |this, _| {
1352            anyhow::Ok((
1353                this.get_existing(buffer_id)?,
1354                this.downstream_client
1355                    .as_ref()
1356                    .map(|(_, project_id)| *project_id)
1357                    .context("project is not shared")?,
1358            ))
1359        })??;
1360        buffer
1361            .update(&mut cx, |buffer, _| {
1362                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
1363            })?
1364            .await?;
1365        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
1366
1367        if let Some(new_path) = envelope.payload.new_path {
1368            let new_path = ProjectPath::from_proto(new_path);
1369            this.update(&mut cx, |this, cx| {
1370                this.save_buffer_as(buffer.clone(), new_path, cx)
1371            })?
1372            .await?;
1373        } else {
1374            this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
1375                .await?;
1376        }
1377
1378        buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
1379            project_id,
1380            buffer_id: buffer_id.into(),
1381            version: serialize_version(buffer.saved_version()),
1382            mtime: buffer.saved_mtime().map(|time| time.into()),
1383        })
1384    }
1385
1386    pub async fn handle_close_buffer(
1387        this: Entity<Self>,
1388        envelope: TypedEnvelope<proto::CloseBuffer>,
1389        mut cx: AsyncApp,
1390    ) -> Result<()> {
1391        let peer_id = envelope.sender_id;
1392        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1393        this.update(&mut cx, |this, cx| {
1394            if let Some(shared) = this.shared_buffers.get_mut(&peer_id) {
1395                if shared.remove(&buffer_id).is_some() {
1396                    cx.emit(BufferStoreEvent::SharedBufferClosed(peer_id, buffer_id));
1397                    if shared.is_empty() {
1398                        this.shared_buffers.remove(&peer_id);
1399                    }
1400                    return;
1401                }
1402            }
1403            debug_panic!(
1404                "peer_id {} closed buffer_id {} which was either not open or already closed",
1405                peer_id,
1406                buffer_id
1407            )
1408        })
1409    }
1410
1411    pub async fn handle_buffer_saved(
1412        this: Entity<Self>,
1413        envelope: TypedEnvelope<proto::BufferSaved>,
1414        mut cx: AsyncApp,
1415    ) -> Result<()> {
1416        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1417        let version = deserialize_version(&envelope.payload.version);
1418        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1419        this.update(&mut cx, move |this, cx| {
1420            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1421                buffer.update(cx, |buffer, cx| {
1422                    buffer.did_save(version, mtime, cx);
1423                });
1424            }
1425
1426            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1427                downstream_client
1428                    .send(proto::BufferSaved {
1429                        project_id: *project_id,
1430                        buffer_id: buffer_id.into(),
1431                        mtime: envelope.payload.mtime,
1432                        version: envelope.payload.version,
1433                    })
1434                    .log_err();
1435            }
1436        })
1437    }
1438
1439    pub async fn handle_buffer_reloaded(
1440        this: Entity<Self>,
1441        envelope: TypedEnvelope<proto::BufferReloaded>,
1442        mut cx: AsyncApp,
1443    ) -> Result<()> {
1444        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1445        let version = deserialize_version(&envelope.payload.version);
1446        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1447        let line_ending = deserialize_line_ending(
1448            proto::LineEnding::from_i32(envelope.payload.line_ending)
1449                .ok_or_else(|| anyhow!("missing line ending"))?,
1450        );
1451        this.update(&mut cx, |this, cx| {
1452            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1453                buffer.update(cx, |buffer, cx| {
1454                    buffer.did_reload(version, line_ending, mtime, cx);
1455                });
1456            }
1457
1458            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1459                downstream_client
1460                    .send(proto::BufferReloaded {
1461                        project_id: *project_id,
1462                        buffer_id: buffer_id.into(),
1463                        mtime: envelope.payload.mtime,
1464                        version: envelope.payload.version,
1465                        line_ending: envelope.payload.line_ending,
1466                    })
1467                    .log_err();
1468            }
1469        })
1470    }
1471
1472    pub fn reload_buffers(
1473        &self,
1474        buffers: HashSet<Entity<Buffer>>,
1475        push_to_history: bool,
1476        cx: &mut Context<Self>,
1477    ) -> Task<Result<ProjectTransaction>> {
1478        if buffers.is_empty() {
1479            return Task::ready(Ok(ProjectTransaction::default()));
1480        }
1481        match &self.state {
1482            BufferStoreState::Local(this) => this.reload_buffers(buffers, push_to_history, cx),
1483            BufferStoreState::Remote(this) => this.reload_buffers(buffers, push_to_history, cx),
1484        }
1485    }
1486
1487    async fn handle_reload_buffers(
1488        this: Entity<Self>,
1489        envelope: TypedEnvelope<proto::ReloadBuffers>,
1490        mut cx: AsyncApp,
1491    ) -> Result<proto::ReloadBuffersResponse> {
1492        let sender_id = envelope.original_sender_id().unwrap_or_default();
1493        let reload = this.update(&mut cx, |this, cx| {
1494            let mut buffers = HashSet::default();
1495            for buffer_id in &envelope.payload.buffer_ids {
1496                let buffer_id = BufferId::new(*buffer_id)?;
1497                buffers.insert(this.get_existing(buffer_id)?);
1498            }
1499            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
1500        })??;
1501
1502        let project_transaction = reload.await?;
1503        let project_transaction = this.update(&mut cx, |this, cx| {
1504            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
1505        })?;
1506        Ok(proto::ReloadBuffersResponse {
1507            transaction: Some(project_transaction),
1508        })
1509    }
1510
1511    pub fn create_buffer_for_peer(
1512        &mut self,
1513        buffer: &Entity<Buffer>,
1514        peer_id: proto::PeerId,
1515        cx: &mut Context<Self>,
1516    ) -> Task<Result<()>> {
1517        let buffer_id = buffer.read(cx).remote_id();
1518        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
1519        if shared_buffers.contains_key(&buffer_id) {
1520            return Task::ready(Ok(()));
1521        }
1522        shared_buffers.insert(
1523            buffer_id,
1524            SharedBuffer {
1525                buffer: buffer.clone(),
1526                lsp_handle: None,
1527            },
1528        );
1529
1530        let Some((client, project_id)) = self.downstream_client.clone() else {
1531            return Task::ready(Ok(()));
1532        };
1533
1534        cx.spawn(async move |this, cx| {
1535            let Some(buffer) = this.update(cx, |this, _| this.get(buffer_id))? else {
1536                return anyhow::Ok(());
1537            };
1538
1539            let operations = buffer.update(cx, |b, cx| b.serialize_ops(None, cx))?;
1540            let operations = operations.await;
1541            let state = buffer.update(cx, |buffer, cx| buffer.to_proto(cx))?;
1542
1543            let initial_state = proto::CreateBufferForPeer {
1544                project_id,
1545                peer_id: Some(peer_id),
1546                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1547            };
1548
1549            if client.send(initial_state).log_err().is_some() {
1550                let client = client.clone();
1551                cx.background_spawn(async move {
1552                    let mut chunks = split_operations(operations).peekable();
1553                    while let Some(chunk) = chunks.next() {
1554                        let is_last = chunks.peek().is_none();
1555                        client.send(proto::CreateBufferForPeer {
1556                            project_id,
1557                            peer_id: Some(peer_id),
1558                            variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
1559                                proto::BufferChunk {
1560                                    buffer_id: buffer_id.into(),
1561                                    operations: chunk,
1562                                    is_last,
1563                                },
1564                            )),
1565                        })?;
1566                    }
1567                    anyhow::Ok(())
1568                })
1569                .await
1570                .log_err();
1571            }
1572            Ok(())
1573        })
1574    }
1575
1576    pub fn forget_shared_buffers(&mut self) {
1577        self.shared_buffers.clear();
1578    }
1579
1580    pub fn forget_shared_buffers_for(&mut self, peer_id: &proto::PeerId) {
1581        self.shared_buffers.remove(peer_id);
1582    }
1583
1584    pub fn update_peer_id(&mut self, old_peer_id: &proto::PeerId, new_peer_id: proto::PeerId) {
1585        if let Some(buffers) = self.shared_buffers.remove(old_peer_id) {
1586            self.shared_buffers.insert(new_peer_id, buffers);
1587        }
1588    }
1589
1590    pub fn has_shared_buffers(&self) -> bool {
1591        !self.shared_buffers.is_empty()
1592    }
1593
1594    pub fn create_local_buffer(
1595        &mut self,
1596        text: &str,
1597        language: Option<Arc<Language>>,
1598        cx: &mut Context<Self>,
1599    ) -> Entity<Buffer> {
1600        let buffer = cx.new(|cx| {
1601            Buffer::local(text, cx)
1602                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1603        });
1604
1605        self.add_buffer(buffer.clone(), cx).log_err();
1606        let buffer_id = buffer.read(cx).remote_id();
1607
1608        let this = self
1609            .as_local_mut()
1610            .expect("local-only method called in a non-local context");
1611        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1612            this.local_buffer_ids_by_path.insert(
1613                ProjectPath {
1614                    worktree_id: file.worktree_id(cx),
1615                    path: file.path.clone(),
1616                },
1617                buffer_id,
1618            );
1619
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
1679impl OpenBuffer {
1680    fn upgrade(&self) -> Option<Entity<Buffer>> {
1681        match self {
1682            OpenBuffer::Complete { buffer, .. } => buffer.upgrade(),
1683            OpenBuffer::Operations(_) => None,
1684        }
1685    }
1686}
1687
1688fn is_not_found_error(error: &anyhow::Error) -> bool {
1689    error
1690        .root_cause()
1691        .downcast_ref::<io::Error>()
1692        .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
1693}