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