project.rs

   1mod ignore;
   2mod lsp_command;
   3pub mod project_settings;
   4pub mod search;
   5pub mod terminals;
   6pub mod worktree;
   7
   8#[cfg(test)]
   9mod project_tests;
  10
  11use anyhow::{anyhow, Context, Result};
  12use client::{proto, Client, TypedEnvelope, UserStore};
  13use clock::ReplicaId;
  14use collections::{hash_map, BTreeMap, HashMap, HashSet};
  15use copilot::Copilot;
  16use futures::{
  17    channel::{
  18        mpsc::{self, UnboundedReceiver},
  19        oneshot,
  20    },
  21    future::{try_join_all, Shared},
  22    stream::FuturesUnordered,
  23    AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
  24};
  25use globset::{Glob, GlobSet, GlobSetBuilder};
  26use gpui::{
  27    AnyModelHandle, AppContext, AsyncAppContext, BorrowAppContext, Entity, ModelContext,
  28    ModelHandle, Task, WeakModelHandle,
  29};
  30use language::{
  31    language_settings::{all_language_settings, language_settings, FormatOnSave, Formatter},
  32    point_to_lsp,
  33    proto::{
  34        deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version,
  35        serialize_anchor, serialize_version,
  36    },
  37    range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CachedLspAdapter, CodeAction, CodeLabel,
  38    Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Event as BufferEvent, File as _,
  39    Language, LanguageRegistry, LanguageServerName, LocalFile, OffsetRangeExt, Operation, Patch,
  40    PendingLanguageServer, PointUtf16, RopeFingerprint, TextBufferSnapshot, ToOffset, ToPointUtf16,
  41    Transaction, Unclipped,
  42};
  43use lsp::{
  44    DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
  45    DocumentHighlightKind, LanguageServer, LanguageServerId,
  46};
  47use lsp_command::*;
  48use postage::watch;
  49use project_settings::ProjectSettings;
  50use rand::prelude::*;
  51use search::SearchQuery;
  52use serde::Serialize;
  53use settings::SettingsStore;
  54use sha2::{Digest, Sha256};
  55use similar::{ChangeTag, TextDiff};
  56use std::{
  57    cell::RefCell,
  58    cmp::{self, Ordering},
  59    convert::TryInto,
  60    hash::Hash,
  61    mem,
  62    num::NonZeroU32,
  63    ops::Range,
  64    path::{Component, Path, PathBuf},
  65    rc::Rc,
  66    str,
  67    sync::{
  68        atomic::{AtomicUsize, Ordering::SeqCst},
  69        Arc,
  70    },
  71    time::{Duration, Instant, SystemTime},
  72};
  73use terminals::Terminals;
  74use util::{debug_panic, defer, merge_json_value_into, post_inc, ResultExt, TryFutureExt as _};
  75
  76pub use fs::*;
  77pub use worktree::*;
  78
  79pub trait Item {
  80    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  81    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
  82}
  83
  84// Language server state is stored across 3 collections:
  85//     language_servers =>
  86//         a mapping from unique server id to LanguageServerState which can either be a task for a
  87//         server in the process of starting, or a running server with adapter and language server arcs
  88//     language_server_ids => a mapping from worktreeId and server name to the unique server id
  89//     language_server_statuses => a mapping from unique server id to the current server status
  90//
  91// Multiple worktrees can map to the same language server for example when you jump to the definition
  92// of a file in the standard library. So language_server_ids is used to look up which server is active
  93// for a given worktree and language server name
  94//
  95// When starting a language server, first the id map is checked to make sure a server isn't already available
  96// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
  97// the Starting variant of LanguageServerState is stored in the language_servers map.
  98pub struct Project {
  99    worktrees: Vec<WorktreeHandle>,
 100    active_entry: Option<ProjectEntryId>,
 101    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 102    languages: Arc<LanguageRegistry>,
 103    language_servers: HashMap<LanguageServerId, LanguageServerState>,
 104    language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
 105    language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
 106    last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
 107    client: Arc<client::Client>,
 108    next_entry_id: Arc<AtomicUsize>,
 109    join_project_response_message_id: u32,
 110    next_diagnostic_group_id: usize,
 111    user_store: ModelHandle<UserStore>,
 112    fs: Arc<dyn Fs>,
 113    client_state: Option<ProjectClientState>,
 114    collaborators: HashMap<proto::PeerId, Collaborator>,
 115    client_subscriptions: Vec<client::Subscription>,
 116    _subscriptions: Vec<gpui::Subscription>,
 117    next_buffer_id: u64,
 118    opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
 119    shared_buffers: HashMap<proto::PeerId, HashSet<u64>>,
 120    #[allow(clippy::type_complexity)]
 121    loading_buffers_by_path: HashMap<
 122        ProjectPath,
 123        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
 124    >,
 125    #[allow(clippy::type_complexity)]
 126    loading_local_worktrees:
 127        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
 128    opened_buffers: HashMap<u64, OpenBuffer>,
 129    local_buffer_ids_by_path: HashMap<ProjectPath, u64>,
 130    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, u64>,
 131    /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
 132    /// Used for re-issuing buffer requests when peers temporarily disconnect
 133    incomplete_remote_buffers: HashMap<u64, Option<ModelHandle<Buffer>>>,
 134    buffer_snapshots: HashMap<u64, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
 135    buffers_being_formatted: HashSet<u64>,
 136    buffers_needing_diff: HashSet<WeakModelHandle<Buffer>>,
 137    git_diff_debouncer: DelayedDebounced,
 138    nonce: u128,
 139    _maintain_buffer_languages: Task<()>,
 140    _maintain_workspace_config: Task<()>,
 141    terminals: Terminals,
 142    copilot_enabled: bool,
 143}
 144
 145struct DelayedDebounced {
 146    task: Option<Task<()>>,
 147    cancel_channel: Option<oneshot::Sender<()>>,
 148}
 149
 150impl DelayedDebounced {
 151    fn new() -> DelayedDebounced {
 152        DelayedDebounced {
 153            task: None,
 154            cancel_channel: None,
 155        }
 156    }
 157
 158    fn fire_new<F>(&mut self, delay: Duration, cx: &mut ModelContext<Project>, func: F)
 159    where
 160        F: 'static + FnOnce(&mut Project, &mut ModelContext<Project>) -> Task<()>,
 161    {
 162        if let Some(channel) = self.cancel_channel.take() {
 163            _ = channel.send(());
 164        }
 165
 166        let (sender, mut receiver) = oneshot::channel::<()>();
 167        self.cancel_channel = Some(sender);
 168
 169        let previous_task = self.task.take();
 170        self.task = Some(cx.spawn(|workspace, mut cx| async move {
 171            let mut timer = cx.background().timer(delay).fuse();
 172            if let Some(previous_task) = previous_task {
 173                previous_task.await;
 174            }
 175
 176            futures::select_biased! {
 177                _ = receiver => return,
 178                    _ = timer => {}
 179            }
 180
 181            workspace
 182                .update(&mut cx, |workspace, cx| (func)(workspace, cx))
 183                .await;
 184        }));
 185    }
 186}
 187
 188struct LspBufferSnapshot {
 189    version: i32,
 190    snapshot: TextBufferSnapshot,
 191}
 192
 193/// Message ordered with respect to buffer operations
 194enum BufferOrderedMessage {
 195    Operation {
 196        buffer_id: u64,
 197        operation: proto::Operation,
 198    },
 199    LanguageServerUpdate {
 200        language_server_id: LanguageServerId,
 201        message: proto::update_language_server::Variant,
 202    },
 203    Resync,
 204}
 205
 206enum LocalProjectUpdate {
 207    WorktreesChanged,
 208    CreateBufferForPeer {
 209        peer_id: proto::PeerId,
 210        buffer_id: u64,
 211    },
 212}
 213
 214enum OpenBuffer {
 215    Strong(ModelHandle<Buffer>),
 216    Weak(WeakModelHandle<Buffer>),
 217    Operations(Vec<Operation>),
 218}
 219
 220enum WorktreeHandle {
 221    Strong(ModelHandle<Worktree>),
 222    Weak(WeakModelHandle<Worktree>),
 223}
 224
 225enum ProjectClientState {
 226    Local {
 227        remote_id: u64,
 228        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
 229        _send_updates: Task<()>,
 230    },
 231    Remote {
 232        sharing_has_stopped: bool,
 233        remote_id: u64,
 234        replica_id: ReplicaId,
 235    },
 236}
 237
 238#[derive(Clone, Debug)]
 239pub struct Collaborator {
 240    pub peer_id: proto::PeerId,
 241    pub replica_id: ReplicaId,
 242}
 243
 244#[derive(Clone, Debug, PartialEq, Eq)]
 245pub enum Event {
 246    LanguageServerAdded(LanguageServerId),
 247    LanguageServerRemoved(LanguageServerId),
 248    ActiveEntryChanged(Option<ProjectEntryId>),
 249    WorktreeAdded,
 250    WorktreeRemoved(WorktreeId),
 251    DiskBasedDiagnosticsStarted {
 252        language_server_id: LanguageServerId,
 253    },
 254    DiskBasedDiagnosticsFinished {
 255        language_server_id: LanguageServerId,
 256    },
 257    DiagnosticsUpdated {
 258        path: ProjectPath,
 259        language_server_id: LanguageServerId,
 260    },
 261    RemoteIdChanged(Option<u64>),
 262    DisconnectedFromHost,
 263    Closed,
 264    DeletedEntry(ProjectEntryId),
 265    CollaboratorUpdated {
 266        old_peer_id: proto::PeerId,
 267        new_peer_id: proto::PeerId,
 268    },
 269    CollaboratorLeft(proto::PeerId),
 270}
 271
 272pub enum LanguageServerState {
 273    Starting(Task<Option<Arc<LanguageServer>>>),
 274    Running {
 275        language: Arc<Language>,
 276        adapter: Arc<CachedLspAdapter>,
 277        server: Arc<LanguageServer>,
 278        watched_paths: HashMap<WorktreeId, GlobSet>,
 279        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
 280    },
 281}
 282
 283#[derive(Serialize)]
 284pub struct LanguageServerStatus {
 285    pub name: String,
 286    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 287    pub has_pending_diagnostic_updates: bool,
 288    progress_tokens: HashSet<String>,
 289}
 290
 291#[derive(Clone, Debug, Serialize)]
 292pub struct LanguageServerProgress {
 293    pub message: Option<String>,
 294    pub percentage: Option<usize>,
 295    #[serde(skip_serializing)]
 296    pub last_update_at: Instant,
 297}
 298
 299#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 300pub struct ProjectPath {
 301    pub worktree_id: WorktreeId,
 302    pub path: Arc<Path>,
 303}
 304
 305#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 306pub struct DiagnosticSummary {
 307    pub error_count: usize,
 308    pub warning_count: usize,
 309}
 310
 311#[derive(Debug, Clone)]
 312pub struct Location {
 313    pub buffer: ModelHandle<Buffer>,
 314    pub range: Range<language::Anchor>,
 315}
 316
 317#[derive(Debug, Clone)]
 318pub struct LocationLink {
 319    pub origin: Option<Location>,
 320    pub target: Location,
 321}
 322
 323#[derive(Debug)]
 324pub struct DocumentHighlight {
 325    pub range: Range<language::Anchor>,
 326    pub kind: DocumentHighlightKind,
 327}
 328
 329#[derive(Clone, Debug)]
 330pub struct Symbol {
 331    pub language_server_name: LanguageServerName,
 332    pub source_worktree_id: WorktreeId,
 333    pub path: ProjectPath,
 334    pub label: CodeLabel,
 335    pub name: String,
 336    pub kind: lsp::SymbolKind,
 337    pub range: Range<Unclipped<PointUtf16>>,
 338    pub signature: [u8; 32],
 339}
 340
 341#[derive(Clone, Debug, PartialEq)]
 342pub struct HoverBlock {
 343    pub text: String,
 344    pub kind: HoverBlockKind,
 345}
 346
 347#[derive(Clone, Debug, PartialEq)]
 348pub enum HoverBlockKind {
 349    PlainText,
 350    Markdown,
 351    Code { language: String },
 352}
 353
 354#[derive(Debug)]
 355pub struct Hover {
 356    pub contents: Vec<HoverBlock>,
 357    pub range: Option<Range<language::Anchor>>,
 358}
 359
 360#[derive(Default)]
 361pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 362
 363impl DiagnosticSummary {
 364    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 365        let mut this = Self {
 366            error_count: 0,
 367            warning_count: 0,
 368        };
 369
 370        for entry in diagnostics {
 371            if entry.diagnostic.is_primary {
 372                match entry.diagnostic.severity {
 373                    DiagnosticSeverity::ERROR => this.error_count += 1,
 374                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 375                    _ => {}
 376                }
 377            }
 378        }
 379
 380        this
 381    }
 382
 383    pub fn is_empty(&self) -> bool {
 384        self.error_count == 0 && self.warning_count == 0
 385    }
 386
 387    pub fn to_proto(
 388        &self,
 389        language_server_id: LanguageServerId,
 390        path: &Path,
 391    ) -> proto::DiagnosticSummary {
 392        proto::DiagnosticSummary {
 393            path: path.to_string_lossy().to_string(),
 394            language_server_id: language_server_id.0 as u64,
 395            error_count: self.error_count as u32,
 396            warning_count: self.warning_count as u32,
 397        }
 398    }
 399}
 400
 401#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 402pub struct ProjectEntryId(usize);
 403
 404impl ProjectEntryId {
 405    pub const MAX: Self = Self(usize::MAX);
 406
 407    pub fn new(counter: &AtomicUsize) -> Self {
 408        Self(counter.fetch_add(1, SeqCst))
 409    }
 410
 411    pub fn from_proto(id: u64) -> Self {
 412        Self(id as usize)
 413    }
 414
 415    pub fn to_proto(&self) -> u64 {
 416        self.0 as u64
 417    }
 418
 419    pub fn to_usize(&self) -> usize {
 420        self.0
 421    }
 422}
 423
 424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 425pub enum FormatTrigger {
 426    Save,
 427    Manual,
 428}
 429
 430impl FormatTrigger {
 431    fn from_proto(value: i32) -> FormatTrigger {
 432        match value {
 433            0 => FormatTrigger::Save,
 434            1 => FormatTrigger::Manual,
 435            _ => FormatTrigger::Save,
 436        }
 437    }
 438}
 439
 440impl Project {
 441    pub fn init_settings(cx: &mut AppContext) {
 442        settings::register::<ProjectSettings>(cx);
 443    }
 444
 445    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
 446        Self::init_settings(cx);
 447
 448        client.add_model_message_handler(Self::handle_add_collaborator);
 449        client.add_model_message_handler(Self::handle_update_project_collaborator);
 450        client.add_model_message_handler(Self::handle_remove_collaborator);
 451        client.add_model_message_handler(Self::handle_buffer_reloaded);
 452        client.add_model_message_handler(Self::handle_buffer_saved);
 453        client.add_model_message_handler(Self::handle_start_language_server);
 454        client.add_model_message_handler(Self::handle_update_language_server);
 455        client.add_model_message_handler(Self::handle_update_project);
 456        client.add_model_message_handler(Self::handle_unshare_project);
 457        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 458        client.add_model_message_handler(Self::handle_update_buffer_file);
 459        client.add_model_request_handler(Self::handle_update_buffer);
 460        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 461        client.add_model_message_handler(Self::handle_update_worktree);
 462        client.add_model_request_handler(Self::handle_create_project_entry);
 463        client.add_model_request_handler(Self::handle_rename_project_entry);
 464        client.add_model_request_handler(Self::handle_copy_project_entry);
 465        client.add_model_request_handler(Self::handle_delete_project_entry);
 466        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 467        client.add_model_request_handler(Self::handle_apply_code_action);
 468        client.add_model_request_handler(Self::handle_on_type_formatting);
 469        client.add_model_request_handler(Self::handle_reload_buffers);
 470        client.add_model_request_handler(Self::handle_synchronize_buffers);
 471        client.add_model_request_handler(Self::handle_format_buffers);
 472        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
 473        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
 474        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 475        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 476        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
 477        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 478        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 479        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 480        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 481        client.add_model_request_handler(Self::handle_search_project);
 482        client.add_model_request_handler(Self::handle_get_project_symbols);
 483        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 484        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 485        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 486        client.add_model_request_handler(Self::handle_save_buffer);
 487        client.add_model_message_handler(Self::handle_update_diff_base);
 488    }
 489
 490    pub fn local(
 491        client: Arc<Client>,
 492        user_store: ModelHandle<UserStore>,
 493        languages: Arc<LanguageRegistry>,
 494        fs: Arc<dyn Fs>,
 495        cx: &mut AppContext,
 496    ) -> ModelHandle<Self> {
 497        cx.add_model(|cx: &mut ModelContext<Self>| {
 498            let (tx, rx) = mpsc::unbounded();
 499            cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 500                .detach();
 501            Self {
 502                worktrees: Default::default(),
 503                buffer_ordered_messages_tx: tx,
 504                collaborators: Default::default(),
 505                next_buffer_id: 0,
 506                opened_buffers: Default::default(),
 507                shared_buffers: Default::default(),
 508                incomplete_remote_buffers: Default::default(),
 509                loading_buffers_by_path: Default::default(),
 510                loading_local_worktrees: Default::default(),
 511                local_buffer_ids_by_path: Default::default(),
 512                local_buffer_ids_by_entry_id: Default::default(),
 513                buffer_snapshots: Default::default(),
 514                join_project_response_message_id: 0,
 515                client_state: None,
 516                opened_buffer: watch::channel(),
 517                client_subscriptions: Vec::new(),
 518                _subscriptions: vec![
 519                    cx.observe_global::<SettingsStore, _>(Self::on_settings_changed)
 520                ],
 521                _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
 522                _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
 523                active_entry: None,
 524                languages,
 525                client,
 526                user_store,
 527                fs,
 528                next_entry_id: Default::default(),
 529                next_diagnostic_group_id: Default::default(),
 530                language_servers: Default::default(),
 531                language_server_ids: Default::default(),
 532                language_server_statuses: Default::default(),
 533                last_workspace_edits_by_language_server: Default::default(),
 534                buffers_being_formatted: Default::default(),
 535                buffers_needing_diff: Default::default(),
 536                git_diff_debouncer: DelayedDebounced::new(),
 537                nonce: StdRng::from_entropy().gen(),
 538                terminals: Terminals {
 539                    local_handles: Vec::new(),
 540                },
 541                copilot_enabled: Copilot::global(cx).is_some(),
 542            }
 543        })
 544    }
 545
 546    pub async fn remote(
 547        remote_id: u64,
 548        client: Arc<Client>,
 549        user_store: ModelHandle<UserStore>,
 550        languages: Arc<LanguageRegistry>,
 551        fs: Arc<dyn Fs>,
 552        mut cx: AsyncAppContext,
 553    ) -> Result<ModelHandle<Self>> {
 554        client.authenticate_and_connect(true, &cx).await?;
 555
 556        let subscription = client.subscribe_to_entity(remote_id)?;
 557        let response = client
 558            .request_envelope(proto::JoinProject {
 559                project_id: remote_id,
 560            })
 561            .await?;
 562        let this = cx.add_model(|cx| {
 563            let replica_id = response.payload.replica_id as ReplicaId;
 564
 565            let mut worktrees = Vec::new();
 566            for worktree in response.payload.worktrees {
 567                let worktree = cx.update(|cx| {
 568                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
 569                });
 570                worktrees.push(worktree);
 571            }
 572
 573            let (tx, rx) = mpsc::unbounded();
 574            cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 575                .detach();
 576            let mut this = Self {
 577                worktrees: Vec::new(),
 578                buffer_ordered_messages_tx: tx,
 579                loading_buffers_by_path: Default::default(),
 580                next_buffer_id: 0,
 581                opened_buffer: watch::channel(),
 582                shared_buffers: Default::default(),
 583                incomplete_remote_buffers: Default::default(),
 584                loading_local_worktrees: Default::default(),
 585                local_buffer_ids_by_path: Default::default(),
 586                local_buffer_ids_by_entry_id: Default::default(),
 587                active_entry: None,
 588                collaborators: Default::default(),
 589                join_project_response_message_id: response.message_id,
 590                _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
 591                _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
 592                languages,
 593                user_store: user_store.clone(),
 594                fs,
 595                next_entry_id: Default::default(),
 596                next_diagnostic_group_id: Default::default(),
 597                client_subscriptions: Default::default(),
 598                _subscriptions: Default::default(),
 599                client: client.clone(),
 600                client_state: Some(ProjectClientState::Remote {
 601                    sharing_has_stopped: false,
 602                    remote_id,
 603                    replica_id,
 604                }),
 605                language_servers: Default::default(),
 606                language_server_ids: Default::default(),
 607                language_server_statuses: response
 608                    .payload
 609                    .language_servers
 610                    .into_iter()
 611                    .map(|server| {
 612                        (
 613                            LanguageServerId(server.id as usize),
 614                            LanguageServerStatus {
 615                                name: server.name,
 616                                pending_work: Default::default(),
 617                                has_pending_diagnostic_updates: false,
 618                                progress_tokens: Default::default(),
 619                            },
 620                        )
 621                    })
 622                    .collect(),
 623                last_workspace_edits_by_language_server: Default::default(),
 624                opened_buffers: Default::default(),
 625                buffers_being_formatted: Default::default(),
 626                buffers_needing_diff: Default::default(),
 627                git_diff_debouncer: DelayedDebounced::new(),
 628                buffer_snapshots: Default::default(),
 629                nonce: StdRng::from_entropy().gen(),
 630                terminals: Terminals {
 631                    local_handles: Vec::new(),
 632                },
 633                copilot_enabled: Copilot::global(cx).is_some(),
 634            };
 635            for worktree in worktrees {
 636                let _ = this.add_worktree(&worktree, cx);
 637            }
 638            this
 639        });
 640        let subscription = subscription.set_model(&this, &mut cx);
 641
 642        let user_ids = response
 643            .payload
 644            .collaborators
 645            .iter()
 646            .map(|peer| peer.user_id)
 647            .collect();
 648        user_store
 649            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
 650            .await?;
 651
 652        this.update(&mut cx, |this, cx| {
 653            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
 654            this.client_subscriptions.push(subscription);
 655            anyhow::Ok(())
 656        })?;
 657
 658        Ok(this)
 659    }
 660
 661    #[cfg(any(test, feature = "test-support"))]
 662    pub async fn test(
 663        fs: Arc<dyn Fs>,
 664        root_paths: impl IntoIterator<Item = &Path>,
 665        cx: &mut gpui::TestAppContext,
 666    ) -> ModelHandle<Project> {
 667        let mut languages = LanguageRegistry::test();
 668        languages.set_executor(cx.background());
 669        let http_client = util::http::FakeHttpClient::with_404_response();
 670        let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
 671        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 672        let project =
 673            cx.update(|cx| Project::local(client, user_store, Arc::new(languages), fs, cx));
 674        for path in root_paths {
 675            let (tree, _) = project
 676                .update(cx, |project, cx| {
 677                    project.find_or_create_local_worktree(path, true, cx)
 678                })
 679                .await
 680                .unwrap();
 681            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 682                .await;
 683        }
 684        project
 685    }
 686
 687    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 688        let settings = all_language_settings(cx);
 689
 690        let mut language_servers_to_start = Vec::new();
 691        for buffer in self.opened_buffers.values() {
 692            if let Some(buffer) = buffer.upgrade(cx) {
 693                let buffer = buffer.read(cx);
 694                if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
 695                {
 696                    if settings
 697                        .language(Some(&language.name()))
 698                        .enable_language_server
 699                    {
 700                        let worktree = file.worktree.read(cx);
 701                        language_servers_to_start.push((
 702                            worktree.id(),
 703                            worktree.as_local().unwrap().abs_path().clone(),
 704                            language.clone(),
 705                        ));
 706                    }
 707                }
 708            }
 709        }
 710
 711        let mut language_servers_to_stop = Vec::new();
 712        for language in self.languages.to_vec() {
 713            for lsp_adapter in language.lsp_adapters() {
 714                if !settings
 715                    .language(Some(&language.name()))
 716                    .enable_language_server
 717                {
 718                    let lsp_name = &lsp_adapter.name;
 719                    for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 720                        if lsp_name == started_lsp_name {
 721                            language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 722                        }
 723                    }
 724                }
 725            }
 726        }
 727
 728        // Stop all newly-disabled language servers.
 729        for (worktree_id, adapter_name) in language_servers_to_stop {
 730            self.stop_language_server(worktree_id, adapter_name, cx)
 731                .detach();
 732        }
 733
 734        // Start all the newly-enabled language servers.
 735        for (worktree_id, worktree_path, language) in language_servers_to_start {
 736            self.start_language_servers(worktree_id, worktree_path, language, cx);
 737        }
 738
 739        if !self.copilot_enabled && Copilot::global(cx).is_some() {
 740            self.copilot_enabled = true;
 741            for buffer in self.opened_buffers.values() {
 742                if let Some(buffer) = buffer.upgrade(cx) {
 743                    self.register_buffer_with_copilot(&buffer, cx);
 744                }
 745            }
 746        }
 747
 748        cx.notify();
 749    }
 750
 751    pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
 752        self.opened_buffers
 753            .get(&remote_id)
 754            .and_then(|buffer| buffer.upgrade(cx))
 755    }
 756
 757    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 758        &self.languages
 759    }
 760
 761    pub fn client(&self) -> Arc<Client> {
 762        self.client.clone()
 763    }
 764
 765    pub fn user_store(&self) -> ModelHandle<UserStore> {
 766        self.user_store.clone()
 767    }
 768
 769    #[cfg(any(test, feature = "test-support"))]
 770    pub fn opened_buffers(&self, cx: &AppContext) -> Vec<ModelHandle<Buffer>> {
 771        self.opened_buffers
 772            .values()
 773            .filter_map(|b| b.upgrade(cx))
 774            .collect()
 775    }
 776
 777    #[cfg(any(test, feature = "test-support"))]
 778    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 779        let path = path.into();
 780        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 781            self.opened_buffers.iter().any(|(_, buffer)| {
 782                if let Some(buffer) = buffer.upgrade(cx) {
 783                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 784                        if file.worktree == worktree && file.path() == &path.path {
 785                            return true;
 786                        }
 787                    }
 788                }
 789                false
 790            })
 791        } else {
 792            false
 793        }
 794    }
 795
 796    pub fn fs(&self) -> &Arc<dyn Fs> {
 797        &self.fs
 798    }
 799
 800    pub fn remote_id(&self) -> Option<u64> {
 801        match self.client_state.as_ref()? {
 802            ProjectClientState::Local { remote_id, .. }
 803            | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 804        }
 805    }
 806
 807    pub fn replica_id(&self) -> ReplicaId {
 808        match &self.client_state {
 809            Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
 810            _ => 0,
 811        }
 812    }
 813
 814    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
 815        if let Some(ProjectClientState::Local { updates_tx, .. }) = &mut self.client_state {
 816            updates_tx
 817                .unbounded_send(LocalProjectUpdate::WorktreesChanged)
 818                .ok();
 819        }
 820        cx.notify();
 821    }
 822
 823    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
 824        &self.collaborators
 825    }
 826
 827    /// Collect all worktrees, including ones that don't appear in the project panel
 828    pub fn worktrees<'a>(
 829        &'a self,
 830        cx: &'a AppContext,
 831    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
 832        self.worktrees
 833            .iter()
 834            .filter_map(move |worktree| worktree.upgrade(cx))
 835    }
 836
 837    /// Collect all user-visible worktrees, the ones that appear in the project panel
 838    pub fn visible_worktrees<'a>(
 839        &'a self,
 840        cx: &'a AppContext,
 841    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
 842        self.worktrees.iter().filter_map(|worktree| {
 843            worktree.upgrade(cx).and_then(|worktree| {
 844                if worktree.read(cx).is_visible() {
 845                    Some(worktree)
 846                } else {
 847                    None
 848                }
 849            })
 850        })
 851    }
 852
 853    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
 854        self.visible_worktrees(cx)
 855            .map(|tree| tree.read(cx).root_name())
 856    }
 857
 858    pub fn worktree_for_id(
 859        &self,
 860        id: WorktreeId,
 861        cx: &AppContext,
 862    ) -> Option<ModelHandle<Worktree>> {
 863        self.worktrees(cx)
 864            .find(|worktree| worktree.read(cx).id() == id)
 865    }
 866
 867    pub fn worktree_for_entry(
 868        &self,
 869        entry_id: ProjectEntryId,
 870        cx: &AppContext,
 871    ) -> Option<ModelHandle<Worktree>> {
 872        self.worktrees(cx)
 873            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 874    }
 875
 876    pub fn worktree_id_for_entry(
 877        &self,
 878        entry_id: ProjectEntryId,
 879        cx: &AppContext,
 880    ) -> Option<WorktreeId> {
 881        self.worktree_for_entry(entry_id, cx)
 882            .map(|worktree| worktree.read(cx).id())
 883    }
 884
 885    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
 886        paths.iter().all(|path| self.contains_path(path, cx))
 887    }
 888
 889    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
 890        for worktree in self.worktrees(cx) {
 891            let worktree = worktree.read(cx).as_local();
 892            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
 893                return true;
 894            }
 895        }
 896        false
 897    }
 898
 899    pub fn create_entry(
 900        &mut self,
 901        project_path: impl Into<ProjectPath>,
 902        is_directory: bool,
 903        cx: &mut ModelContext<Self>,
 904    ) -> Option<Task<Result<Entry>>> {
 905        let project_path = project_path.into();
 906        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 907        if self.is_local() {
 908            Some(worktree.update(cx, |worktree, cx| {
 909                worktree
 910                    .as_local_mut()
 911                    .unwrap()
 912                    .create_entry(project_path.path, is_directory, cx)
 913            }))
 914        } else {
 915            let client = self.client.clone();
 916            let project_id = self.remote_id().unwrap();
 917            Some(cx.spawn_weak(|_, mut cx| async move {
 918                let response = client
 919                    .request(proto::CreateProjectEntry {
 920                        worktree_id: project_path.worktree_id.to_proto(),
 921                        project_id,
 922                        path: project_path.path.to_string_lossy().into(),
 923                        is_directory,
 924                    })
 925                    .await?;
 926                let entry = response
 927                    .entry
 928                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 929                worktree
 930                    .update(&mut cx, |worktree, cx| {
 931                        worktree.as_remote_mut().unwrap().insert_entry(
 932                            entry,
 933                            response.worktree_scan_id as usize,
 934                            cx,
 935                        )
 936                    })
 937                    .await
 938            }))
 939        }
 940    }
 941
 942    pub fn copy_entry(
 943        &mut self,
 944        entry_id: ProjectEntryId,
 945        new_path: impl Into<Arc<Path>>,
 946        cx: &mut ModelContext<Self>,
 947    ) -> Option<Task<Result<Entry>>> {
 948        let worktree = self.worktree_for_entry(entry_id, cx)?;
 949        let new_path = new_path.into();
 950        if self.is_local() {
 951            worktree.update(cx, |worktree, cx| {
 952                worktree
 953                    .as_local_mut()
 954                    .unwrap()
 955                    .copy_entry(entry_id, new_path, cx)
 956            })
 957        } else {
 958            let client = self.client.clone();
 959            let project_id = self.remote_id().unwrap();
 960
 961            Some(cx.spawn_weak(|_, mut cx| async move {
 962                let response = client
 963                    .request(proto::CopyProjectEntry {
 964                        project_id,
 965                        entry_id: entry_id.to_proto(),
 966                        new_path: new_path.to_string_lossy().into(),
 967                    })
 968                    .await?;
 969                let entry = response
 970                    .entry
 971                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 972                worktree
 973                    .update(&mut cx, |worktree, cx| {
 974                        worktree.as_remote_mut().unwrap().insert_entry(
 975                            entry,
 976                            response.worktree_scan_id as usize,
 977                            cx,
 978                        )
 979                    })
 980                    .await
 981            }))
 982        }
 983    }
 984
 985    pub fn rename_entry(
 986        &mut self,
 987        entry_id: ProjectEntryId,
 988        new_path: impl Into<Arc<Path>>,
 989        cx: &mut ModelContext<Self>,
 990    ) -> Option<Task<Result<Entry>>> {
 991        let worktree = self.worktree_for_entry(entry_id, cx)?;
 992        let new_path = new_path.into();
 993        if self.is_local() {
 994            worktree.update(cx, |worktree, cx| {
 995                worktree
 996                    .as_local_mut()
 997                    .unwrap()
 998                    .rename_entry(entry_id, new_path, cx)
 999            })
1000        } else {
1001            let client = self.client.clone();
1002            let project_id = self.remote_id().unwrap();
1003
1004            Some(cx.spawn_weak(|_, mut cx| async move {
1005                let response = client
1006                    .request(proto::RenameProjectEntry {
1007                        project_id,
1008                        entry_id: entry_id.to_proto(),
1009                        new_path: new_path.to_string_lossy().into(),
1010                    })
1011                    .await?;
1012                let entry = response
1013                    .entry
1014                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1015                worktree
1016                    .update(&mut cx, |worktree, cx| {
1017                        worktree.as_remote_mut().unwrap().insert_entry(
1018                            entry,
1019                            response.worktree_scan_id as usize,
1020                            cx,
1021                        )
1022                    })
1023                    .await
1024            }))
1025        }
1026    }
1027
1028    pub fn delete_entry(
1029        &mut self,
1030        entry_id: ProjectEntryId,
1031        cx: &mut ModelContext<Self>,
1032    ) -> Option<Task<Result<()>>> {
1033        let worktree = self.worktree_for_entry(entry_id, cx)?;
1034
1035        cx.emit(Event::DeletedEntry(entry_id));
1036
1037        if self.is_local() {
1038            worktree.update(cx, |worktree, cx| {
1039                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1040            })
1041        } else {
1042            let client = self.client.clone();
1043            let project_id = self.remote_id().unwrap();
1044            Some(cx.spawn_weak(|_, mut cx| async move {
1045                let response = client
1046                    .request(proto::DeleteProjectEntry {
1047                        project_id,
1048                        entry_id: entry_id.to_proto(),
1049                    })
1050                    .await?;
1051                worktree
1052                    .update(&mut cx, move |worktree, cx| {
1053                        worktree.as_remote_mut().unwrap().delete_entry(
1054                            entry_id,
1055                            response.worktree_scan_id as usize,
1056                            cx,
1057                        )
1058                    })
1059                    .await
1060            }))
1061        }
1062    }
1063
1064    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1065        if self.client_state.is_some() {
1066            return Err(anyhow!("project was already shared"));
1067        }
1068        self.client_subscriptions.push(
1069            self.client
1070                .subscribe_to_entity(project_id)?
1071                .set_model(&cx.handle(), &mut cx.to_async()),
1072        );
1073
1074        for open_buffer in self.opened_buffers.values_mut() {
1075            match open_buffer {
1076                OpenBuffer::Strong(_) => {}
1077                OpenBuffer::Weak(buffer) => {
1078                    if let Some(buffer) = buffer.upgrade(cx) {
1079                        *open_buffer = OpenBuffer::Strong(buffer);
1080                    }
1081                }
1082                OpenBuffer::Operations(_) => unreachable!(),
1083            }
1084        }
1085
1086        for worktree_handle in self.worktrees.iter_mut() {
1087            match worktree_handle {
1088                WorktreeHandle::Strong(_) => {}
1089                WorktreeHandle::Weak(worktree) => {
1090                    if let Some(worktree) = worktree.upgrade(cx) {
1091                        *worktree_handle = WorktreeHandle::Strong(worktree);
1092                    }
1093                }
1094            }
1095        }
1096
1097        for (server_id, status) in &self.language_server_statuses {
1098            self.client
1099                .send(proto::StartLanguageServer {
1100                    project_id,
1101                    server: Some(proto::LanguageServer {
1102                        id: server_id.0 as u64,
1103                        name: status.name.clone(),
1104                    }),
1105                })
1106                .log_err();
1107        }
1108
1109        let (updates_tx, mut updates_rx) = mpsc::unbounded();
1110        let client = self.client.clone();
1111        self.client_state = Some(ProjectClientState::Local {
1112            remote_id: project_id,
1113            updates_tx,
1114            _send_updates: cx.spawn_weak(move |this, mut cx| async move {
1115                while let Some(update) = updates_rx.next().await {
1116                    let Some(this) = this.upgrade(&cx) else { break };
1117
1118                    match update {
1119                        LocalProjectUpdate::WorktreesChanged => {
1120                            let worktrees = this
1121                                .read_with(&cx, |this, cx| this.worktrees(cx).collect::<Vec<_>>());
1122                            let update_project = this
1123                                .read_with(&cx, |this, cx| {
1124                                    this.client.request(proto::UpdateProject {
1125                                        project_id,
1126                                        worktrees: this.worktree_metadata_protos(cx),
1127                                    })
1128                                })
1129                                .await;
1130                            if update_project.is_ok() {
1131                                for worktree in worktrees {
1132                                    worktree.update(&mut cx, |worktree, cx| {
1133                                        let worktree = worktree.as_local_mut().unwrap();
1134                                        worktree.share(project_id, cx).detach_and_log_err(cx)
1135                                    });
1136                                }
1137                            }
1138                        }
1139                        LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
1140                            let buffer = this.update(&mut cx, |this, _| {
1141                                let buffer = this.opened_buffers.get(&buffer_id).unwrap();
1142                                let shared_buffers =
1143                                    this.shared_buffers.entry(peer_id).or_default();
1144                                if shared_buffers.insert(buffer_id) {
1145                                    if let OpenBuffer::Strong(buffer) = buffer {
1146                                        Some(buffer.clone())
1147                                    } else {
1148                                        None
1149                                    }
1150                                } else {
1151                                    None
1152                                }
1153                            });
1154
1155                            let Some(buffer) = buffer else { continue };
1156                            let operations =
1157                                buffer.read_with(&cx, |b, cx| b.serialize_ops(None, cx));
1158                            let operations = operations.await;
1159                            let state = buffer.read_with(&cx, |buffer, _| buffer.to_proto());
1160
1161                            let initial_state = proto::CreateBufferForPeer {
1162                                project_id,
1163                                peer_id: Some(peer_id),
1164                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1165                            };
1166                            if client.send(initial_state).log_err().is_some() {
1167                                let client = client.clone();
1168                                cx.background()
1169                                    .spawn(async move {
1170                                        let mut chunks = split_operations(operations).peekable();
1171                                        while let Some(chunk) = chunks.next() {
1172                                            let is_last = chunks.peek().is_none();
1173                                            client.send(proto::CreateBufferForPeer {
1174                                                project_id,
1175                                                peer_id: Some(peer_id),
1176                                                variant: Some(
1177                                                    proto::create_buffer_for_peer::Variant::Chunk(
1178                                                        proto::BufferChunk {
1179                                                            buffer_id,
1180                                                            operations: chunk,
1181                                                            is_last,
1182                                                        },
1183                                                    ),
1184                                                ),
1185                                            })?;
1186                                        }
1187                                        anyhow::Ok(())
1188                                    })
1189                                    .await
1190                                    .log_err();
1191                            }
1192                        }
1193                    }
1194                }
1195            }),
1196        });
1197
1198        self.metadata_changed(cx);
1199        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1200        cx.notify();
1201        Ok(())
1202    }
1203
1204    pub fn reshared(
1205        &mut self,
1206        message: proto::ResharedProject,
1207        cx: &mut ModelContext<Self>,
1208    ) -> Result<()> {
1209        self.shared_buffers.clear();
1210        self.set_collaborators_from_proto(message.collaborators, cx)?;
1211        self.metadata_changed(cx);
1212        Ok(())
1213    }
1214
1215    pub fn rejoined(
1216        &mut self,
1217        message: proto::RejoinedProject,
1218        message_id: u32,
1219        cx: &mut ModelContext<Self>,
1220    ) -> Result<()> {
1221        self.join_project_response_message_id = message_id;
1222        self.set_worktrees_from_proto(message.worktrees, cx)?;
1223        self.set_collaborators_from_proto(message.collaborators, cx)?;
1224        self.language_server_statuses = message
1225            .language_servers
1226            .into_iter()
1227            .map(|server| {
1228                (
1229                    LanguageServerId(server.id as usize),
1230                    LanguageServerStatus {
1231                        name: server.name,
1232                        pending_work: Default::default(),
1233                        has_pending_diagnostic_updates: false,
1234                        progress_tokens: Default::default(),
1235                    },
1236                )
1237            })
1238            .collect();
1239        self.buffer_ordered_messages_tx
1240            .unbounded_send(BufferOrderedMessage::Resync)
1241            .unwrap();
1242        cx.notify();
1243        Ok(())
1244    }
1245
1246    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1247        self.unshare_internal(cx)?;
1248        self.metadata_changed(cx);
1249        cx.notify();
1250        Ok(())
1251    }
1252
1253    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1254        if self.is_remote() {
1255            return Err(anyhow!("attempted to unshare a remote project"));
1256        }
1257
1258        if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1259            self.collaborators.clear();
1260            self.shared_buffers.clear();
1261            self.client_subscriptions.clear();
1262
1263            for worktree_handle in self.worktrees.iter_mut() {
1264                if let WorktreeHandle::Strong(worktree) = worktree_handle {
1265                    let is_visible = worktree.update(cx, |worktree, _| {
1266                        worktree.as_local_mut().unwrap().unshare();
1267                        worktree.is_visible()
1268                    });
1269                    if !is_visible {
1270                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1271                    }
1272                }
1273            }
1274
1275            for open_buffer in self.opened_buffers.values_mut() {
1276                // Wake up any tasks waiting for peers' edits to this buffer.
1277                if let Some(buffer) = open_buffer.upgrade(cx) {
1278                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1279                }
1280
1281                if let OpenBuffer::Strong(buffer) = open_buffer {
1282                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1283                }
1284            }
1285
1286            self.client.send(proto::UnshareProject {
1287                project_id: remote_id,
1288            })?;
1289
1290            Ok(())
1291        } else {
1292            Err(anyhow!("attempted to unshare an unshared project"))
1293        }
1294    }
1295
1296    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1297        self.disconnected_from_host_internal(cx);
1298        cx.emit(Event::DisconnectedFromHost);
1299        cx.notify();
1300    }
1301
1302    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1303        if let Some(ProjectClientState::Remote {
1304            sharing_has_stopped,
1305            ..
1306        }) = &mut self.client_state
1307        {
1308            *sharing_has_stopped = true;
1309
1310            self.collaborators.clear();
1311
1312            for worktree in &self.worktrees {
1313                if let Some(worktree) = worktree.upgrade(cx) {
1314                    worktree.update(cx, |worktree, _| {
1315                        if let Some(worktree) = worktree.as_remote_mut() {
1316                            worktree.disconnected_from_host();
1317                        }
1318                    });
1319                }
1320            }
1321
1322            for open_buffer in self.opened_buffers.values_mut() {
1323                // Wake up any tasks waiting for peers' edits to this buffer.
1324                if let Some(buffer) = open_buffer.upgrade(cx) {
1325                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1326                }
1327
1328                if let OpenBuffer::Strong(buffer) = open_buffer {
1329                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1330                }
1331            }
1332
1333            // Wake up all futures currently waiting on a buffer to get opened,
1334            // to give them a chance to fail now that we've disconnected.
1335            *self.opened_buffer.0.borrow_mut() = ();
1336        }
1337    }
1338
1339    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1340        cx.emit(Event::Closed);
1341    }
1342
1343    pub fn is_read_only(&self) -> bool {
1344        match &self.client_state {
1345            Some(ProjectClientState::Remote {
1346                sharing_has_stopped,
1347                ..
1348            }) => *sharing_has_stopped,
1349            _ => false,
1350        }
1351    }
1352
1353    pub fn is_local(&self) -> bool {
1354        match &self.client_state {
1355            Some(ProjectClientState::Remote { .. }) => false,
1356            _ => true,
1357        }
1358    }
1359
1360    pub fn is_remote(&self) -> bool {
1361        !self.is_local()
1362    }
1363
1364    pub fn create_buffer(
1365        &mut self,
1366        text: &str,
1367        language: Option<Arc<Language>>,
1368        cx: &mut ModelContext<Self>,
1369    ) -> Result<ModelHandle<Buffer>> {
1370        if self.is_remote() {
1371            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1372        }
1373
1374        let buffer = cx.add_model(|cx| {
1375            Buffer::new(self.replica_id(), text, cx)
1376                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1377        });
1378        self.register_buffer(&buffer, cx)?;
1379        Ok(buffer)
1380    }
1381
1382    pub fn open_path(
1383        &mut self,
1384        path: impl Into<ProjectPath>,
1385        cx: &mut ModelContext<Self>,
1386    ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1387        let task = self.open_buffer(path, cx);
1388        cx.spawn_weak(|_, cx| async move {
1389            let buffer = task.await?;
1390            let project_entry_id = buffer
1391                .read_with(&cx, |buffer, cx| {
1392                    File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1393                })
1394                .ok_or_else(|| anyhow!("no project entry"))?;
1395
1396            let buffer: &AnyModelHandle = &buffer;
1397            Ok((project_entry_id, buffer.clone()))
1398        })
1399    }
1400
1401    pub fn open_local_buffer(
1402        &mut self,
1403        abs_path: impl AsRef<Path>,
1404        cx: &mut ModelContext<Self>,
1405    ) -> Task<Result<ModelHandle<Buffer>>> {
1406        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1407            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1408        } else {
1409            Task::ready(Err(anyhow!("no such path")))
1410        }
1411    }
1412
1413    pub fn open_buffer(
1414        &mut self,
1415        path: impl Into<ProjectPath>,
1416        cx: &mut ModelContext<Self>,
1417    ) -> Task<Result<ModelHandle<Buffer>>> {
1418        let project_path = path.into();
1419        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1420            worktree
1421        } else {
1422            return Task::ready(Err(anyhow!("no such worktree")));
1423        };
1424
1425        // If there is already a buffer for the given path, then return it.
1426        let existing_buffer = self.get_open_buffer(&project_path, cx);
1427        if let Some(existing_buffer) = existing_buffer {
1428            return Task::ready(Ok(existing_buffer));
1429        }
1430
1431        let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1432            // If the given path is already being loaded, then wait for that existing
1433            // task to complete and return the same buffer.
1434            hash_map::Entry::Occupied(e) => e.get().clone(),
1435
1436            // Otherwise, record the fact that this path is now being loaded.
1437            hash_map::Entry::Vacant(entry) => {
1438                let (mut tx, rx) = postage::watch::channel();
1439                entry.insert(rx.clone());
1440
1441                let load_buffer = if worktree.read(cx).is_local() {
1442                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1443                } else {
1444                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1445                };
1446
1447                cx.spawn(move |this, mut cx| async move {
1448                    let load_result = load_buffer.await;
1449                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1450                        // Record the fact that the buffer is no longer loading.
1451                        this.loading_buffers_by_path.remove(&project_path);
1452                        let buffer = load_result.map_err(Arc::new)?;
1453                        Ok(buffer)
1454                    }));
1455                })
1456                .detach();
1457                rx
1458            }
1459        };
1460
1461        cx.foreground().spawn(async move {
1462            pump_loading_buffer_reciever(loading_watch)
1463                .await
1464                .map_err(|error| anyhow!("{}", error))
1465        })
1466    }
1467
1468    fn open_local_buffer_internal(
1469        &mut self,
1470        path: &Arc<Path>,
1471        worktree: &ModelHandle<Worktree>,
1472        cx: &mut ModelContext<Self>,
1473    ) -> Task<Result<ModelHandle<Buffer>>> {
1474        let buffer_id = post_inc(&mut self.next_buffer_id);
1475        let load_buffer = worktree.update(cx, |worktree, cx| {
1476            let worktree = worktree.as_local_mut().unwrap();
1477            worktree.load_buffer(buffer_id, path, cx)
1478        });
1479        cx.spawn(|this, mut cx| async move {
1480            let buffer = load_buffer.await?;
1481            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1482            Ok(buffer)
1483        })
1484    }
1485
1486    fn open_remote_buffer_internal(
1487        &mut self,
1488        path: &Arc<Path>,
1489        worktree: &ModelHandle<Worktree>,
1490        cx: &mut ModelContext<Self>,
1491    ) -> Task<Result<ModelHandle<Buffer>>> {
1492        let rpc = self.client.clone();
1493        let project_id = self.remote_id().unwrap();
1494        let remote_worktree_id = worktree.read(cx).id();
1495        let path = path.clone();
1496        let path_string = path.to_string_lossy().to_string();
1497        cx.spawn(|this, mut cx| async move {
1498            let response = rpc
1499                .request(proto::OpenBufferByPath {
1500                    project_id,
1501                    worktree_id: remote_worktree_id.to_proto(),
1502                    path: path_string,
1503                })
1504                .await?;
1505            this.update(&mut cx, |this, cx| {
1506                this.wait_for_remote_buffer(response.buffer_id, cx)
1507            })
1508            .await
1509        })
1510    }
1511
1512    /// LanguageServerName is owned, because it is inserted into a map
1513    fn open_local_buffer_via_lsp(
1514        &mut self,
1515        abs_path: lsp::Url,
1516        language_server_id: LanguageServerId,
1517        language_server_name: LanguageServerName,
1518        cx: &mut ModelContext<Self>,
1519    ) -> Task<Result<ModelHandle<Buffer>>> {
1520        cx.spawn(|this, mut cx| async move {
1521            let abs_path = abs_path
1522                .to_file_path()
1523                .map_err(|_| anyhow!("can't convert URI to path"))?;
1524            let (worktree, relative_path) = if let Some(result) =
1525                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1526            {
1527                result
1528            } else {
1529                let worktree = this
1530                    .update(&mut cx, |this, cx| {
1531                        this.create_local_worktree(&abs_path, false, cx)
1532                    })
1533                    .await?;
1534                this.update(&mut cx, |this, cx| {
1535                    this.language_server_ids.insert(
1536                        (worktree.read(cx).id(), language_server_name),
1537                        language_server_id,
1538                    );
1539                });
1540                (worktree, PathBuf::new())
1541            };
1542
1543            let project_path = ProjectPath {
1544                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1545                path: relative_path.into(),
1546            };
1547            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1548                .await
1549        })
1550    }
1551
1552    pub fn open_buffer_by_id(
1553        &mut self,
1554        id: u64,
1555        cx: &mut ModelContext<Self>,
1556    ) -> Task<Result<ModelHandle<Buffer>>> {
1557        if let Some(buffer) = self.buffer_for_id(id, cx) {
1558            Task::ready(Ok(buffer))
1559        } else if self.is_local() {
1560            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1561        } else if let Some(project_id) = self.remote_id() {
1562            let request = self
1563                .client
1564                .request(proto::OpenBufferById { project_id, id });
1565            cx.spawn(|this, mut cx| async move {
1566                let buffer_id = request.await?.buffer_id;
1567                this.update(&mut cx, |this, cx| {
1568                    this.wait_for_remote_buffer(buffer_id, cx)
1569                })
1570                .await
1571            })
1572        } else {
1573            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1574        }
1575    }
1576
1577    pub fn save_buffers(
1578        &self,
1579        buffers: HashSet<ModelHandle<Buffer>>,
1580        cx: &mut ModelContext<Self>,
1581    ) -> Task<Result<()>> {
1582        cx.spawn(|this, mut cx| async move {
1583            let save_tasks = buffers
1584                .into_iter()
1585                .map(|buffer| this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx)));
1586            try_join_all(save_tasks).await?;
1587            Ok(())
1588        })
1589    }
1590
1591    pub fn save_buffer(
1592        &self,
1593        buffer: ModelHandle<Buffer>,
1594        cx: &mut ModelContext<Self>,
1595    ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1596        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1597            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1598        };
1599        let worktree = file.worktree.clone();
1600        let path = file.path.clone();
1601        worktree.update(cx, |worktree, cx| match worktree {
1602            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1603            Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1604        })
1605    }
1606
1607    pub fn save_buffer_as(
1608        &mut self,
1609        buffer: ModelHandle<Buffer>,
1610        abs_path: PathBuf,
1611        cx: &mut ModelContext<Self>,
1612    ) -> Task<Result<()>> {
1613        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1614        let old_file = File::from_dyn(buffer.read(cx).file())
1615            .filter(|f| f.is_local())
1616            .cloned();
1617        cx.spawn(|this, mut cx| async move {
1618            if let Some(old_file) = &old_file {
1619                this.update(&mut cx, |this, cx| {
1620                    this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
1621                });
1622            }
1623            let (worktree, path) = worktree_task.await?;
1624            worktree
1625                .update(&mut cx, |worktree, cx| match worktree {
1626                    Worktree::Local(worktree) => {
1627                        worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1628                    }
1629                    Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1630                })
1631                .await?;
1632            this.update(&mut cx, |this, cx| {
1633                this.detect_language_for_buffer(&buffer, cx);
1634                this.register_buffer_with_language_servers(&buffer, cx);
1635            });
1636            Ok(())
1637        })
1638    }
1639
1640    pub fn get_open_buffer(
1641        &mut self,
1642        path: &ProjectPath,
1643        cx: &mut ModelContext<Self>,
1644    ) -> Option<ModelHandle<Buffer>> {
1645        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1646        self.opened_buffers.values().find_map(|buffer| {
1647            let buffer = buffer.upgrade(cx)?;
1648            let file = File::from_dyn(buffer.read(cx).file())?;
1649            if file.worktree == worktree && file.path() == &path.path {
1650                Some(buffer)
1651            } else {
1652                None
1653            }
1654        })
1655    }
1656
1657    fn register_buffer(
1658        &mut self,
1659        buffer: &ModelHandle<Buffer>,
1660        cx: &mut ModelContext<Self>,
1661    ) -> Result<()> {
1662        self.request_buffer_diff_recalculation(buffer, cx);
1663        buffer.update(cx, |buffer, _| {
1664            buffer.set_language_registry(self.languages.clone())
1665        });
1666
1667        let remote_id = buffer.read(cx).remote_id();
1668        let is_remote = self.is_remote();
1669        let open_buffer = if is_remote || self.is_shared() {
1670            OpenBuffer::Strong(buffer.clone())
1671        } else {
1672            OpenBuffer::Weak(buffer.downgrade())
1673        };
1674
1675        match self.opened_buffers.entry(remote_id) {
1676            hash_map::Entry::Vacant(entry) => {
1677                entry.insert(open_buffer);
1678            }
1679            hash_map::Entry::Occupied(mut entry) => {
1680                if let OpenBuffer::Operations(operations) = entry.get_mut() {
1681                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
1682                } else if entry.get().upgrade(cx).is_some() {
1683                    if is_remote {
1684                        return Ok(());
1685                    } else {
1686                        debug_panic!("buffer {} was already registered", remote_id);
1687                        Err(anyhow!("buffer {} was already registered", remote_id))?;
1688                    }
1689                }
1690                entry.insert(open_buffer);
1691            }
1692        }
1693        cx.subscribe(buffer, |this, buffer, event, cx| {
1694            this.on_buffer_event(buffer, event, cx);
1695        })
1696        .detach();
1697
1698        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1699            if file.is_local {
1700                self.local_buffer_ids_by_path.insert(
1701                    ProjectPath {
1702                        worktree_id: file.worktree_id(cx),
1703                        path: file.path.clone(),
1704                    },
1705                    remote_id,
1706                );
1707
1708                self.local_buffer_ids_by_entry_id
1709                    .insert(file.entry_id, remote_id);
1710            }
1711        }
1712
1713        self.detect_language_for_buffer(buffer, cx);
1714        self.register_buffer_with_language_servers(buffer, cx);
1715        self.register_buffer_with_copilot(buffer, cx);
1716        cx.observe_release(buffer, |this, buffer, cx| {
1717            if let Some(file) = File::from_dyn(buffer.file()) {
1718                if file.is_local() {
1719                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1720                    for server in this.language_servers_for_buffer(buffer, cx) {
1721                        server
1722                            .1
1723                            .notify::<lsp::notification::DidCloseTextDocument>(
1724                                lsp::DidCloseTextDocumentParams {
1725                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1726                                },
1727                            )
1728                            .log_err();
1729                    }
1730                }
1731            }
1732        })
1733        .detach();
1734
1735        *self.opened_buffer.0.borrow_mut() = ();
1736        Ok(())
1737    }
1738
1739    fn register_buffer_with_language_servers(
1740        &mut self,
1741        buffer_handle: &ModelHandle<Buffer>,
1742        cx: &mut ModelContext<Self>,
1743    ) {
1744        let buffer = buffer_handle.read(cx);
1745        let buffer_id = buffer.remote_id();
1746
1747        if let Some(file) = File::from_dyn(buffer.file()) {
1748            if !file.is_local() {
1749                return;
1750            }
1751
1752            let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1753            let initial_snapshot = buffer.text_snapshot();
1754            let language = buffer.language().cloned();
1755            let worktree_id = file.worktree_id(cx);
1756
1757            if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1758                for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
1759                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
1760                        .log_err();
1761                }
1762            }
1763
1764            if let Some(language) = language {
1765                for adapter in language.lsp_adapters() {
1766                    let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1767                    let server = self
1768                        .language_server_ids
1769                        .get(&(worktree_id, adapter.name.clone()))
1770                        .and_then(|id| self.language_servers.get(id))
1771                        .and_then(|server_state| {
1772                            if let LanguageServerState::Running { server, .. } = server_state {
1773                                Some(server.clone())
1774                            } else {
1775                                None
1776                            }
1777                        });
1778                    let server = match server {
1779                        Some(server) => server,
1780                        None => continue,
1781                    };
1782
1783                    server
1784                        .notify::<lsp::notification::DidOpenTextDocument>(
1785                            lsp::DidOpenTextDocumentParams {
1786                                text_document: lsp::TextDocumentItem::new(
1787                                    uri.clone(),
1788                                    language_id.unwrap_or_default(),
1789                                    0,
1790                                    initial_snapshot.text(),
1791                                ),
1792                            },
1793                        )
1794                        .log_err();
1795
1796                    buffer_handle.update(cx, |buffer, cx| {
1797                        buffer.set_completion_triggers(
1798                            server
1799                                .capabilities()
1800                                .completion_provider
1801                                .as_ref()
1802                                .and_then(|provider| provider.trigger_characters.clone())
1803                                .unwrap_or_default(),
1804                            cx,
1805                        );
1806                    });
1807
1808                    let snapshot = LspBufferSnapshot {
1809                        version: 0,
1810                        snapshot: initial_snapshot.clone(),
1811                    };
1812                    self.buffer_snapshots
1813                        .entry(buffer_id)
1814                        .or_default()
1815                        .insert(server.server_id(), vec![snapshot]);
1816                }
1817            }
1818        }
1819    }
1820
1821    fn unregister_buffer_from_language_servers(
1822        &mut self,
1823        buffer: &ModelHandle<Buffer>,
1824        old_file: &File,
1825        cx: &mut ModelContext<Self>,
1826    ) {
1827        let old_path = match old_file.as_local() {
1828            Some(local) => local.abs_path(cx),
1829            None => return,
1830        };
1831
1832        buffer.update(cx, |buffer, cx| {
1833            let worktree_id = old_file.worktree_id(cx);
1834            let ids = &self.language_server_ids;
1835
1836            let language = buffer.language().cloned();
1837            let adapters = language.iter().flat_map(|language| language.lsp_adapters());
1838            for &server_id in adapters.flat_map(|a| ids.get(&(worktree_id, a.name.clone()))) {
1839                buffer.update_diagnostics(server_id, Default::default(), cx);
1840            }
1841
1842            self.buffer_snapshots.remove(&buffer.remote_id());
1843            let file_url = lsp::Url::from_file_path(old_path).unwrap();
1844            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
1845                language_server
1846                    .notify::<lsp::notification::DidCloseTextDocument>(
1847                        lsp::DidCloseTextDocumentParams {
1848                            text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
1849                        },
1850                    )
1851                    .log_err();
1852            }
1853        });
1854    }
1855
1856    fn register_buffer_with_copilot(
1857        &self,
1858        buffer_handle: &ModelHandle<Buffer>,
1859        cx: &mut ModelContext<Self>,
1860    ) {
1861        if let Some(copilot) = Copilot::global(cx) {
1862            copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
1863        }
1864    }
1865
1866    async fn send_buffer_ordered_messages(
1867        this: WeakModelHandle<Self>,
1868        rx: UnboundedReceiver<BufferOrderedMessage>,
1869        mut cx: AsyncAppContext,
1870    ) -> Option<()> {
1871        const MAX_BATCH_SIZE: usize = 128;
1872
1873        let mut operations_by_buffer_id = HashMap::default();
1874        async fn flush_operations(
1875            this: &ModelHandle<Project>,
1876            operations_by_buffer_id: &mut HashMap<u64, Vec<proto::Operation>>,
1877            needs_resync_with_host: &mut bool,
1878            is_local: bool,
1879            cx: &AsyncAppContext,
1880        ) {
1881            for (buffer_id, operations) in operations_by_buffer_id.drain() {
1882                let request = this.read_with(cx, |this, _| {
1883                    let project_id = this.remote_id()?;
1884                    Some(this.client.request(proto::UpdateBuffer {
1885                        buffer_id,
1886                        project_id,
1887                        operations,
1888                    }))
1889                });
1890                if let Some(request) = request {
1891                    if request.await.is_err() && !is_local {
1892                        *needs_resync_with_host = true;
1893                        break;
1894                    }
1895                }
1896            }
1897        }
1898
1899        let mut needs_resync_with_host = false;
1900        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
1901
1902        while let Some(changes) = changes.next().await {
1903            let this = this.upgrade(&mut cx)?;
1904            let is_local = this.read_with(&cx, |this, _| this.is_local());
1905
1906            for change in changes {
1907                match change {
1908                    BufferOrderedMessage::Operation {
1909                        buffer_id,
1910                        operation,
1911                    } => {
1912                        if needs_resync_with_host {
1913                            continue;
1914                        }
1915
1916                        operations_by_buffer_id
1917                            .entry(buffer_id)
1918                            .or_insert(Vec::new())
1919                            .push(operation);
1920                    }
1921
1922                    BufferOrderedMessage::Resync => {
1923                        operations_by_buffer_id.clear();
1924                        if this
1925                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))
1926                            .await
1927                            .is_ok()
1928                        {
1929                            needs_resync_with_host = false;
1930                        }
1931                    }
1932
1933                    BufferOrderedMessage::LanguageServerUpdate {
1934                        language_server_id,
1935                        message,
1936                    } => {
1937                        flush_operations(
1938                            &this,
1939                            &mut operations_by_buffer_id,
1940                            &mut needs_resync_with_host,
1941                            is_local,
1942                            &cx,
1943                        )
1944                        .await;
1945
1946                        this.read_with(&cx, |this, _| {
1947                            if let Some(project_id) = this.remote_id() {
1948                                this.client
1949                                    .send(proto::UpdateLanguageServer {
1950                                        project_id,
1951                                        language_server_id: language_server_id.0 as u64,
1952                                        variant: Some(message),
1953                                    })
1954                                    .log_err();
1955                            }
1956                        });
1957                    }
1958                }
1959            }
1960
1961            flush_operations(
1962                &this,
1963                &mut operations_by_buffer_id,
1964                &mut needs_resync_with_host,
1965                is_local,
1966                &cx,
1967            )
1968            .await;
1969        }
1970
1971        None
1972    }
1973
1974    fn on_buffer_event(
1975        &mut self,
1976        buffer: ModelHandle<Buffer>,
1977        event: &BufferEvent,
1978        cx: &mut ModelContext<Self>,
1979    ) -> Option<()> {
1980        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
1981            self.request_buffer_diff_recalculation(&buffer, cx);
1982        }
1983
1984        match event {
1985            BufferEvent::Operation(operation) => {
1986                self.buffer_ordered_messages_tx
1987                    .unbounded_send(BufferOrderedMessage::Operation {
1988                        buffer_id: buffer.read(cx).remote_id(),
1989                        operation: language::proto::serialize_operation(operation),
1990                    })
1991                    .ok();
1992            }
1993
1994            BufferEvent::Edited { .. } => {
1995                let buffer = buffer.read(cx);
1996                let file = File::from_dyn(buffer.file())?;
1997                let abs_path = file.as_local()?.abs_path(cx);
1998                let uri = lsp::Url::from_file_path(abs_path).unwrap();
1999                let next_snapshot = buffer.text_snapshot();
2000
2001                let language_servers: Vec<_> = self
2002                    .language_servers_for_buffer(buffer, cx)
2003                    .map(|i| i.1.clone())
2004                    .collect();
2005
2006                for language_server in language_servers {
2007                    let language_server = language_server.clone();
2008
2009                    let buffer_snapshots = self
2010                        .buffer_snapshots
2011                        .get_mut(&buffer.remote_id())
2012                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
2013                    let previous_snapshot = buffer_snapshots.last()?;
2014                    let next_version = previous_snapshot.version + 1;
2015
2016                    let content_changes = buffer
2017                        .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
2018                        .map(|edit| {
2019                            let edit_start = edit.new.start.0;
2020                            let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
2021                            let new_text = next_snapshot
2022                                .text_for_range(edit.new.start.1..edit.new.end.1)
2023                                .collect();
2024                            lsp::TextDocumentContentChangeEvent {
2025                                range: Some(lsp::Range::new(
2026                                    point_to_lsp(edit_start),
2027                                    point_to_lsp(edit_end),
2028                                )),
2029                                range_length: None,
2030                                text: new_text,
2031                            }
2032                        })
2033                        .collect();
2034
2035                    buffer_snapshots.push(LspBufferSnapshot {
2036                        version: next_version,
2037                        snapshot: next_snapshot.clone(),
2038                    });
2039
2040                    language_server
2041                        .notify::<lsp::notification::DidChangeTextDocument>(
2042                            lsp::DidChangeTextDocumentParams {
2043                                text_document: lsp::VersionedTextDocumentIdentifier::new(
2044                                    uri.clone(),
2045                                    next_version,
2046                                ),
2047                                content_changes,
2048                            },
2049                        )
2050                        .log_err();
2051                }
2052            }
2053
2054            BufferEvent::Saved => {
2055                let file = File::from_dyn(buffer.read(cx).file())?;
2056                let worktree_id = file.worktree_id(cx);
2057                let abs_path = file.as_local()?.abs_path(cx);
2058                let text_document = lsp::TextDocumentIdentifier {
2059                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
2060                };
2061
2062                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
2063                    server
2064                        .notify::<lsp::notification::DidSaveTextDocument>(
2065                            lsp::DidSaveTextDocumentParams {
2066                                text_document: text_document.clone(),
2067                                text: None,
2068                            },
2069                        )
2070                        .log_err();
2071                }
2072
2073                let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
2074                for language_server_id in language_server_ids {
2075                    if let Some(LanguageServerState::Running {
2076                        adapter,
2077                        simulate_disk_based_diagnostics_completion,
2078                        ..
2079                    }) = self.language_servers.get_mut(&language_server_id)
2080                    {
2081                        // After saving a buffer using a language server that doesn't provide
2082                        // a disk-based progress token, kick off a timer that will reset every
2083                        // time the buffer is saved. If the timer eventually fires, simulate
2084                        // disk-based diagnostics being finished so that other pieces of UI
2085                        // (e.g., project diagnostics view, diagnostic status bar) can update.
2086                        // We don't emit an event right away because the language server might take
2087                        // some time to publish diagnostics.
2088                        if adapter.disk_based_diagnostics_progress_token.is_none() {
2089                            const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
2090                                Duration::from_secs(1);
2091
2092                            let task = cx.spawn_weak(|this, mut cx| async move {
2093                                cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
2094                                if let Some(this) = this.upgrade(&cx) {
2095                                    this.update(&mut cx, |this, cx| {
2096                                        this.disk_based_diagnostics_finished(
2097                                            language_server_id,
2098                                            cx,
2099                                        );
2100                                        this.buffer_ordered_messages_tx
2101                                            .unbounded_send(
2102                                                BufferOrderedMessage::LanguageServerUpdate {
2103                                                    language_server_id,
2104                                                    message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
2105                                                },
2106                                            )
2107                                            .ok();
2108                                    });
2109                                }
2110                            });
2111                            *simulate_disk_based_diagnostics_completion = Some(task);
2112                        }
2113                    }
2114                }
2115            }
2116
2117            _ => {}
2118        }
2119
2120        None
2121    }
2122
2123    fn request_buffer_diff_recalculation(
2124        &mut self,
2125        buffer: &ModelHandle<Buffer>,
2126        cx: &mut ModelContext<Self>,
2127    ) {
2128        self.buffers_needing_diff.insert(buffer.downgrade());
2129        let first_insertion = self.buffers_needing_diff.len() == 1;
2130
2131        let settings = settings::get::<ProjectSettings>(cx);
2132        let delay = if let Some(delay) = settings.git.gutter_debounce {
2133            delay
2134        } else {
2135            if first_insertion {
2136                let this = cx.weak_handle();
2137                cx.defer(move |cx| {
2138                    if let Some(this) = this.upgrade(cx) {
2139                        this.update(cx, |this, cx| {
2140                            this.recalculate_buffer_diffs(cx).detach();
2141                        });
2142                    }
2143                });
2144            }
2145            return;
2146        };
2147
2148        const MIN_DELAY: u64 = 50;
2149        let delay = delay.max(MIN_DELAY);
2150        let duration = Duration::from_millis(delay);
2151
2152        self.git_diff_debouncer
2153            .fire_new(duration, cx, move |this, cx| {
2154                this.recalculate_buffer_diffs(cx)
2155            });
2156    }
2157
2158    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2159        cx.spawn(|this, mut cx| async move {
2160            let buffers: Vec<_> = this.update(&mut cx, |this, _| {
2161                this.buffers_needing_diff.drain().collect()
2162            });
2163
2164            let tasks: Vec<_> = this.update(&mut cx, |_, cx| {
2165                buffers
2166                    .iter()
2167                    .filter_map(|buffer| {
2168                        let buffer = buffer.upgrade(cx)?;
2169                        buffer.update(cx, |buffer, cx| buffer.git_diff_recalc_2(cx))
2170                    })
2171                    .collect()
2172            });
2173
2174            futures::future::join_all(tasks).await;
2175
2176            this.update(&mut cx, |this, cx| {
2177                if !this.buffers_needing_diff.is_empty() {
2178                    this.recalculate_buffer_diffs(cx).detach();
2179                } else {
2180                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2181                    for buffer in buffers {
2182                        if let Some(buffer) = buffer.upgrade(cx) {
2183                            buffer.update(cx, |_, cx| cx.notify());
2184                        }
2185                    }
2186                }
2187            });
2188        })
2189    }
2190
2191    fn language_servers_for_worktree(
2192        &self,
2193        worktree_id: WorktreeId,
2194    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2195        self.language_server_ids
2196            .iter()
2197            .filter_map(move |((language_server_worktree_id, _), id)| {
2198                if *language_server_worktree_id == worktree_id {
2199                    if let Some(LanguageServerState::Running {
2200                        adapter,
2201                        language,
2202                        server,
2203                        ..
2204                    }) = self.language_servers.get(id)
2205                    {
2206                        return Some((adapter, language, server));
2207                    }
2208                }
2209                None
2210            })
2211    }
2212
2213    fn maintain_buffer_languages(
2214        languages: &LanguageRegistry,
2215        cx: &mut ModelContext<Project>,
2216    ) -> Task<()> {
2217        let mut subscription = languages.subscribe();
2218        cx.spawn_weak(|project, mut cx| async move {
2219            while let Some(()) = subscription.next().await {
2220                if let Some(project) = project.upgrade(&cx) {
2221                    project.update(&mut cx, |project, cx| {
2222                        let mut plain_text_buffers = Vec::new();
2223                        let mut buffers_with_unknown_injections = Vec::new();
2224                        for buffer in project.opened_buffers.values() {
2225                            if let Some(handle) = buffer.upgrade(cx) {
2226                                let buffer = &handle.read(cx);
2227                                if buffer.language().is_none()
2228                                    || buffer.language() == Some(&*language::PLAIN_TEXT)
2229                                {
2230                                    plain_text_buffers.push(handle);
2231                                } else if buffer.contains_unknown_injections() {
2232                                    buffers_with_unknown_injections.push(handle);
2233                                }
2234                            }
2235                        }
2236
2237                        for buffer in plain_text_buffers {
2238                            project.detect_language_for_buffer(&buffer, cx);
2239                            project.register_buffer_with_language_servers(&buffer, cx);
2240                        }
2241
2242                        for buffer in buffers_with_unknown_injections {
2243                            buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2244                        }
2245                    });
2246                }
2247            }
2248        })
2249    }
2250
2251    fn maintain_workspace_config(
2252        languages: Arc<LanguageRegistry>,
2253        cx: &mut ModelContext<Project>,
2254    ) -> Task<()> {
2255        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2256        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2257
2258        let settings_observation = cx.observe_global::<SettingsStore, _>(move |_, _| {
2259            *settings_changed_tx.borrow_mut() = ();
2260        });
2261        cx.spawn_weak(|this, mut cx| async move {
2262            while let Some(_) = settings_changed_rx.next().await {
2263                let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2264                if let Some(this) = this.upgrade(&cx) {
2265                    this.read_with(&cx, |this, _| {
2266                        for server_state in this.language_servers.values() {
2267                            if let LanguageServerState::Running { server, .. } = server_state {
2268                                server
2269                                    .notify::<lsp::notification::DidChangeConfiguration>(
2270                                        lsp::DidChangeConfigurationParams {
2271                                            settings: workspace_config.clone(),
2272                                        },
2273                                    )
2274                                    .ok();
2275                            }
2276                        }
2277                    })
2278                } else {
2279                    break;
2280                }
2281            }
2282
2283            drop(settings_observation);
2284        })
2285    }
2286
2287    fn detect_language_for_buffer(
2288        &mut self,
2289        buffer_handle: &ModelHandle<Buffer>,
2290        cx: &mut ModelContext<Self>,
2291    ) -> Option<()> {
2292        // If the buffer has a language, set it and start the language server if we haven't already.
2293        let buffer = buffer_handle.read(cx);
2294        let full_path = buffer.file()?.full_path(cx);
2295        let content = buffer.as_rope();
2296        let new_language = self
2297            .languages
2298            .language_for_file(&full_path, Some(content))
2299            .now_or_never()?
2300            .ok()?;
2301        self.set_language_for_buffer(buffer_handle, new_language, cx);
2302        None
2303    }
2304
2305    pub fn set_language_for_buffer(
2306        &mut self,
2307        buffer: &ModelHandle<Buffer>,
2308        new_language: Arc<Language>,
2309        cx: &mut ModelContext<Self>,
2310    ) {
2311        buffer.update(cx, |buffer, cx| {
2312            if buffer.language().map_or(true, |old_language| {
2313                !Arc::ptr_eq(old_language, &new_language)
2314            }) {
2315                buffer.set_language(Some(new_language.clone()), cx);
2316            }
2317        });
2318
2319        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2320            if let Some(worktree) = file.worktree.read(cx).as_local() {
2321                let worktree_id = worktree.id();
2322                let worktree_abs_path = worktree.abs_path().clone();
2323                self.start_language_servers(worktree_id, worktree_abs_path, new_language, cx);
2324            }
2325        }
2326    }
2327
2328    fn start_language_servers(
2329        &mut self,
2330        worktree_id: WorktreeId,
2331        worktree_path: Arc<Path>,
2332        language: Arc<Language>,
2333        cx: &mut ModelContext<Self>,
2334    ) {
2335        if !language_settings(Some(&language.name()), cx).enable_language_server {
2336            return;
2337        }
2338
2339        for adapter in language.lsp_adapters() {
2340            let key = (worktree_id, adapter.name.clone());
2341            if self.language_server_ids.contains_key(&key) {
2342                continue;
2343            }
2344
2345            let pending_server = match self.languages.start_language_server(
2346                language.clone(),
2347                adapter.clone(),
2348                worktree_path.clone(),
2349                self.client.http_client(),
2350                cx,
2351            ) {
2352                Some(pending_server) => pending_server,
2353                None => continue,
2354            };
2355
2356            let lsp = settings::get::<ProjectSettings>(cx)
2357                .lsp
2358                .get(&adapter.name.0);
2359            let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2360
2361            let mut initialization_options = adapter.initialization_options.clone();
2362            match (&mut initialization_options, override_options) {
2363                (Some(initialization_options), Some(override_options)) => {
2364                    merge_json_value_into(override_options, initialization_options);
2365                }
2366                (None, override_options) => initialization_options = override_options,
2367                _ => {}
2368            }
2369
2370            let server_id = pending_server.server_id;
2371            let state = self.setup_pending_language_server(
2372                initialization_options,
2373                pending_server,
2374                adapter.clone(),
2375                language.clone(),
2376                key.clone(),
2377                cx,
2378            );
2379            self.language_servers.insert(server_id, state);
2380            self.language_server_ids.insert(key.clone(), server_id);
2381        }
2382    }
2383
2384    fn setup_pending_language_server(
2385        &mut self,
2386        initialization_options: Option<serde_json::Value>,
2387        pending_server: PendingLanguageServer,
2388        adapter: Arc<CachedLspAdapter>,
2389        language: Arc<Language>,
2390        key: (WorktreeId, LanguageServerName),
2391        cx: &mut ModelContext<Project>,
2392    ) -> LanguageServerState {
2393        let server_id = pending_server.server_id;
2394        let languages = self.languages.clone();
2395
2396        LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2397            let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2398            let language_server = pending_server.task.await.log_err()?;
2399            let language_server = language_server
2400                .initialize(initialization_options)
2401                .await
2402                .log_err()?;
2403            let this = this.upgrade(&cx)?;
2404
2405            language_server
2406                .on_notification::<lsp::notification::PublishDiagnostics, _>({
2407                    let this = this.downgrade();
2408                    let adapter = adapter.clone();
2409                    move |mut params, cx| {
2410                        let this = this;
2411                        let adapter = adapter.clone();
2412                        cx.spawn(|mut cx| async move {
2413                            adapter.process_diagnostics(&mut params).await;
2414                            if let Some(this) = this.upgrade(&cx) {
2415                                this.update(&mut cx, |this, cx| {
2416                                    this.update_diagnostics(
2417                                        server_id,
2418                                        params,
2419                                        &adapter.disk_based_diagnostic_sources,
2420                                        cx,
2421                                    )
2422                                    .log_err();
2423                                });
2424                            }
2425                        })
2426                        .detach();
2427                    }
2428                })
2429                .detach();
2430
2431            language_server
2432                .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2433                    let languages = languages.clone();
2434                    move |params, mut cx| {
2435                        let languages = languages.clone();
2436                        async move {
2437                            let workspace_config =
2438                                cx.update(|cx| languages.workspace_configuration(cx)).await;
2439                            Ok(params
2440                                .items
2441                                .into_iter()
2442                                .map(|item| {
2443                                    if let Some(section) = &item.section {
2444                                        workspace_config
2445                                            .get(section)
2446                                            .cloned()
2447                                            .unwrap_or(serde_json::Value::Null)
2448                                    } else {
2449                                        workspace_config.clone()
2450                                    }
2451                                })
2452                                .collect())
2453                        }
2454                    }
2455                })
2456                .detach();
2457
2458            // Even though we don't have handling for these requests, respond to them to
2459            // avoid stalling any language server like `gopls` which waits for a response
2460            // to these requests when initializing.
2461            language_server
2462                .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2463                    let this = this.downgrade();
2464                    move |params, mut cx| async move {
2465                        if let Some(this) = this.upgrade(&cx) {
2466                            this.update(&mut cx, |this, _| {
2467                                if let Some(status) =
2468                                    this.language_server_statuses.get_mut(&server_id)
2469                                {
2470                                    if let lsp::NumberOrString::String(token) = params.token {
2471                                        status.progress_tokens.insert(token);
2472                                    }
2473                                }
2474                            });
2475                        }
2476                        Ok(())
2477                    }
2478                })
2479                .detach();
2480            language_server
2481                .on_request::<lsp::request::RegisterCapability, _, _>({
2482                    let this = this.downgrade();
2483                    move |params, mut cx| async move {
2484                        let this = this
2485                            .upgrade(&cx)
2486                            .ok_or_else(|| anyhow!("project dropped"))?;
2487                        for reg in params.registrations {
2488                            if reg.method == "workspace/didChangeWatchedFiles" {
2489                                if let Some(options) = reg.register_options {
2490                                    let options = serde_json::from_value(options)?;
2491                                    this.update(&mut cx, |this, cx| {
2492                                        this.on_lsp_did_change_watched_files(
2493                                            server_id, options, cx,
2494                                        );
2495                                    });
2496                                }
2497                            }
2498                        }
2499                        Ok(())
2500                    }
2501                })
2502                .detach();
2503
2504            language_server
2505                .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2506                    let this = this.downgrade();
2507                    let adapter = adapter.clone();
2508                    let language_server = language_server.clone();
2509                    move |params, cx| {
2510                        Self::on_lsp_workspace_edit(
2511                            this,
2512                            params,
2513                            server_id,
2514                            adapter.clone(),
2515                            language_server.clone(),
2516                            cx,
2517                        )
2518                    }
2519                })
2520                .detach();
2521
2522            let disk_based_diagnostics_progress_token =
2523                adapter.disk_based_diagnostics_progress_token.clone();
2524
2525            language_server
2526                .on_notification::<lsp::notification::Progress, _>({
2527                    let this = this.downgrade();
2528                    move |params, mut cx| {
2529                        if let Some(this) = this.upgrade(&cx) {
2530                            this.update(&mut cx, |this, cx| {
2531                                this.on_lsp_progress(
2532                                    params,
2533                                    server_id,
2534                                    disk_based_diagnostics_progress_token.clone(),
2535                                    cx,
2536                                );
2537                            });
2538                        }
2539                    }
2540                })
2541                .detach();
2542
2543            language_server
2544                .notify::<lsp::notification::DidChangeConfiguration>(
2545                    lsp::DidChangeConfigurationParams {
2546                        settings: workspace_config,
2547                    },
2548                )
2549                .ok();
2550
2551            this.update(&mut cx, |this, cx| {
2552                // If the language server for this key doesn't match the server id, don't store the
2553                // server. Which will cause it to be dropped, killing the process
2554                if this
2555                    .language_server_ids
2556                    .get(&key)
2557                    .map(|id| id != &server_id)
2558                    .unwrap_or(false)
2559                {
2560                    return None;
2561                }
2562
2563                // Update language_servers collection with Running variant of LanguageServerState
2564                // indicating that the server is up and running and ready
2565                this.language_servers.insert(
2566                    server_id,
2567                    LanguageServerState::Running {
2568                        adapter: adapter.clone(),
2569                        language: language.clone(),
2570                        watched_paths: Default::default(),
2571                        server: language_server.clone(),
2572                        simulate_disk_based_diagnostics_completion: None,
2573                    },
2574                );
2575                this.language_server_statuses.insert(
2576                    server_id,
2577                    LanguageServerStatus {
2578                        name: language_server.name().to_string(),
2579                        pending_work: Default::default(),
2580                        has_pending_diagnostic_updates: false,
2581                        progress_tokens: Default::default(),
2582                    },
2583                );
2584
2585                if let Some(project_id) = this.remote_id() {
2586                    this.client
2587                        .send(proto::StartLanguageServer {
2588                            project_id,
2589                            server: Some(proto::LanguageServer {
2590                                id: server_id.0 as u64,
2591                                name: language_server.name().to_string(),
2592                            }),
2593                        })
2594                        .log_err();
2595                }
2596
2597                // Tell the language server about every open buffer in the worktree that matches the language.
2598                for buffer in this.opened_buffers.values() {
2599                    if let Some(buffer_handle) = buffer.upgrade(cx) {
2600                        let buffer = buffer_handle.read(cx);
2601                        let file = match File::from_dyn(buffer.file()) {
2602                            Some(file) => file,
2603                            None => continue,
2604                        };
2605                        let language = match buffer.language() {
2606                            Some(language) => language,
2607                            None => continue,
2608                        };
2609
2610                        if file.worktree.read(cx).id() != key.0
2611                            || !language.lsp_adapters().iter().any(|a| a.name == key.1)
2612                        {
2613                            continue;
2614                        }
2615
2616                        let file = file.as_local()?;
2617                        let versions = this
2618                            .buffer_snapshots
2619                            .entry(buffer.remote_id())
2620                            .or_default()
2621                            .entry(server_id)
2622                            .or_insert_with(|| {
2623                                vec![LspBufferSnapshot {
2624                                    version: 0,
2625                                    snapshot: buffer.text_snapshot(),
2626                                }]
2627                            });
2628
2629                        let snapshot = versions.last().unwrap();
2630                        let version = snapshot.version;
2631                        let initial_snapshot = &snapshot.snapshot;
2632                        let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2633                        language_server
2634                            .notify::<lsp::notification::DidOpenTextDocument>(
2635                                lsp::DidOpenTextDocumentParams {
2636                                    text_document: lsp::TextDocumentItem::new(
2637                                        uri,
2638                                        adapter
2639                                            .language_ids
2640                                            .get(language.name().as_ref())
2641                                            .cloned()
2642                                            .unwrap_or_default(),
2643                                        version,
2644                                        initial_snapshot.text(),
2645                                    ),
2646                                },
2647                            )
2648                            .log_err()?;
2649                        buffer_handle.update(cx, |buffer, cx| {
2650                            buffer.set_completion_triggers(
2651                                language_server
2652                                    .capabilities()
2653                                    .completion_provider
2654                                    .as_ref()
2655                                    .and_then(|provider| provider.trigger_characters.clone())
2656                                    .unwrap_or_default(),
2657                                cx,
2658                            )
2659                        });
2660                    }
2661                }
2662
2663                cx.notify();
2664                Some(language_server)
2665            })
2666        }))
2667    }
2668
2669    // Returns a list of all of the worktrees which no longer have a language server and the root path
2670    // for the stopped server
2671    fn stop_language_server(
2672        &mut self,
2673        worktree_id: WorktreeId,
2674        adapter_name: LanguageServerName,
2675        cx: &mut ModelContext<Self>,
2676    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2677        let key = (worktree_id, adapter_name);
2678        if let Some(server_id) = self.language_server_ids.remove(&key) {
2679            // Remove other entries for this language server as well
2680            let mut orphaned_worktrees = vec![worktree_id];
2681            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2682            for other_key in other_keys {
2683                if self.language_server_ids.get(&other_key) == Some(&server_id) {
2684                    self.language_server_ids.remove(&other_key);
2685                    orphaned_worktrees.push(other_key.0);
2686                }
2687            }
2688
2689            for buffer in self.opened_buffers.values() {
2690                if let Some(buffer) = buffer.upgrade(cx) {
2691                    buffer.update(cx, |buffer, cx| {
2692                        buffer.update_diagnostics(server_id, Default::default(), cx);
2693                    });
2694                }
2695            }
2696            for worktree in &self.worktrees {
2697                if let Some(worktree) = worktree.upgrade(cx) {
2698                    worktree.update(cx, |worktree, cx| {
2699                        if let Some(worktree) = worktree.as_local_mut() {
2700                            worktree.clear_diagnostics_for_language_server(server_id, cx);
2701                        }
2702                    });
2703                }
2704            }
2705
2706            self.language_server_statuses.remove(&server_id);
2707            cx.notify();
2708
2709            let server_state = self.language_servers.remove(&server_id);
2710            cx.spawn_weak(|this, mut cx| async move {
2711                let mut root_path = None;
2712
2713                let server = match server_state {
2714                    Some(LanguageServerState::Starting(started_language_server)) => {
2715                        started_language_server.await
2716                    }
2717                    Some(LanguageServerState::Running { server, .. }) => Some(server),
2718                    None => None,
2719                };
2720
2721                if let Some(server) = server {
2722                    root_path = Some(server.root_path().clone());
2723                    if let Some(shutdown) = server.shutdown() {
2724                        shutdown.await;
2725                    }
2726                }
2727
2728                if let Some(this) = this.upgrade(&cx) {
2729                    this.update(&mut cx, |this, cx| {
2730                        this.language_server_statuses.remove(&server_id);
2731                        cx.notify();
2732                    });
2733                }
2734
2735                (root_path, orphaned_worktrees)
2736            })
2737        } else {
2738            Task::ready((None, Vec::new()))
2739        }
2740    }
2741
2742    pub fn restart_language_servers_for_buffers(
2743        &mut self,
2744        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2745        cx: &mut ModelContext<Self>,
2746    ) -> Option<()> {
2747        let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, Arc<Language>)> = buffers
2748            .into_iter()
2749            .filter_map(|buffer| {
2750                let buffer = buffer.read(cx);
2751                let file = File::from_dyn(buffer.file())?;
2752                let worktree = file.worktree.read(cx).as_local()?;
2753                let full_path = file.full_path(cx);
2754                let language = self
2755                    .languages
2756                    .language_for_file(&full_path, Some(buffer.as_rope()))
2757                    .now_or_never()?
2758                    .ok()?;
2759                Some((worktree.id(), worktree.abs_path().clone(), language))
2760            })
2761            .collect();
2762        for (worktree_id, worktree_abs_path, language) in language_server_lookup_info {
2763            self.restart_language_servers(worktree_id, worktree_abs_path, language, cx);
2764        }
2765
2766        None
2767    }
2768
2769    // TODO This will break in the case where the adapter's root paths and worktrees are not equal
2770    fn restart_language_servers(
2771        &mut self,
2772        worktree_id: WorktreeId,
2773        fallback_path: Arc<Path>,
2774        language: Arc<Language>,
2775        cx: &mut ModelContext<Self>,
2776    ) {
2777        let mut stops = Vec::new();
2778        for adapter in language.lsp_adapters() {
2779            stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
2780        }
2781
2782        if stops.is_empty() {
2783            return;
2784        }
2785        let mut stops = stops.into_iter();
2786
2787        cx.spawn_weak(|this, mut cx| async move {
2788            let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
2789            for stop in stops {
2790                let (_, worktrees) = stop.await;
2791                orphaned_worktrees.extend_from_slice(&worktrees);
2792            }
2793
2794            let this = match this.upgrade(&cx) {
2795                Some(this) => this,
2796                None => return,
2797            };
2798
2799            this.update(&mut cx, |this, cx| {
2800                // Attempt to restart using original server path. Fallback to passed in
2801                // path if we could not retrieve the root path
2802                let root_path = original_root_path
2803                    .map(|path_buf| Arc::from(path_buf.as_path()))
2804                    .unwrap_or(fallback_path);
2805
2806                this.start_language_servers(worktree_id, root_path, language.clone(), cx);
2807
2808                // Lookup new server ids and set them for each of the orphaned worktrees
2809                for adapter in language.lsp_adapters() {
2810                    if let Some(new_server_id) = this
2811                        .language_server_ids
2812                        .get(&(worktree_id, adapter.name.clone()))
2813                        .cloned()
2814                    {
2815                        for &orphaned_worktree in &orphaned_worktrees {
2816                            this.language_server_ids
2817                                .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
2818                        }
2819                    }
2820                }
2821            });
2822        })
2823        .detach();
2824    }
2825
2826    fn on_lsp_progress(
2827        &mut self,
2828        progress: lsp::ProgressParams,
2829        language_server_id: LanguageServerId,
2830        disk_based_diagnostics_progress_token: Option<String>,
2831        cx: &mut ModelContext<Self>,
2832    ) {
2833        let token = match progress.token {
2834            lsp::NumberOrString::String(token) => token,
2835            lsp::NumberOrString::Number(token) => {
2836                log::info!("skipping numeric progress token {}", token);
2837                return;
2838            }
2839        };
2840        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2841        let language_server_status =
2842            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2843                status
2844            } else {
2845                return;
2846            };
2847
2848        if !language_server_status.progress_tokens.contains(&token) {
2849            return;
2850        }
2851
2852        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
2853            .as_ref()
2854            .map_or(false, |disk_based_token| {
2855                token.starts_with(disk_based_token)
2856            });
2857
2858        match progress {
2859            lsp::WorkDoneProgress::Begin(report) => {
2860                if is_disk_based_diagnostics_progress {
2861                    language_server_status.has_pending_diagnostic_updates = true;
2862                    self.disk_based_diagnostics_started(language_server_id, cx);
2863                    self.buffer_ordered_messages_tx
2864                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2865                            language_server_id,
2866                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
2867                        })
2868                        .ok();
2869                } else {
2870                    self.on_lsp_work_start(
2871                        language_server_id,
2872                        token.clone(),
2873                        LanguageServerProgress {
2874                            message: report.message.clone(),
2875                            percentage: report.percentage.map(|p| p as usize),
2876                            last_update_at: Instant::now(),
2877                        },
2878                        cx,
2879                    );
2880                    self.buffer_ordered_messages_tx
2881                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2882                            language_server_id,
2883                            message: proto::update_language_server::Variant::WorkStart(
2884                                proto::LspWorkStart {
2885                                    token,
2886                                    message: report.message,
2887                                    percentage: report.percentage.map(|p| p as u32),
2888                                },
2889                            ),
2890                        })
2891                        .ok();
2892                }
2893            }
2894            lsp::WorkDoneProgress::Report(report) => {
2895                if !is_disk_based_diagnostics_progress {
2896                    self.on_lsp_work_progress(
2897                        language_server_id,
2898                        token.clone(),
2899                        LanguageServerProgress {
2900                            message: report.message.clone(),
2901                            percentage: report.percentage.map(|p| p as usize),
2902                            last_update_at: Instant::now(),
2903                        },
2904                        cx,
2905                    );
2906                    self.buffer_ordered_messages_tx
2907                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2908                            language_server_id,
2909                            message: proto::update_language_server::Variant::WorkProgress(
2910                                proto::LspWorkProgress {
2911                                    token,
2912                                    message: report.message,
2913                                    percentage: report.percentage.map(|p| p as u32),
2914                                },
2915                            ),
2916                        })
2917                        .ok();
2918                }
2919            }
2920            lsp::WorkDoneProgress::End(_) => {
2921                language_server_status.progress_tokens.remove(&token);
2922
2923                if is_disk_based_diagnostics_progress {
2924                    language_server_status.has_pending_diagnostic_updates = false;
2925                    self.disk_based_diagnostics_finished(language_server_id, cx);
2926                    self.buffer_ordered_messages_tx
2927                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2928                            language_server_id,
2929                            message:
2930                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2931                                    Default::default(),
2932                                ),
2933                        })
2934                        .ok();
2935                } else {
2936                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
2937                    self.buffer_ordered_messages_tx
2938                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
2939                            language_server_id,
2940                            message: proto::update_language_server::Variant::WorkEnd(
2941                                proto::LspWorkEnd { token },
2942                            ),
2943                        })
2944                        .ok();
2945                }
2946            }
2947        }
2948    }
2949
2950    fn on_lsp_work_start(
2951        &mut self,
2952        language_server_id: LanguageServerId,
2953        token: String,
2954        progress: LanguageServerProgress,
2955        cx: &mut ModelContext<Self>,
2956    ) {
2957        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2958            status.pending_work.insert(token, progress);
2959            cx.notify();
2960        }
2961    }
2962
2963    fn on_lsp_work_progress(
2964        &mut self,
2965        language_server_id: LanguageServerId,
2966        token: String,
2967        progress: LanguageServerProgress,
2968        cx: &mut ModelContext<Self>,
2969    ) {
2970        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2971            let entry = status
2972                .pending_work
2973                .entry(token)
2974                .or_insert(LanguageServerProgress {
2975                    message: Default::default(),
2976                    percentage: Default::default(),
2977                    last_update_at: progress.last_update_at,
2978                });
2979            if progress.message.is_some() {
2980                entry.message = progress.message;
2981            }
2982            if progress.percentage.is_some() {
2983                entry.percentage = progress.percentage;
2984            }
2985            entry.last_update_at = progress.last_update_at;
2986            cx.notify();
2987        }
2988    }
2989
2990    fn on_lsp_work_end(
2991        &mut self,
2992        language_server_id: LanguageServerId,
2993        token: String,
2994        cx: &mut ModelContext<Self>,
2995    ) {
2996        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2997            status.pending_work.remove(&token);
2998            cx.notify();
2999        }
3000    }
3001
3002    fn on_lsp_did_change_watched_files(
3003        &mut self,
3004        language_server_id: LanguageServerId,
3005        params: DidChangeWatchedFilesRegistrationOptions,
3006        cx: &mut ModelContext<Self>,
3007    ) {
3008        if let Some(LanguageServerState::Running { watched_paths, .. }) =
3009            self.language_servers.get_mut(&language_server_id)
3010        {
3011            let mut builders = HashMap::default();
3012            for watcher in params.watchers {
3013                for worktree in &self.worktrees {
3014                    if let Some(worktree) = worktree.upgrade(cx) {
3015                        let worktree = worktree.read(cx);
3016                        if let Some(abs_path) = worktree.abs_path().to_str() {
3017                            if let Some(suffix) = watcher
3018                                .glob_pattern
3019                                .strip_prefix(abs_path)
3020                                .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR))
3021                            {
3022                                if let Some(glob) = Glob::new(suffix).log_err() {
3023                                    builders
3024                                        .entry(worktree.id())
3025                                        .or_insert_with(|| GlobSetBuilder::new())
3026                                        .add(glob);
3027                                }
3028                                break;
3029                            }
3030                        }
3031                    }
3032                }
3033            }
3034
3035            watched_paths.clear();
3036            for (worktree_id, builder) in builders {
3037                if let Ok(globset) = builder.build() {
3038                    watched_paths.insert(worktree_id, globset);
3039                }
3040            }
3041
3042            cx.notify();
3043        }
3044    }
3045
3046    async fn on_lsp_workspace_edit(
3047        this: WeakModelHandle<Self>,
3048        params: lsp::ApplyWorkspaceEditParams,
3049        server_id: LanguageServerId,
3050        adapter: Arc<CachedLspAdapter>,
3051        language_server: Arc<LanguageServer>,
3052        mut cx: AsyncAppContext,
3053    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3054        let this = this
3055            .upgrade(&cx)
3056            .ok_or_else(|| anyhow!("project project closed"))?;
3057        let transaction = Self::deserialize_workspace_edit(
3058            this.clone(),
3059            params.edit,
3060            true,
3061            adapter.clone(),
3062            language_server.clone(),
3063            &mut cx,
3064        )
3065        .await
3066        .log_err();
3067        this.update(&mut cx, |this, _| {
3068            if let Some(transaction) = transaction {
3069                this.last_workspace_edits_by_language_server
3070                    .insert(server_id, transaction);
3071            }
3072        });
3073        Ok(lsp::ApplyWorkspaceEditResponse {
3074            applied: true,
3075            failed_change: None,
3076            failure_reason: None,
3077        })
3078    }
3079
3080    pub fn language_server_statuses(
3081        &self,
3082    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3083        self.language_server_statuses.values()
3084    }
3085
3086    pub fn update_diagnostics(
3087        &mut self,
3088        language_server_id: LanguageServerId,
3089        mut params: lsp::PublishDiagnosticsParams,
3090        disk_based_sources: &[String],
3091        cx: &mut ModelContext<Self>,
3092    ) -> Result<()> {
3093        let abs_path = params
3094            .uri
3095            .to_file_path()
3096            .map_err(|_| anyhow!("URI is not a file"))?;
3097        let mut diagnostics = Vec::default();
3098        let mut primary_diagnostic_group_ids = HashMap::default();
3099        let mut sources_by_group_id = HashMap::default();
3100        let mut supporting_diagnostics = HashMap::default();
3101
3102        // Ensure that primary diagnostics are always the most severe
3103        params.diagnostics.sort_by_key(|item| item.severity);
3104
3105        for diagnostic in &params.diagnostics {
3106            let source = diagnostic.source.as_ref();
3107            let code = diagnostic.code.as_ref().map(|code| match code {
3108                lsp::NumberOrString::Number(code) => code.to_string(),
3109                lsp::NumberOrString::String(code) => code.clone(),
3110            });
3111            let range = range_from_lsp(diagnostic.range);
3112            let is_supporting = diagnostic
3113                .related_information
3114                .as_ref()
3115                .map_or(false, |infos| {
3116                    infos.iter().any(|info| {
3117                        primary_diagnostic_group_ids.contains_key(&(
3118                            source,
3119                            code.clone(),
3120                            range_from_lsp(info.location.range),
3121                        ))
3122                    })
3123                });
3124
3125            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3126                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3127            });
3128
3129            if is_supporting {
3130                supporting_diagnostics.insert(
3131                    (source, code.clone(), range),
3132                    (diagnostic.severity, is_unnecessary),
3133                );
3134            } else {
3135                let group_id = post_inc(&mut self.next_diagnostic_group_id);
3136                let is_disk_based =
3137                    source.map_or(false, |source| disk_based_sources.contains(source));
3138
3139                sources_by_group_id.insert(group_id, source);
3140                primary_diagnostic_group_ids
3141                    .insert((source, code.clone(), range.clone()), group_id);
3142
3143                diagnostics.push(DiagnosticEntry {
3144                    range,
3145                    diagnostic: Diagnostic {
3146                        source: diagnostic.source.clone(),
3147                        code: code.clone(),
3148                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3149                        message: diagnostic.message.clone(),
3150                        group_id,
3151                        is_primary: true,
3152                        is_valid: true,
3153                        is_disk_based,
3154                        is_unnecessary,
3155                    },
3156                });
3157                if let Some(infos) = &diagnostic.related_information {
3158                    for info in infos {
3159                        if info.location.uri == params.uri && !info.message.is_empty() {
3160                            let range = range_from_lsp(info.location.range);
3161                            diagnostics.push(DiagnosticEntry {
3162                                range,
3163                                diagnostic: Diagnostic {
3164                                    source: diagnostic.source.clone(),
3165                                    code: code.clone(),
3166                                    severity: DiagnosticSeverity::INFORMATION,
3167                                    message: info.message.clone(),
3168                                    group_id,
3169                                    is_primary: false,
3170                                    is_valid: true,
3171                                    is_disk_based,
3172                                    is_unnecessary: false,
3173                                },
3174                            });
3175                        }
3176                    }
3177                }
3178            }
3179        }
3180
3181        for entry in &mut diagnostics {
3182            let diagnostic = &mut entry.diagnostic;
3183            if !diagnostic.is_primary {
3184                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3185                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3186                    source,
3187                    diagnostic.code.clone(),
3188                    entry.range.clone(),
3189                )) {
3190                    if let Some(severity) = severity {
3191                        diagnostic.severity = severity;
3192                    }
3193                    diagnostic.is_unnecessary = is_unnecessary;
3194                }
3195            }
3196        }
3197
3198        self.update_diagnostic_entries(
3199            language_server_id,
3200            abs_path,
3201            params.version,
3202            diagnostics,
3203            cx,
3204        )?;
3205        Ok(())
3206    }
3207
3208    pub fn update_diagnostic_entries(
3209        &mut self,
3210        server_id: LanguageServerId,
3211        abs_path: PathBuf,
3212        version: Option<i32>,
3213        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3214        cx: &mut ModelContext<Project>,
3215    ) -> Result<(), anyhow::Error> {
3216        let (worktree, relative_path) = self
3217            .find_local_worktree(&abs_path, cx)
3218            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
3219
3220        let project_path = ProjectPath {
3221            worktree_id: worktree.read(cx).id(),
3222            path: relative_path.into(),
3223        };
3224
3225        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3226            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3227        }
3228
3229        let updated = worktree.update(cx, |worktree, cx| {
3230            worktree
3231                .as_local_mut()
3232                .ok_or_else(|| anyhow!("not a local worktree"))?
3233                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3234        })?;
3235        if updated {
3236            cx.emit(Event::DiagnosticsUpdated {
3237                language_server_id: server_id,
3238                path: project_path,
3239            });
3240        }
3241        Ok(())
3242    }
3243
3244    fn update_buffer_diagnostics(
3245        &mut self,
3246        buffer: &ModelHandle<Buffer>,
3247        server_id: LanguageServerId,
3248        version: Option<i32>,
3249        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3250        cx: &mut ModelContext<Self>,
3251    ) -> Result<()> {
3252        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3253            Ordering::Equal
3254                .then_with(|| b.is_primary.cmp(&a.is_primary))
3255                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3256                .then_with(|| a.severity.cmp(&b.severity))
3257                .then_with(|| a.message.cmp(&b.message))
3258        }
3259
3260        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3261
3262        diagnostics.sort_unstable_by(|a, b| {
3263            Ordering::Equal
3264                .then_with(|| a.range.start.cmp(&b.range.start))
3265                .then_with(|| b.range.end.cmp(&a.range.end))
3266                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3267        });
3268
3269        let mut sanitized_diagnostics = Vec::new();
3270        let edits_since_save = Patch::new(
3271            snapshot
3272                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3273                .collect(),
3274        );
3275        for entry in diagnostics {
3276            let start;
3277            let end;
3278            if entry.diagnostic.is_disk_based {
3279                // Some diagnostics are based on files on disk instead of buffers'
3280                // current contents. Adjust these diagnostics' ranges to reflect
3281                // any unsaved edits.
3282                start = edits_since_save.old_to_new(entry.range.start);
3283                end = edits_since_save.old_to_new(entry.range.end);
3284            } else {
3285                start = entry.range.start;
3286                end = entry.range.end;
3287            }
3288
3289            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3290                ..snapshot.clip_point_utf16(end, Bias::Right);
3291
3292            // Expand empty ranges by one codepoint
3293            if range.start == range.end {
3294                // This will be go to the next boundary when being clipped
3295                range.end.column += 1;
3296                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3297                if range.start == range.end && range.end.column > 0 {
3298                    range.start.column -= 1;
3299                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3300                }
3301            }
3302
3303            sanitized_diagnostics.push(DiagnosticEntry {
3304                range,
3305                diagnostic: entry.diagnostic,
3306            });
3307        }
3308        drop(edits_since_save);
3309
3310        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
3311        buffer.update(cx, |buffer, cx| {
3312            buffer.update_diagnostics(server_id, set, cx)
3313        });
3314        Ok(())
3315    }
3316
3317    pub fn reload_buffers(
3318        &self,
3319        buffers: HashSet<ModelHandle<Buffer>>,
3320        push_to_history: bool,
3321        cx: &mut ModelContext<Self>,
3322    ) -> Task<Result<ProjectTransaction>> {
3323        let mut local_buffers = Vec::new();
3324        let mut remote_buffers = None;
3325        for buffer_handle in buffers {
3326            let buffer = buffer_handle.read(cx);
3327            if buffer.is_dirty() {
3328                if let Some(file) = File::from_dyn(buffer.file()) {
3329                    if file.is_local() {
3330                        local_buffers.push(buffer_handle);
3331                    } else {
3332                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3333                    }
3334                }
3335            }
3336        }
3337
3338        let remote_buffers = self.remote_id().zip(remote_buffers);
3339        let client = self.client.clone();
3340
3341        cx.spawn(|this, mut cx| async move {
3342            let mut project_transaction = ProjectTransaction::default();
3343
3344            if let Some((project_id, remote_buffers)) = remote_buffers {
3345                let response = client
3346                    .request(proto::ReloadBuffers {
3347                        project_id,
3348                        buffer_ids: remote_buffers
3349                            .iter()
3350                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3351                            .collect(),
3352                    })
3353                    .await?
3354                    .transaction
3355                    .ok_or_else(|| anyhow!("missing transaction"))?;
3356                project_transaction = this
3357                    .update(&mut cx, |this, cx| {
3358                        this.deserialize_project_transaction(response, push_to_history, cx)
3359                    })
3360                    .await?;
3361            }
3362
3363            for buffer in local_buffers {
3364                let transaction = buffer
3365                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
3366                    .await?;
3367                buffer.update(&mut cx, |buffer, cx| {
3368                    if let Some(transaction) = transaction {
3369                        if !push_to_history {
3370                            buffer.forget_transaction(transaction.id);
3371                        }
3372                        project_transaction.0.insert(cx.handle(), transaction);
3373                    }
3374                });
3375            }
3376
3377            Ok(project_transaction)
3378        })
3379    }
3380
3381    pub fn format(
3382        &self,
3383        buffers: HashSet<ModelHandle<Buffer>>,
3384        push_to_history: bool,
3385        trigger: FormatTrigger,
3386        cx: &mut ModelContext<Project>,
3387    ) -> Task<Result<ProjectTransaction>> {
3388        if self.is_local() {
3389            let mut buffers_with_paths_and_servers = buffers
3390                .into_iter()
3391                .filter_map(|buffer_handle| {
3392                    let buffer = buffer_handle.read(cx);
3393                    let file = File::from_dyn(buffer.file())?;
3394                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3395                    let server = self
3396                        .primary_language_servers_for_buffer(buffer, cx)
3397                        .map(|s| s.1.clone());
3398                    Some((buffer_handle, buffer_abs_path, server))
3399                })
3400                .collect::<Vec<_>>();
3401
3402            cx.spawn(|this, mut cx| async move {
3403                // Do not allow multiple concurrent formatting requests for the
3404                // same buffer.
3405                this.update(&mut cx, |this, cx| {
3406                    buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
3407                        this.buffers_being_formatted
3408                            .insert(buffer.read(cx).remote_id())
3409                    });
3410                });
3411
3412                let _cleanup = defer({
3413                    let this = this.clone();
3414                    let mut cx = cx.clone();
3415                    let buffers = &buffers_with_paths_and_servers;
3416                    move || {
3417                        this.update(&mut cx, |this, cx| {
3418                            for (buffer, _, _) in buffers {
3419                                this.buffers_being_formatted
3420                                    .remove(&buffer.read(cx).remote_id());
3421                            }
3422                        });
3423                    }
3424                });
3425
3426                let mut project_transaction = ProjectTransaction::default();
3427                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3428                    let settings = buffer.read_with(&cx, |buffer, cx| {
3429                        let language_name = buffer.language().map(|language| language.name());
3430                        language_settings(language_name.as_deref(), cx).clone()
3431                    });
3432
3433                    let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
3434                    let ensure_final_newline = settings.ensure_final_newline_on_save;
3435                    let format_on_save = settings.format_on_save.clone();
3436                    let formatter = settings.formatter.clone();
3437                    let tab_size = settings.tab_size;
3438
3439                    // First, format buffer's whitespace according to the settings.
3440                    let trailing_whitespace_diff = if remove_trailing_whitespace {
3441                        Some(
3442                            buffer
3443                                .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3444                                .await,
3445                        )
3446                    } else {
3447                        None
3448                    };
3449                    let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3450                        buffer.finalize_last_transaction();
3451                        buffer.start_transaction();
3452                        if let Some(diff) = trailing_whitespace_diff {
3453                            buffer.apply_diff(diff, cx);
3454                        }
3455                        if ensure_final_newline {
3456                            buffer.ensure_final_newline(cx);
3457                        }
3458                        buffer.end_transaction(cx)
3459                    });
3460
3461                    // Currently, formatting operations are represented differently depending on
3462                    // whether they come from a language server or an external command.
3463                    enum FormatOperation {
3464                        Lsp(Vec<(Range<Anchor>, String)>),
3465                        External(Diff),
3466                    }
3467
3468                    // Apply language-specific formatting using either a language server
3469                    // or external command.
3470                    let mut format_operation = None;
3471                    match (formatter, format_on_save) {
3472                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3473
3474                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3475                        | (_, FormatOnSave::LanguageServer) => {
3476                            if let Some((language_server, buffer_abs_path)) =
3477                                language_server.as_ref().zip(buffer_abs_path.as_ref())
3478                            {
3479                                format_operation = Some(FormatOperation::Lsp(
3480                                    Self::format_via_lsp(
3481                                        &this,
3482                                        &buffer,
3483                                        buffer_abs_path,
3484                                        &language_server,
3485                                        tab_size,
3486                                        &mut cx,
3487                                    )
3488                                    .await
3489                                    .context("failed to format via language server")?,
3490                                ));
3491                            }
3492                        }
3493
3494                        (
3495                            Formatter::External { command, arguments },
3496                            FormatOnSave::On | FormatOnSave::Off,
3497                        )
3498                        | (_, FormatOnSave::External { command, arguments }) => {
3499                            if let Some(buffer_abs_path) = buffer_abs_path {
3500                                format_operation = Self::format_via_external_command(
3501                                    &buffer,
3502                                    &buffer_abs_path,
3503                                    &command,
3504                                    &arguments,
3505                                    &mut cx,
3506                                )
3507                                .await
3508                                .context(format!(
3509                                    "failed to format via external command {:?}",
3510                                    command
3511                                ))?
3512                                .map(FormatOperation::External);
3513                            }
3514                        }
3515                    };
3516
3517                    buffer.update(&mut cx, |b, cx| {
3518                        // If the buffer had its whitespace formatted and was edited while the language-specific
3519                        // formatting was being computed, avoid applying the language-specific formatting, because
3520                        // it can't be grouped with the whitespace formatting in the undo history.
3521                        if let Some(transaction_id) = whitespace_transaction_id {
3522                            if b.peek_undo_stack()
3523                                .map_or(true, |e| e.transaction_id() != transaction_id)
3524                            {
3525                                format_operation.take();
3526                            }
3527                        }
3528
3529                        // Apply any language-specific formatting, and group the two formatting operations
3530                        // in the buffer's undo history.
3531                        if let Some(operation) = format_operation {
3532                            match operation {
3533                                FormatOperation::Lsp(edits) => {
3534                                    b.edit(edits, None, cx);
3535                                }
3536                                FormatOperation::External(diff) => {
3537                                    b.apply_diff(diff, cx);
3538                                }
3539                            }
3540
3541                            if let Some(transaction_id) = whitespace_transaction_id {
3542                                b.group_until_transaction(transaction_id);
3543                            }
3544                        }
3545
3546                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
3547                            if !push_to_history {
3548                                b.forget_transaction(transaction.id);
3549                            }
3550                            project_transaction.0.insert(buffer.clone(), transaction);
3551                        }
3552                    });
3553                }
3554
3555                Ok(project_transaction)
3556            })
3557        } else {
3558            let remote_id = self.remote_id();
3559            let client = self.client.clone();
3560            cx.spawn(|this, mut cx| async move {
3561                let mut project_transaction = ProjectTransaction::default();
3562                if let Some(project_id) = remote_id {
3563                    let response = client
3564                        .request(proto::FormatBuffers {
3565                            project_id,
3566                            trigger: trigger as i32,
3567                            buffer_ids: buffers
3568                                .iter()
3569                                .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3570                                .collect(),
3571                        })
3572                        .await?
3573                        .transaction
3574                        .ok_or_else(|| anyhow!("missing transaction"))?;
3575                    project_transaction = this
3576                        .update(&mut cx, |this, cx| {
3577                            this.deserialize_project_transaction(response, push_to_history, cx)
3578                        })
3579                        .await?;
3580                }
3581                Ok(project_transaction)
3582            })
3583        }
3584    }
3585
3586    async fn format_via_lsp(
3587        this: &ModelHandle<Self>,
3588        buffer: &ModelHandle<Buffer>,
3589        abs_path: &Path,
3590        language_server: &Arc<LanguageServer>,
3591        tab_size: NonZeroU32,
3592        cx: &mut AsyncAppContext,
3593    ) -> Result<Vec<(Range<Anchor>, String)>> {
3594        let text_document =
3595            lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3596        let capabilities = &language_server.capabilities();
3597        let lsp_edits = if capabilities
3598            .document_formatting_provider
3599            .as_ref()
3600            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3601        {
3602            language_server
3603                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3604                    text_document,
3605                    options: lsp_command::lsp_formatting_options(tab_size.get()),
3606                    work_done_progress_params: Default::default(),
3607                })
3608                .await?
3609        } else if capabilities
3610            .document_range_formatting_provider
3611            .as_ref()
3612            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3613        {
3614            let buffer_start = lsp::Position::new(0, 0);
3615            let buffer_end =
3616                buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3617            language_server
3618                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3619                    text_document,
3620                    range: lsp::Range::new(buffer_start, buffer_end),
3621                    options: lsp_command::lsp_formatting_options(tab_size.get()),
3622                    work_done_progress_params: Default::default(),
3623                })
3624                .await?
3625        } else {
3626            None
3627        };
3628
3629        if let Some(lsp_edits) = lsp_edits {
3630            this.update(cx, |this, cx| {
3631                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
3632            })
3633            .await
3634        } else {
3635            Ok(Default::default())
3636        }
3637    }
3638
3639    async fn format_via_external_command(
3640        buffer: &ModelHandle<Buffer>,
3641        buffer_abs_path: &Path,
3642        command: &str,
3643        arguments: &[String],
3644        cx: &mut AsyncAppContext,
3645    ) -> Result<Option<Diff>> {
3646        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3647            let file = File::from_dyn(buffer.file())?;
3648            let worktree = file.worktree.read(cx).as_local()?;
3649            let mut worktree_path = worktree.abs_path().to_path_buf();
3650            if worktree.root_entry()?.is_file() {
3651                worktree_path.pop();
3652            }
3653            Some(worktree_path)
3654        });
3655
3656        if let Some(working_dir_path) = working_dir_path {
3657            let mut child =
3658                smol::process::Command::new(command)
3659                    .args(arguments.iter().map(|arg| {
3660                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3661                    }))
3662                    .current_dir(&working_dir_path)
3663                    .stdin(smol::process::Stdio::piped())
3664                    .stdout(smol::process::Stdio::piped())
3665                    .stderr(smol::process::Stdio::piped())
3666                    .spawn()?;
3667            let stdin = child
3668                .stdin
3669                .as_mut()
3670                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3671            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3672            for chunk in text.chunks() {
3673                stdin.write_all(chunk.as_bytes()).await?;
3674            }
3675            stdin.flush().await?;
3676
3677            let output = child.output().await?;
3678            if !output.status.success() {
3679                return Err(anyhow!(
3680                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3681                    output.status.code(),
3682                    String::from_utf8_lossy(&output.stdout),
3683                    String::from_utf8_lossy(&output.stderr),
3684                ));
3685            }
3686
3687            let stdout = String::from_utf8(output.stdout)?;
3688            Ok(Some(
3689                buffer
3690                    .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3691                    .await,
3692            ))
3693        } else {
3694            Ok(None)
3695        }
3696    }
3697
3698    pub fn definition<T: ToPointUtf16>(
3699        &self,
3700        buffer: &ModelHandle<Buffer>,
3701        position: T,
3702        cx: &mut ModelContext<Self>,
3703    ) -> Task<Result<Vec<LocationLink>>> {
3704        let position = position.to_point_utf16(buffer.read(cx));
3705        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3706    }
3707
3708    pub fn type_definition<T: ToPointUtf16>(
3709        &self,
3710        buffer: &ModelHandle<Buffer>,
3711        position: T,
3712        cx: &mut ModelContext<Self>,
3713    ) -> Task<Result<Vec<LocationLink>>> {
3714        let position = position.to_point_utf16(buffer.read(cx));
3715        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3716    }
3717
3718    pub fn references<T: ToPointUtf16>(
3719        &self,
3720        buffer: &ModelHandle<Buffer>,
3721        position: T,
3722        cx: &mut ModelContext<Self>,
3723    ) -> Task<Result<Vec<Location>>> {
3724        let position = position.to_point_utf16(buffer.read(cx));
3725        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3726    }
3727
3728    pub fn document_highlights<T: ToPointUtf16>(
3729        &self,
3730        buffer: &ModelHandle<Buffer>,
3731        position: T,
3732        cx: &mut ModelContext<Self>,
3733    ) -> Task<Result<Vec<DocumentHighlight>>> {
3734        let position = position.to_point_utf16(buffer.read(cx));
3735        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3736    }
3737
3738    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3739        if self.is_local() {
3740            let mut requests = Vec::new();
3741            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3742                let worktree_id = *worktree_id;
3743                if let Some(worktree) = self
3744                    .worktree_for_id(worktree_id, cx)
3745                    .and_then(|worktree| worktree.read(cx).as_local())
3746                {
3747                    if let Some(LanguageServerState::Running {
3748                        adapter,
3749                        language,
3750                        server,
3751                        ..
3752                    }) = self.language_servers.get(server_id)
3753                    {
3754                        let adapter = adapter.clone();
3755                        let language = language.clone();
3756                        let worktree_abs_path = worktree.abs_path().clone();
3757                        requests.push(
3758                            server
3759                                .request::<lsp::request::WorkspaceSymbol>(
3760                                    lsp::WorkspaceSymbolParams {
3761                                        query: query.to_string(),
3762                                        ..Default::default()
3763                                    },
3764                                )
3765                                .log_err()
3766                                .map(move |response| {
3767                                    (
3768                                        adapter,
3769                                        language,
3770                                        worktree_id,
3771                                        worktree_abs_path,
3772                                        response.unwrap_or_default(),
3773                                    )
3774                                }),
3775                        );
3776                    }
3777                }
3778            }
3779
3780            cx.spawn_weak(|this, cx| async move {
3781                let responses = futures::future::join_all(requests).await;
3782                let this = if let Some(this) = this.upgrade(&cx) {
3783                    this
3784                } else {
3785                    return Ok(Default::default());
3786                };
3787                let symbols = this.read_with(&cx, |this, cx| {
3788                    let mut symbols = Vec::new();
3789                    for (
3790                        adapter,
3791                        adapter_language,
3792                        source_worktree_id,
3793                        worktree_abs_path,
3794                        response,
3795                    ) in responses
3796                    {
3797                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3798                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3799                            let mut worktree_id = source_worktree_id;
3800                            let path;
3801                            if let Some((worktree, rel_path)) =
3802                                this.find_local_worktree(&abs_path, cx)
3803                            {
3804                                worktree_id = worktree.read(cx).id();
3805                                path = rel_path;
3806                            } else {
3807                                path = relativize_path(&worktree_abs_path, &abs_path);
3808                            }
3809
3810                            let project_path = ProjectPath {
3811                                worktree_id,
3812                                path: path.into(),
3813                            };
3814                            let signature = this.symbol_signature(&project_path);
3815                            let adapter_language = adapter_language.clone();
3816                            let language = this
3817                                .languages
3818                                .language_for_file(&project_path.path, None)
3819                                .unwrap_or_else(move |_| adapter_language);
3820                            let language_server_name = adapter.name.clone();
3821                            Some(async move {
3822                                let language = language.await;
3823                                let label = language
3824                                    .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3825                                    .await;
3826
3827                                Symbol {
3828                                    language_server_name,
3829                                    source_worktree_id,
3830                                    path: project_path,
3831                                    label: label.unwrap_or_else(|| {
3832                                        CodeLabel::plain(lsp_symbol.name.clone(), None)
3833                                    }),
3834                                    kind: lsp_symbol.kind,
3835                                    name: lsp_symbol.name,
3836                                    range: range_from_lsp(lsp_symbol.location.range),
3837                                    signature,
3838                                }
3839                            })
3840                        }));
3841                    }
3842                    symbols
3843                });
3844                Ok(futures::future::join_all(symbols).await)
3845            })
3846        } else if let Some(project_id) = self.remote_id() {
3847            let request = self.client.request(proto::GetProjectSymbols {
3848                project_id,
3849                query: query.to_string(),
3850            });
3851            cx.spawn_weak(|this, cx| async move {
3852                let response = request.await?;
3853                let mut symbols = Vec::new();
3854                if let Some(this) = this.upgrade(&cx) {
3855                    let new_symbols = this.read_with(&cx, |this, _| {
3856                        response
3857                            .symbols
3858                            .into_iter()
3859                            .map(|symbol| this.deserialize_symbol(symbol))
3860                            .collect::<Vec<_>>()
3861                    });
3862                    symbols = futures::future::join_all(new_symbols)
3863                        .await
3864                        .into_iter()
3865                        .filter_map(|symbol| symbol.log_err())
3866                        .collect::<Vec<_>>();
3867                }
3868                Ok(symbols)
3869            })
3870        } else {
3871            Task::ready(Ok(Default::default()))
3872        }
3873    }
3874
3875    pub fn open_buffer_for_symbol(
3876        &mut self,
3877        symbol: &Symbol,
3878        cx: &mut ModelContext<Self>,
3879    ) -> Task<Result<ModelHandle<Buffer>>> {
3880        if self.is_local() {
3881            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3882                symbol.source_worktree_id,
3883                symbol.language_server_name.clone(),
3884            )) {
3885                *id
3886            } else {
3887                return Task::ready(Err(anyhow!(
3888                    "language server for worktree and language not found"
3889                )));
3890            };
3891
3892            let worktree_abs_path = if let Some(worktree_abs_path) = self
3893                .worktree_for_id(symbol.path.worktree_id, cx)
3894                .and_then(|worktree| worktree.read(cx).as_local())
3895                .map(|local_worktree| local_worktree.abs_path())
3896            {
3897                worktree_abs_path
3898            } else {
3899                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3900            };
3901            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3902            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3903                uri
3904            } else {
3905                return Task::ready(Err(anyhow!("invalid symbol path")));
3906            };
3907
3908            self.open_local_buffer_via_lsp(
3909                symbol_uri,
3910                language_server_id,
3911                symbol.language_server_name.clone(),
3912                cx,
3913            )
3914        } else if let Some(project_id) = self.remote_id() {
3915            let request = self.client.request(proto::OpenBufferForSymbol {
3916                project_id,
3917                symbol: Some(serialize_symbol(symbol)),
3918            });
3919            cx.spawn(|this, mut cx| async move {
3920                let response = request.await?;
3921                this.update(&mut cx, |this, cx| {
3922                    this.wait_for_remote_buffer(response.buffer_id, cx)
3923                })
3924                .await
3925            })
3926        } else {
3927            Task::ready(Err(anyhow!("project does not have a remote id")))
3928        }
3929    }
3930
3931    pub fn hover<T: ToPointUtf16>(
3932        &self,
3933        buffer: &ModelHandle<Buffer>,
3934        position: T,
3935        cx: &mut ModelContext<Self>,
3936    ) -> Task<Result<Option<Hover>>> {
3937        let position = position.to_point_utf16(buffer.read(cx));
3938        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3939    }
3940
3941    pub fn completions<T: ToPointUtf16>(
3942        &self,
3943        buffer: &ModelHandle<Buffer>,
3944        position: T,
3945        cx: &mut ModelContext<Self>,
3946    ) -> Task<Result<Vec<Completion>>> {
3947        let position = position.to_point_utf16(buffer.read(cx));
3948        self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
3949    }
3950
3951    pub fn apply_additional_edits_for_completion(
3952        &self,
3953        buffer_handle: ModelHandle<Buffer>,
3954        completion: Completion,
3955        push_to_history: bool,
3956        cx: &mut ModelContext<Self>,
3957    ) -> Task<Result<Option<Transaction>>> {
3958        let buffer = buffer_handle.read(cx);
3959        let buffer_id = buffer.remote_id();
3960
3961        if self.is_local() {
3962            let lang_server = match self.primary_language_servers_for_buffer(buffer, cx) {
3963                Some((_, server)) => server.clone(),
3964                _ => return Task::ready(Ok(Default::default())),
3965            };
3966
3967            cx.spawn(|this, mut cx| async move {
3968                let resolved_completion = lang_server
3969                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3970                    .await?;
3971
3972                if let Some(edits) = resolved_completion.additional_text_edits {
3973                    let edits = this
3974                        .update(&mut cx, |this, cx| {
3975                            this.edits_from_lsp(
3976                                &buffer_handle,
3977                                edits,
3978                                lang_server.server_id(),
3979                                None,
3980                                cx,
3981                            )
3982                        })
3983                        .await?;
3984
3985                    buffer_handle.update(&mut cx, |buffer, cx| {
3986                        buffer.finalize_last_transaction();
3987                        buffer.start_transaction();
3988
3989                        for (range, text) in edits {
3990                            let primary = &completion.old_range;
3991                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
3992                                && primary.end.cmp(&range.start, buffer).is_ge();
3993                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
3994                                && range.end.cmp(&primary.end, buffer).is_ge();
3995
3996                            //Skip addtional edits which overlap with the primary completion edit
3997                            //https://github.com/zed-industries/zed/pull/1871
3998                            if !start_within && !end_within {
3999                                buffer.edit([(range, text)], None, cx);
4000                            }
4001                        }
4002
4003                        let transaction = if buffer.end_transaction(cx).is_some() {
4004                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4005                            if !push_to_history {
4006                                buffer.forget_transaction(transaction.id);
4007                            }
4008                            Some(transaction)
4009                        } else {
4010                            None
4011                        };
4012                        Ok(transaction)
4013                    })
4014                } else {
4015                    Ok(None)
4016                }
4017            })
4018        } else if let Some(project_id) = self.remote_id() {
4019            let client = self.client.clone();
4020            cx.spawn(|_, mut cx| async move {
4021                let response = client
4022                    .request(proto::ApplyCompletionAdditionalEdits {
4023                        project_id,
4024                        buffer_id,
4025                        completion: Some(language::proto::serialize_completion(&completion)),
4026                    })
4027                    .await?;
4028
4029                if let Some(transaction) = response.transaction {
4030                    let transaction = language::proto::deserialize_transaction(transaction)?;
4031                    buffer_handle
4032                        .update(&mut cx, |buffer, _| {
4033                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4034                        })
4035                        .await?;
4036                    if push_to_history {
4037                        buffer_handle.update(&mut cx, |buffer, _| {
4038                            buffer.push_transaction(transaction.clone(), Instant::now());
4039                        });
4040                    }
4041                    Ok(Some(transaction))
4042                } else {
4043                    Ok(None)
4044                }
4045            })
4046        } else {
4047            Task::ready(Err(anyhow!("project does not have a remote id")))
4048        }
4049    }
4050
4051    pub fn code_actions<T: Clone + ToOffset>(
4052        &self,
4053        buffer_handle: &ModelHandle<Buffer>,
4054        range: Range<T>,
4055        cx: &mut ModelContext<Self>,
4056    ) -> Task<Result<Vec<CodeAction>>> {
4057        let buffer = buffer_handle.read(cx);
4058        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4059        self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
4060    }
4061
4062    pub fn apply_code_action(
4063        &self,
4064        buffer_handle: ModelHandle<Buffer>,
4065        mut action: CodeAction,
4066        push_to_history: bool,
4067        cx: &mut ModelContext<Self>,
4068    ) -> Task<Result<ProjectTransaction>> {
4069        if self.is_local() {
4070            let buffer = buffer_handle.read(cx);
4071            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4072                self.language_server_for_buffer(buffer, action.server_id, cx)
4073            {
4074                (adapter.clone(), server.clone())
4075            } else {
4076                return Task::ready(Ok(Default::default()));
4077            };
4078            let range = action.range.to_point_utf16(buffer);
4079
4080            cx.spawn(|this, mut cx| async move {
4081                if let Some(lsp_range) = action
4082                    .lsp_action
4083                    .data
4084                    .as_mut()
4085                    .and_then(|d| d.get_mut("codeActionParams"))
4086                    .and_then(|d| d.get_mut("range"))
4087                {
4088                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4089                    action.lsp_action = lang_server
4090                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4091                        .await?;
4092                } else {
4093                    let actions = this
4094                        .update(&mut cx, |this, cx| {
4095                            this.code_actions(&buffer_handle, action.range, cx)
4096                        })
4097                        .await?;
4098                    action.lsp_action = actions
4099                        .into_iter()
4100                        .find(|a| a.lsp_action.title == action.lsp_action.title)
4101                        .ok_or_else(|| anyhow!("code action is outdated"))?
4102                        .lsp_action;
4103                }
4104
4105                if let Some(edit) = action.lsp_action.edit {
4106                    if edit.changes.is_some() || edit.document_changes.is_some() {
4107                        return Self::deserialize_workspace_edit(
4108                            this,
4109                            edit,
4110                            push_to_history,
4111                            lsp_adapter.clone(),
4112                            lang_server.clone(),
4113                            &mut cx,
4114                        )
4115                        .await;
4116                    }
4117                }
4118
4119                if let Some(command) = action.lsp_action.command {
4120                    this.update(&mut cx, |this, _| {
4121                        this.last_workspace_edits_by_language_server
4122                            .remove(&lang_server.server_id());
4123                    });
4124                    lang_server
4125                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4126                            command: command.command,
4127                            arguments: command.arguments.unwrap_or_default(),
4128                            ..Default::default()
4129                        })
4130                        .await?;
4131                    return Ok(this.update(&mut cx, |this, _| {
4132                        this.last_workspace_edits_by_language_server
4133                            .remove(&lang_server.server_id())
4134                            .unwrap_or_default()
4135                    }));
4136                }
4137
4138                Ok(ProjectTransaction::default())
4139            })
4140        } else if let Some(project_id) = self.remote_id() {
4141            let client = self.client.clone();
4142            let request = proto::ApplyCodeAction {
4143                project_id,
4144                buffer_id: buffer_handle.read(cx).remote_id(),
4145                action: Some(language::proto::serialize_code_action(&action)),
4146            };
4147            cx.spawn(|this, mut cx| async move {
4148                let response = client
4149                    .request(request)
4150                    .await?
4151                    .transaction
4152                    .ok_or_else(|| anyhow!("missing transaction"))?;
4153                this.update(&mut cx, |this, cx| {
4154                    this.deserialize_project_transaction(response, push_to_history, cx)
4155                })
4156                .await
4157            })
4158        } else {
4159            Task::ready(Err(anyhow!("project does not have a remote id")))
4160        }
4161    }
4162
4163    fn apply_on_type_formatting(
4164        &self,
4165        buffer: ModelHandle<Buffer>,
4166        position: Anchor,
4167        trigger: String,
4168        cx: &mut ModelContext<Self>,
4169    ) -> Task<Result<Option<Transaction>>> {
4170        if self.is_local() {
4171            cx.spawn(|this, mut cx| async move {
4172                // Do not allow multiple concurrent formatting requests for the
4173                // same buffer.
4174                this.update(&mut cx, |this, cx| {
4175                    this.buffers_being_formatted
4176                        .insert(buffer.read(cx).remote_id())
4177                });
4178
4179                let _cleanup = defer({
4180                    let this = this.clone();
4181                    let mut cx = cx.clone();
4182                    let closure_buffer = buffer.clone();
4183                    move || {
4184                        this.update(&mut cx, |this, cx| {
4185                            this.buffers_being_formatted
4186                                .remove(&closure_buffer.read(cx).remote_id());
4187                        });
4188                    }
4189                });
4190
4191                buffer
4192                    .update(&mut cx, |buffer, _| {
4193                        buffer.wait_for_edits(Some(position.timestamp))
4194                    })
4195                    .await?;
4196                this.update(&mut cx, |this, cx| {
4197                    let position = position.to_point_utf16(buffer.read(cx));
4198                    this.on_type_format(buffer, position, trigger, false, cx)
4199                })
4200                .await
4201            })
4202        } else if let Some(project_id) = self.remote_id() {
4203            let client = self.client.clone();
4204            let request = proto::OnTypeFormatting {
4205                project_id,
4206                buffer_id: buffer.read(cx).remote_id(),
4207                position: Some(serialize_anchor(&position)),
4208                trigger,
4209                version: serialize_version(&buffer.read(cx).version()),
4210            };
4211            cx.spawn(|_, _| async move {
4212                client
4213                    .request(request)
4214                    .await?
4215                    .transaction
4216                    .map(language::proto::deserialize_transaction)
4217                    .transpose()
4218            })
4219        } else {
4220            Task::ready(Err(anyhow!("project does not have a remote id")))
4221        }
4222    }
4223
4224    async fn deserialize_edits(
4225        this: ModelHandle<Self>,
4226        buffer_to_edit: ModelHandle<Buffer>,
4227        edits: Vec<lsp::TextEdit>,
4228        push_to_history: bool,
4229        _: Arc<CachedLspAdapter>,
4230        language_server: Arc<LanguageServer>,
4231        cx: &mut AsyncAppContext,
4232    ) -> Result<Option<Transaction>> {
4233        let edits = this
4234            .update(cx, |this, cx| {
4235                this.edits_from_lsp(
4236                    &buffer_to_edit,
4237                    edits,
4238                    language_server.server_id(),
4239                    None,
4240                    cx,
4241                )
4242            })
4243            .await?;
4244
4245        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4246            buffer.finalize_last_transaction();
4247            buffer.start_transaction();
4248            for (range, text) in edits {
4249                buffer.edit([(range, text)], None, cx);
4250            }
4251
4252            if buffer.end_transaction(cx).is_some() {
4253                let transaction = buffer.finalize_last_transaction().unwrap().clone();
4254                if !push_to_history {
4255                    buffer.forget_transaction(transaction.id);
4256                }
4257                Some(transaction)
4258            } else {
4259                None
4260            }
4261        });
4262
4263        Ok(transaction)
4264    }
4265
4266    async fn deserialize_workspace_edit(
4267        this: ModelHandle<Self>,
4268        edit: lsp::WorkspaceEdit,
4269        push_to_history: bool,
4270        lsp_adapter: Arc<CachedLspAdapter>,
4271        language_server: Arc<LanguageServer>,
4272        cx: &mut AsyncAppContext,
4273    ) -> Result<ProjectTransaction> {
4274        let fs = this.read_with(cx, |this, _| this.fs.clone());
4275        let mut operations = Vec::new();
4276        if let Some(document_changes) = edit.document_changes {
4277            match document_changes {
4278                lsp::DocumentChanges::Edits(edits) => {
4279                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4280                }
4281                lsp::DocumentChanges::Operations(ops) => operations = ops,
4282            }
4283        } else if let Some(changes) = edit.changes {
4284            operations.extend(changes.into_iter().map(|(uri, edits)| {
4285                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4286                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4287                        uri,
4288                        version: None,
4289                    },
4290                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
4291                })
4292            }));
4293        }
4294
4295        let mut project_transaction = ProjectTransaction::default();
4296        for operation in operations {
4297            match operation {
4298                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4299                    let abs_path = op
4300                        .uri
4301                        .to_file_path()
4302                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4303
4304                    if let Some(parent_path) = abs_path.parent() {
4305                        fs.create_dir(parent_path).await?;
4306                    }
4307                    if abs_path.ends_with("/") {
4308                        fs.create_dir(&abs_path).await?;
4309                    } else {
4310                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4311                            .await?;
4312                    }
4313                }
4314
4315                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4316                    let source_abs_path = op
4317                        .old_uri
4318                        .to_file_path()
4319                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4320                    let target_abs_path = op
4321                        .new_uri
4322                        .to_file_path()
4323                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4324                    fs.rename(
4325                        &source_abs_path,
4326                        &target_abs_path,
4327                        op.options.map(Into::into).unwrap_or_default(),
4328                    )
4329                    .await?;
4330                }
4331
4332                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4333                    let abs_path = op
4334                        .uri
4335                        .to_file_path()
4336                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4337                    let options = op.options.map(Into::into).unwrap_or_default();
4338                    if abs_path.ends_with("/") {
4339                        fs.remove_dir(&abs_path, options).await?;
4340                    } else {
4341                        fs.remove_file(&abs_path, options).await?;
4342                    }
4343                }
4344
4345                lsp::DocumentChangeOperation::Edit(op) => {
4346                    let buffer_to_edit = this
4347                        .update(cx, |this, cx| {
4348                            this.open_local_buffer_via_lsp(
4349                                op.text_document.uri,
4350                                language_server.server_id(),
4351                                lsp_adapter.name.clone(),
4352                                cx,
4353                            )
4354                        })
4355                        .await?;
4356
4357                    let edits = this
4358                        .update(cx, |this, cx| {
4359                            let edits = op.edits.into_iter().map(|edit| match edit {
4360                                lsp::OneOf::Left(edit) => edit,
4361                                lsp::OneOf::Right(edit) => edit.text_edit,
4362                            });
4363                            this.edits_from_lsp(
4364                                &buffer_to_edit,
4365                                edits,
4366                                language_server.server_id(),
4367                                op.text_document.version,
4368                                cx,
4369                            )
4370                        })
4371                        .await?;
4372
4373                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4374                        buffer.finalize_last_transaction();
4375                        buffer.start_transaction();
4376                        for (range, text) in edits {
4377                            buffer.edit([(range, text)], None, cx);
4378                        }
4379                        let transaction = if buffer.end_transaction(cx).is_some() {
4380                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4381                            if !push_to_history {
4382                                buffer.forget_transaction(transaction.id);
4383                            }
4384                            Some(transaction)
4385                        } else {
4386                            None
4387                        };
4388
4389                        transaction
4390                    });
4391                    if let Some(transaction) = transaction {
4392                        project_transaction.0.insert(buffer_to_edit, transaction);
4393                    }
4394                }
4395            }
4396        }
4397
4398        Ok(project_transaction)
4399    }
4400
4401    pub fn prepare_rename<T: ToPointUtf16>(
4402        &self,
4403        buffer: ModelHandle<Buffer>,
4404        position: T,
4405        cx: &mut ModelContext<Self>,
4406    ) -> Task<Result<Option<Range<Anchor>>>> {
4407        let position = position.to_point_utf16(buffer.read(cx));
4408        self.request_lsp(buffer, PrepareRename { position }, cx)
4409    }
4410
4411    pub fn perform_rename<T: ToPointUtf16>(
4412        &self,
4413        buffer: ModelHandle<Buffer>,
4414        position: T,
4415        new_name: String,
4416        push_to_history: bool,
4417        cx: &mut ModelContext<Self>,
4418    ) -> Task<Result<ProjectTransaction>> {
4419        let position = position.to_point_utf16(buffer.read(cx));
4420        self.request_lsp(
4421            buffer,
4422            PerformRename {
4423                position,
4424                new_name,
4425                push_to_history,
4426            },
4427            cx,
4428        )
4429    }
4430
4431    pub fn on_type_format<T: ToPointUtf16>(
4432        &self,
4433        buffer: ModelHandle<Buffer>,
4434        position: T,
4435        trigger: String,
4436        push_to_history: bool,
4437        cx: &mut ModelContext<Self>,
4438    ) -> Task<Result<Option<Transaction>>> {
4439        let tab_size = buffer.read_with(cx, |buffer, cx| {
4440            let language_name = buffer.language().map(|language| language.name());
4441            language_settings(language_name.as_deref(), cx).tab_size
4442        });
4443        let position = position.to_point_utf16(buffer.read(cx));
4444        self.request_lsp(
4445            buffer.clone(),
4446            OnTypeFormatting {
4447                position,
4448                trigger,
4449                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
4450                push_to_history,
4451            },
4452            cx,
4453        )
4454    }
4455
4456    #[allow(clippy::type_complexity)]
4457    pub fn search(
4458        &self,
4459        query: SearchQuery,
4460        cx: &mut ModelContext<Self>,
4461    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4462        if self.is_local() {
4463            let snapshots = self
4464                .visible_worktrees(cx)
4465                .filter_map(|tree| {
4466                    let tree = tree.read(cx).as_local()?;
4467                    Some(tree.snapshot())
4468                })
4469                .collect::<Vec<_>>();
4470
4471            let background = cx.background().clone();
4472            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4473            if path_count == 0 {
4474                return Task::ready(Ok(Default::default()));
4475            }
4476            let workers = background.num_cpus().min(path_count);
4477            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4478            cx.background()
4479                .spawn({
4480                    let fs = self.fs.clone();
4481                    let background = cx.background().clone();
4482                    let query = query.clone();
4483                    async move {
4484                        let fs = &fs;
4485                        let query = &query;
4486                        let matching_paths_tx = &matching_paths_tx;
4487                        let paths_per_worker = (path_count + workers - 1) / workers;
4488                        let snapshots = &snapshots;
4489                        background
4490                            .scoped(|scope| {
4491                                for worker_ix in 0..workers {
4492                                    let worker_start_ix = worker_ix * paths_per_worker;
4493                                    let worker_end_ix = worker_start_ix + paths_per_worker;
4494                                    scope.spawn(async move {
4495                                        let mut snapshot_start_ix = 0;
4496                                        let mut abs_path = PathBuf::new();
4497                                        for snapshot in snapshots {
4498                                            let snapshot_end_ix =
4499                                                snapshot_start_ix + snapshot.visible_file_count();
4500                                            if worker_end_ix <= snapshot_start_ix {
4501                                                break;
4502                                            } else if worker_start_ix > snapshot_end_ix {
4503                                                snapshot_start_ix = snapshot_end_ix;
4504                                                continue;
4505                                            } else {
4506                                                let start_in_snapshot = worker_start_ix
4507                                                    .saturating_sub(snapshot_start_ix);
4508                                                let end_in_snapshot =
4509                                                    cmp::min(worker_end_ix, snapshot_end_ix)
4510                                                        - snapshot_start_ix;
4511
4512                                                for entry in snapshot
4513                                                    .files(false, start_in_snapshot)
4514                                                    .take(end_in_snapshot - start_in_snapshot)
4515                                                {
4516                                                    if matching_paths_tx.is_closed() {
4517                                                        break;
4518                                                    }
4519                                                    let matches = if query
4520                                                        .file_matches(Some(&entry.path))
4521                                                    {
4522                                                        abs_path.clear();
4523                                                        abs_path.push(&snapshot.abs_path());
4524                                                        abs_path.push(&entry.path);
4525                                                        if let Some(file) =
4526                                                            fs.open_sync(&abs_path).await.log_err()
4527                                                        {
4528                                                            query.detect(file).unwrap_or(false)
4529                                                        } else {
4530                                                            false
4531                                                        }
4532                                                    } else {
4533                                                        false
4534                                                    };
4535
4536                                                    if matches {
4537                                                        let project_path =
4538                                                            (snapshot.id(), entry.path.clone());
4539                                                        if matching_paths_tx
4540                                                            .send(project_path)
4541                                                            .await
4542                                                            .is_err()
4543                                                        {
4544                                                            break;
4545                                                        }
4546                                                    }
4547                                                }
4548
4549                                                snapshot_start_ix = snapshot_end_ix;
4550                                            }
4551                                        }
4552                                    });
4553                                }
4554                            })
4555                            .await;
4556                    }
4557                })
4558                .detach();
4559
4560            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4561            let open_buffers = self
4562                .opened_buffers
4563                .values()
4564                .filter_map(|b| b.upgrade(cx))
4565                .collect::<HashSet<_>>();
4566            cx.spawn(|this, cx| async move {
4567                for buffer in &open_buffers {
4568                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4569                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4570                }
4571
4572                let open_buffers = Rc::new(RefCell::new(open_buffers));
4573                while let Some(project_path) = matching_paths_rx.next().await {
4574                    if buffers_tx.is_closed() {
4575                        break;
4576                    }
4577
4578                    let this = this.clone();
4579                    let open_buffers = open_buffers.clone();
4580                    let buffers_tx = buffers_tx.clone();
4581                    cx.spawn(|mut cx| async move {
4582                        if let Some(buffer) = this
4583                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4584                            .await
4585                            .log_err()
4586                        {
4587                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4588                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4589                                buffers_tx.send((buffer, snapshot)).await?;
4590                            }
4591                        }
4592
4593                        Ok::<_, anyhow::Error>(())
4594                    })
4595                    .detach();
4596                }
4597
4598                Ok::<_, anyhow::Error>(())
4599            })
4600            .detach_and_log_err(cx);
4601
4602            let background = cx.background().clone();
4603            cx.background().spawn(async move {
4604                let query = &query;
4605                let mut matched_buffers = Vec::new();
4606                for _ in 0..workers {
4607                    matched_buffers.push(HashMap::default());
4608                }
4609                background
4610                    .scoped(|scope| {
4611                        for worker_matched_buffers in matched_buffers.iter_mut() {
4612                            let mut buffers_rx = buffers_rx.clone();
4613                            scope.spawn(async move {
4614                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4615                                    let buffer_matches = if query.file_matches(
4616                                        snapshot.file().map(|file| file.path().as_ref()),
4617                                    ) {
4618                                        query
4619                                            .search(snapshot.as_rope())
4620                                            .await
4621                                            .iter()
4622                                            .map(|range| {
4623                                                snapshot.anchor_before(range.start)
4624                                                    ..snapshot.anchor_after(range.end)
4625                                            })
4626                                            .collect()
4627                                    } else {
4628                                        Vec::new()
4629                                    };
4630                                    if !buffer_matches.is_empty() {
4631                                        worker_matched_buffers
4632                                            .insert(buffer.clone(), buffer_matches);
4633                                    }
4634                                }
4635                            });
4636                        }
4637                    })
4638                    .await;
4639                Ok(matched_buffers.into_iter().flatten().collect())
4640            })
4641        } else if let Some(project_id) = self.remote_id() {
4642            let request = self.client.request(query.to_proto(project_id));
4643            cx.spawn(|this, mut cx| async move {
4644                let response = request.await?;
4645                let mut result = HashMap::default();
4646                for location in response.locations {
4647                    let target_buffer = this
4648                        .update(&mut cx, |this, cx| {
4649                            this.wait_for_remote_buffer(location.buffer_id, cx)
4650                        })
4651                        .await?;
4652                    let start = location
4653                        .start
4654                        .and_then(deserialize_anchor)
4655                        .ok_or_else(|| anyhow!("missing target start"))?;
4656                    let end = location
4657                        .end
4658                        .and_then(deserialize_anchor)
4659                        .ok_or_else(|| anyhow!("missing target end"))?;
4660                    result
4661                        .entry(target_buffer)
4662                        .or_insert(Vec::new())
4663                        .push(start..end)
4664                }
4665                Ok(result)
4666            })
4667        } else {
4668            Task::ready(Ok(Default::default()))
4669        }
4670    }
4671
4672    // TODO: Wire this up to allow selecting a server?
4673    fn request_lsp<R: LspCommand>(
4674        &self,
4675        buffer_handle: ModelHandle<Buffer>,
4676        request: R,
4677        cx: &mut ModelContext<Self>,
4678    ) -> Task<Result<R::Response>>
4679    where
4680        <R::LspRequest as lsp::request::Request>::Result: Send,
4681    {
4682        let buffer = buffer_handle.read(cx);
4683        if self.is_local() {
4684            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4685            if let Some((file, language_server)) = file.zip(
4686                self.primary_language_servers_for_buffer(buffer, cx)
4687                    .map(|(_, server)| server.clone()),
4688            ) {
4689                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
4690                return cx.spawn(|this, cx| async move {
4691                    if !request.check_capabilities(language_server.capabilities()) {
4692                        return Ok(Default::default());
4693                    }
4694
4695                    let response = language_server
4696                        .request::<R::LspRequest>(lsp_params)
4697                        .await
4698                        .context("lsp request failed")?;
4699                    request
4700                        .response_from_lsp(
4701                            response,
4702                            this,
4703                            buffer_handle,
4704                            language_server.server_id(),
4705                            cx,
4706                        )
4707                        .await
4708                });
4709            }
4710        } else if let Some(project_id) = self.remote_id() {
4711            let rpc = self.client.clone();
4712            let message = request.to_proto(project_id, buffer);
4713            return cx.spawn_weak(|this, cx| async move {
4714                // Ensure the project is still alive by the time the task
4715                // is scheduled.
4716                this.upgrade(&cx)
4717                    .ok_or_else(|| anyhow!("project dropped"))?;
4718
4719                let response = rpc.request(message).await?;
4720
4721                let this = this
4722                    .upgrade(&cx)
4723                    .ok_or_else(|| anyhow!("project dropped"))?;
4724                if this.read_with(&cx, |this, _| this.is_read_only()) {
4725                    Err(anyhow!("disconnected before completing request"))
4726                } else {
4727                    request
4728                        .response_from_proto(response, this, buffer_handle, cx)
4729                        .await
4730                }
4731            });
4732        }
4733        Task::ready(Ok(Default::default()))
4734    }
4735
4736    pub fn find_or_create_local_worktree(
4737        &mut self,
4738        abs_path: impl AsRef<Path>,
4739        visible: bool,
4740        cx: &mut ModelContext<Self>,
4741    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4742        let abs_path = abs_path.as_ref();
4743        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4744            Task::ready(Ok((tree, relative_path)))
4745        } else {
4746            let worktree = self.create_local_worktree(abs_path, visible, cx);
4747            cx.foreground()
4748                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4749        }
4750    }
4751
4752    pub fn find_local_worktree(
4753        &self,
4754        abs_path: &Path,
4755        cx: &AppContext,
4756    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4757        for tree in &self.worktrees {
4758            if let Some(tree) = tree.upgrade(cx) {
4759                if let Some(relative_path) = tree
4760                    .read(cx)
4761                    .as_local()
4762                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4763                {
4764                    return Some((tree.clone(), relative_path.into()));
4765                }
4766            }
4767        }
4768        None
4769    }
4770
4771    pub fn is_shared(&self) -> bool {
4772        match &self.client_state {
4773            Some(ProjectClientState::Local { .. }) => true,
4774            _ => false,
4775        }
4776    }
4777
4778    fn create_local_worktree(
4779        &mut self,
4780        abs_path: impl AsRef<Path>,
4781        visible: bool,
4782        cx: &mut ModelContext<Self>,
4783    ) -> Task<Result<ModelHandle<Worktree>>> {
4784        let fs = self.fs.clone();
4785        let client = self.client.clone();
4786        let next_entry_id = self.next_entry_id.clone();
4787        let path: Arc<Path> = abs_path.as_ref().into();
4788        let task = self
4789            .loading_local_worktrees
4790            .entry(path.clone())
4791            .or_insert_with(|| {
4792                cx.spawn(|project, mut cx| {
4793                    async move {
4794                        let worktree = Worktree::local(
4795                            client.clone(),
4796                            path.clone(),
4797                            visible,
4798                            fs,
4799                            next_entry_id,
4800                            &mut cx,
4801                        )
4802                        .await;
4803
4804                        project.update(&mut cx, |project, _| {
4805                            project.loading_local_worktrees.remove(&path);
4806                        });
4807
4808                        let worktree = worktree?;
4809                        project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
4810                        Ok(worktree)
4811                    }
4812                    .map_err(Arc::new)
4813                })
4814                .shared()
4815            })
4816            .clone();
4817        cx.foreground().spawn(async move {
4818            match task.await {
4819                Ok(worktree) => Ok(worktree),
4820                Err(err) => Err(anyhow!("{}", err)),
4821            }
4822        })
4823    }
4824
4825    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4826        self.worktrees.retain(|worktree| {
4827            if let Some(worktree) = worktree.upgrade(cx) {
4828                let id = worktree.read(cx).id();
4829                if id == id_to_remove {
4830                    cx.emit(Event::WorktreeRemoved(id));
4831                    false
4832                } else {
4833                    true
4834                }
4835            } else {
4836                false
4837            }
4838        });
4839        self.metadata_changed(cx);
4840    }
4841
4842    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4843        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4844        if worktree.read(cx).is_local() {
4845            cx.subscribe(worktree, |this, worktree, event, cx| match event {
4846                worktree::Event::UpdatedEntries(changes) => {
4847                    this.update_local_worktree_buffers(&worktree, &changes, cx);
4848                    this.update_local_worktree_language_servers(&worktree, changes, cx);
4849                }
4850                worktree::Event::UpdatedGitRepositories(updated_repos) => {
4851                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4852                }
4853            })
4854            .detach();
4855        }
4856
4857        let push_strong_handle = {
4858            let worktree = worktree.read(cx);
4859            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4860        };
4861        if push_strong_handle {
4862            self.worktrees
4863                .push(WorktreeHandle::Strong(worktree.clone()));
4864        } else {
4865            self.worktrees
4866                .push(WorktreeHandle::Weak(worktree.downgrade()));
4867        }
4868
4869        cx.observe_release(worktree, |this, worktree, cx| {
4870            let _ = this.remove_worktree(worktree.id(), cx);
4871        })
4872        .detach();
4873
4874        cx.emit(Event::WorktreeAdded);
4875        self.metadata_changed(cx);
4876    }
4877
4878    fn update_local_worktree_buffers(
4879        &mut self,
4880        worktree_handle: &ModelHandle<Worktree>,
4881        changes: &HashMap<(Arc<Path>, ProjectEntryId), PathChange>,
4882        cx: &mut ModelContext<Self>,
4883    ) {
4884        let snapshot = worktree_handle.read(cx).snapshot();
4885
4886        let mut renamed_buffers = Vec::new();
4887        for (path, entry_id) in changes.keys() {
4888            let worktree_id = worktree_handle.read(cx).id();
4889            let project_path = ProjectPath {
4890                worktree_id,
4891                path: path.clone(),
4892            };
4893
4894            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
4895                Some(&buffer_id) => buffer_id,
4896                None => match self.local_buffer_ids_by_path.get(&project_path) {
4897                    Some(&buffer_id) => buffer_id,
4898                    None => continue,
4899                },
4900            };
4901
4902            let open_buffer = self.opened_buffers.get(&buffer_id);
4903            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
4904                buffer
4905            } else {
4906                self.opened_buffers.remove(&buffer_id);
4907                self.local_buffer_ids_by_path.remove(&project_path);
4908                self.local_buffer_ids_by_entry_id.remove(entry_id);
4909                continue;
4910            };
4911
4912            buffer.update(cx, |buffer, cx| {
4913                if let Some(old_file) = File::from_dyn(buffer.file()) {
4914                    if old_file.worktree != *worktree_handle {
4915                        return;
4916                    }
4917
4918                    let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
4919                        File {
4920                            is_local: true,
4921                            entry_id: entry.id,
4922                            mtime: entry.mtime,
4923                            path: entry.path.clone(),
4924                            worktree: worktree_handle.clone(),
4925                            is_deleted: false,
4926                        }
4927                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
4928                        File {
4929                            is_local: true,
4930                            entry_id: entry.id,
4931                            mtime: entry.mtime,
4932                            path: entry.path.clone(),
4933                            worktree: worktree_handle.clone(),
4934                            is_deleted: false,
4935                        }
4936                    } else {
4937                        File {
4938                            is_local: true,
4939                            entry_id: old_file.entry_id,
4940                            path: old_file.path().clone(),
4941                            mtime: old_file.mtime(),
4942                            worktree: worktree_handle.clone(),
4943                            is_deleted: true,
4944                        }
4945                    };
4946
4947                    let old_path = old_file.abs_path(cx);
4948                    if new_file.abs_path(cx) != old_path {
4949                        renamed_buffers.push((cx.handle(), old_file.clone()));
4950                        self.local_buffer_ids_by_path.remove(&project_path);
4951                        self.local_buffer_ids_by_path.insert(
4952                            ProjectPath {
4953                                worktree_id,
4954                                path: path.clone(),
4955                            },
4956                            buffer_id,
4957                        );
4958                    }
4959
4960                    if new_file.entry_id != *entry_id {
4961                        self.local_buffer_ids_by_entry_id.remove(entry_id);
4962                        self.local_buffer_ids_by_entry_id
4963                            .insert(new_file.entry_id, buffer_id);
4964                    }
4965
4966                    if new_file != *old_file {
4967                        if let Some(project_id) = self.remote_id() {
4968                            self.client
4969                                .send(proto::UpdateBufferFile {
4970                                    project_id,
4971                                    buffer_id: buffer_id as u64,
4972                                    file: Some(new_file.to_proto()),
4973                                })
4974                                .log_err();
4975                        }
4976
4977                        buffer.file_updated(Arc::new(new_file), cx).detach();
4978                    }
4979                }
4980            });
4981        }
4982
4983        for (buffer, old_file) in renamed_buffers {
4984            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
4985            self.detect_language_for_buffer(&buffer, cx);
4986            self.register_buffer_with_language_servers(&buffer, cx);
4987        }
4988    }
4989
4990    fn update_local_worktree_language_servers(
4991        &mut self,
4992        worktree_handle: &ModelHandle<Worktree>,
4993        changes: &HashMap<(Arc<Path>, ProjectEntryId), PathChange>,
4994        cx: &mut ModelContext<Self>,
4995    ) {
4996        if changes.is_empty() {
4997            return;
4998        }
4999
5000        let worktree_id = worktree_handle.read(cx).id();
5001        let mut language_server_ids = self
5002            .language_server_ids
5003            .iter()
5004            .filter_map(|((server_worktree_id, _), server_id)| {
5005                (*server_worktree_id == worktree_id).then_some(*server_id)
5006            })
5007            .collect::<Vec<_>>();
5008        language_server_ids.sort();
5009        language_server_ids.dedup();
5010
5011        let abs_path = worktree_handle.read(cx).abs_path();
5012        for server_id in &language_server_ids {
5013            if let Some(server) = self.language_servers.get(server_id) {
5014                if let LanguageServerState::Running {
5015                    server,
5016                    watched_paths,
5017                    ..
5018                } = server
5019                {
5020                    if let Some(watched_paths) = watched_paths.get(&worktree_id) {
5021                        let params = lsp::DidChangeWatchedFilesParams {
5022                            changes: changes
5023                                .iter()
5024                                .filter_map(|((path, _), change)| {
5025                                    if watched_paths.is_match(&path) {
5026                                        Some(lsp::FileEvent {
5027                                            uri: lsp::Url::from_file_path(abs_path.join(path))
5028                                                .unwrap(),
5029                                            typ: match change {
5030                                                PathChange::Added => lsp::FileChangeType::CREATED,
5031                                                PathChange::Removed => lsp::FileChangeType::DELETED,
5032                                                PathChange::Updated
5033                                                | PathChange::AddedOrUpdated => {
5034                                                    lsp::FileChangeType::CHANGED
5035                                                }
5036                                            },
5037                                        })
5038                                    } else {
5039                                        None
5040                                    }
5041                                })
5042                                .collect(),
5043                        };
5044
5045                        if !params.changes.is_empty() {
5046                            server
5047                                .notify::<lsp::notification::DidChangeWatchedFiles>(params)
5048                                .log_err();
5049                        }
5050                    }
5051                }
5052            }
5053        }
5054    }
5055
5056    fn update_local_worktree_buffers_git_repos(
5057        &mut self,
5058        worktree_handle: ModelHandle<Worktree>,
5059        repos: &HashMap<Arc<Path>, LocalRepositoryEntry>,
5060        cx: &mut ModelContext<Self>,
5061    ) {
5062        debug_assert!(worktree_handle.read(cx).is_local());
5063
5064        // Setup the pending buffers
5065        let future_buffers = self
5066            .loading_buffers_by_path
5067            .iter()
5068            .filter_map(|(path, receiver)| {
5069                let path = &path.path;
5070                let (work_directory, repo) = repos
5071                    .iter()
5072                    .find(|(work_directory, _)| path.starts_with(work_directory))?;
5073
5074                let repo_relative_path = path.strip_prefix(work_directory).log_err()?;
5075
5076                let receiver = receiver.clone();
5077                let repo_ptr = repo.repo_ptr.clone();
5078                let repo_relative_path = repo_relative_path.to_owned();
5079                Some(async move {
5080                    pump_loading_buffer_reciever(receiver)
5081                        .await
5082                        .ok()
5083                        .map(|buffer| (buffer, repo_relative_path, repo_ptr))
5084                })
5085            })
5086            .collect::<FuturesUnordered<_>>()
5087            .filter_map(|result| async move {
5088                let (buffer_handle, repo_relative_path, repo_ptr) = result?;
5089
5090                let lock = repo_ptr.lock();
5091                lock.load_index_text(&repo_relative_path)
5092                    .map(|diff_base| (diff_base, buffer_handle))
5093            });
5094
5095        let update_diff_base_fn = update_diff_base(self);
5096        cx.spawn(|_, mut cx| async move {
5097            let diff_base_tasks = cx
5098                .background()
5099                .spawn(future_buffers.collect::<Vec<_>>())
5100                .await;
5101
5102            for (diff_base, buffer) in diff_base_tasks.into_iter() {
5103                update_diff_base_fn(Some(diff_base), buffer, &mut cx);
5104            }
5105        })
5106        .detach();
5107
5108        // And the current buffers
5109        for (_, buffer) in &self.opened_buffers {
5110            if let Some(buffer) = buffer.upgrade(cx) {
5111                let file = match File::from_dyn(buffer.read(cx).file()) {
5112                    Some(file) => file,
5113                    None => continue,
5114                };
5115                if file.worktree != worktree_handle {
5116                    continue;
5117                }
5118
5119                let path = file.path().clone();
5120
5121                let worktree = worktree_handle.read(cx);
5122
5123                let (work_directory, repo) = match repos
5124                    .iter()
5125                    .find(|(work_directory, _)| path.starts_with(work_directory))
5126                {
5127                    Some(repo) => repo.clone(),
5128                    None => continue,
5129                };
5130
5131                let relative_repo = match path.strip_prefix(work_directory).log_err() {
5132                    Some(relative_repo) => relative_repo.to_owned(),
5133                    None => continue,
5134                };
5135
5136                drop(worktree);
5137
5138                let update_diff_base_fn = update_diff_base(self);
5139                let git_ptr = repo.repo_ptr.clone();
5140                let diff_base_task = cx
5141                    .background()
5142                    .spawn(async move { git_ptr.lock().load_index_text(&relative_repo) });
5143
5144                cx.spawn(|_, mut cx| async move {
5145                    let diff_base = diff_base_task.await;
5146                    update_diff_base_fn(diff_base, buffer, &mut cx);
5147                })
5148                .detach();
5149            }
5150        }
5151    }
5152
5153    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
5154        let new_active_entry = entry.and_then(|project_path| {
5155            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
5156            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
5157            Some(entry.id)
5158        });
5159        if new_active_entry != self.active_entry {
5160            self.active_entry = new_active_entry;
5161            cx.emit(Event::ActiveEntryChanged(new_active_entry));
5162        }
5163    }
5164
5165    pub fn language_servers_running_disk_based_diagnostics(
5166        &self,
5167    ) -> impl Iterator<Item = LanguageServerId> + '_ {
5168        self.language_server_statuses
5169            .iter()
5170            .filter_map(|(id, status)| {
5171                if status.has_pending_diagnostic_updates {
5172                    Some(*id)
5173                } else {
5174                    None
5175                }
5176            })
5177    }
5178
5179    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
5180        let mut summary = DiagnosticSummary::default();
5181        for (_, _, path_summary) in self.diagnostic_summaries(cx) {
5182            summary.error_count += path_summary.error_count;
5183            summary.warning_count += path_summary.warning_count;
5184        }
5185        summary
5186    }
5187
5188    pub fn diagnostic_summaries<'a>(
5189        &'a self,
5190        cx: &'a AppContext,
5191    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
5192        self.visible_worktrees(cx).flat_map(move |worktree| {
5193            let worktree = worktree.read(cx);
5194            let worktree_id = worktree.id();
5195            worktree
5196                .diagnostic_summaries()
5197                .map(move |(path, server_id, summary)| {
5198                    (ProjectPath { worktree_id, path }, server_id, summary)
5199                })
5200        })
5201    }
5202
5203    pub fn disk_based_diagnostics_started(
5204        &mut self,
5205        language_server_id: LanguageServerId,
5206        cx: &mut ModelContext<Self>,
5207    ) {
5208        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
5209    }
5210
5211    pub fn disk_based_diagnostics_finished(
5212        &mut self,
5213        language_server_id: LanguageServerId,
5214        cx: &mut ModelContext<Self>,
5215    ) {
5216        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
5217    }
5218
5219    pub fn active_entry(&self) -> Option<ProjectEntryId> {
5220        self.active_entry
5221    }
5222
5223    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
5224        self.worktree_for_id(path.worktree_id, cx)?
5225            .read(cx)
5226            .entry_for_path(&path.path)
5227            .cloned()
5228    }
5229
5230    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
5231        let worktree = self.worktree_for_entry(entry_id, cx)?;
5232        let worktree = worktree.read(cx);
5233        let worktree_id = worktree.id();
5234        let path = worktree.entry_for_id(entry_id)?.path.clone();
5235        Some(ProjectPath { worktree_id, path })
5236    }
5237
5238    // RPC message handlers
5239
5240    async fn handle_unshare_project(
5241        this: ModelHandle<Self>,
5242        _: TypedEnvelope<proto::UnshareProject>,
5243        _: Arc<Client>,
5244        mut cx: AsyncAppContext,
5245    ) -> Result<()> {
5246        this.update(&mut cx, |this, cx| {
5247            if this.is_local() {
5248                this.unshare(cx)?;
5249            } else {
5250                this.disconnected_from_host(cx);
5251            }
5252            Ok(())
5253        })
5254    }
5255
5256    async fn handle_add_collaborator(
5257        this: ModelHandle<Self>,
5258        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
5259        _: Arc<Client>,
5260        mut cx: AsyncAppContext,
5261    ) -> Result<()> {
5262        let collaborator = envelope
5263            .payload
5264            .collaborator
5265            .take()
5266            .ok_or_else(|| anyhow!("empty collaborator"))?;
5267
5268        let collaborator = Collaborator::from_proto(collaborator)?;
5269        this.update(&mut cx, |this, cx| {
5270            this.shared_buffers.remove(&collaborator.peer_id);
5271            this.collaborators
5272                .insert(collaborator.peer_id, collaborator);
5273            cx.notify();
5274        });
5275
5276        Ok(())
5277    }
5278
5279    async fn handle_update_project_collaborator(
5280        this: ModelHandle<Self>,
5281        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
5282        _: Arc<Client>,
5283        mut cx: AsyncAppContext,
5284    ) -> Result<()> {
5285        let old_peer_id = envelope
5286            .payload
5287            .old_peer_id
5288            .ok_or_else(|| anyhow!("missing old peer id"))?;
5289        let new_peer_id = envelope
5290            .payload
5291            .new_peer_id
5292            .ok_or_else(|| anyhow!("missing new peer id"))?;
5293        this.update(&mut cx, |this, cx| {
5294            let collaborator = this
5295                .collaborators
5296                .remove(&old_peer_id)
5297                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
5298            let is_host = collaborator.replica_id == 0;
5299            this.collaborators.insert(new_peer_id, collaborator);
5300
5301            let buffers = this.shared_buffers.remove(&old_peer_id);
5302            log::info!(
5303                "peer {} became {}. moving buffers {:?}",
5304                old_peer_id,
5305                new_peer_id,
5306                &buffers
5307            );
5308            if let Some(buffers) = buffers {
5309                this.shared_buffers.insert(new_peer_id, buffers);
5310            }
5311
5312            if is_host {
5313                this.opened_buffers
5314                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
5315                this.buffer_ordered_messages_tx
5316                    .unbounded_send(BufferOrderedMessage::Resync)
5317                    .unwrap();
5318            }
5319
5320            cx.emit(Event::CollaboratorUpdated {
5321                old_peer_id,
5322                new_peer_id,
5323            });
5324            cx.notify();
5325            Ok(())
5326        })
5327    }
5328
5329    async fn handle_remove_collaborator(
5330        this: ModelHandle<Self>,
5331        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5332        _: Arc<Client>,
5333        mut cx: AsyncAppContext,
5334    ) -> Result<()> {
5335        this.update(&mut cx, |this, cx| {
5336            let peer_id = envelope
5337                .payload
5338                .peer_id
5339                .ok_or_else(|| anyhow!("invalid peer id"))?;
5340            let replica_id = this
5341                .collaborators
5342                .remove(&peer_id)
5343                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
5344                .replica_id;
5345            for buffer in this.opened_buffers.values() {
5346                if let Some(buffer) = buffer.upgrade(cx) {
5347                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5348                }
5349            }
5350            this.shared_buffers.remove(&peer_id);
5351
5352            cx.emit(Event::CollaboratorLeft(peer_id));
5353            cx.notify();
5354            Ok(())
5355        })
5356    }
5357
5358    async fn handle_update_project(
5359        this: ModelHandle<Self>,
5360        envelope: TypedEnvelope<proto::UpdateProject>,
5361        _: Arc<Client>,
5362        mut cx: AsyncAppContext,
5363    ) -> Result<()> {
5364        this.update(&mut cx, |this, cx| {
5365            // Don't handle messages that were sent before the response to us joining the project
5366            if envelope.message_id > this.join_project_response_message_id {
5367                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5368            }
5369            Ok(())
5370        })
5371    }
5372
5373    async fn handle_update_worktree(
5374        this: ModelHandle<Self>,
5375        envelope: TypedEnvelope<proto::UpdateWorktree>,
5376        _: Arc<Client>,
5377        mut cx: AsyncAppContext,
5378    ) -> Result<()> {
5379        this.update(&mut cx, |this, cx| {
5380            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5381            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5382                worktree.update(cx, |worktree, _| {
5383                    let worktree = worktree.as_remote_mut().unwrap();
5384                    worktree.update_from_remote(envelope.payload);
5385                });
5386            }
5387            Ok(())
5388        })
5389    }
5390
5391    async fn handle_create_project_entry(
5392        this: ModelHandle<Self>,
5393        envelope: TypedEnvelope<proto::CreateProjectEntry>,
5394        _: Arc<Client>,
5395        mut cx: AsyncAppContext,
5396    ) -> Result<proto::ProjectEntryResponse> {
5397        let worktree = this.update(&mut cx, |this, cx| {
5398            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5399            this.worktree_for_id(worktree_id, cx)
5400                .ok_or_else(|| anyhow!("worktree not found"))
5401        })?;
5402        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5403        let entry = worktree
5404            .update(&mut cx, |worktree, cx| {
5405                let worktree = worktree.as_local_mut().unwrap();
5406                let path = PathBuf::from(envelope.payload.path);
5407                worktree.create_entry(path, envelope.payload.is_directory, cx)
5408            })
5409            .await?;
5410        Ok(proto::ProjectEntryResponse {
5411            entry: Some((&entry).into()),
5412            worktree_scan_id: worktree_scan_id as u64,
5413        })
5414    }
5415
5416    async fn handle_rename_project_entry(
5417        this: ModelHandle<Self>,
5418        envelope: TypedEnvelope<proto::RenameProjectEntry>,
5419        _: Arc<Client>,
5420        mut cx: AsyncAppContext,
5421    ) -> Result<proto::ProjectEntryResponse> {
5422        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5423        let worktree = this.read_with(&cx, |this, cx| {
5424            this.worktree_for_entry(entry_id, cx)
5425                .ok_or_else(|| anyhow!("worktree not found"))
5426        })?;
5427        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5428        let entry = worktree
5429            .update(&mut cx, |worktree, cx| {
5430                let new_path = PathBuf::from(envelope.payload.new_path);
5431                worktree
5432                    .as_local_mut()
5433                    .unwrap()
5434                    .rename_entry(entry_id, new_path, cx)
5435                    .ok_or_else(|| anyhow!("invalid entry"))
5436            })?
5437            .await?;
5438        Ok(proto::ProjectEntryResponse {
5439            entry: Some((&entry).into()),
5440            worktree_scan_id: worktree_scan_id as u64,
5441        })
5442    }
5443
5444    async fn handle_copy_project_entry(
5445        this: ModelHandle<Self>,
5446        envelope: TypedEnvelope<proto::CopyProjectEntry>,
5447        _: Arc<Client>,
5448        mut cx: AsyncAppContext,
5449    ) -> Result<proto::ProjectEntryResponse> {
5450        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5451        let worktree = this.read_with(&cx, |this, cx| {
5452            this.worktree_for_entry(entry_id, cx)
5453                .ok_or_else(|| anyhow!("worktree not found"))
5454        })?;
5455        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5456        let entry = worktree
5457            .update(&mut cx, |worktree, cx| {
5458                let new_path = PathBuf::from(envelope.payload.new_path);
5459                worktree
5460                    .as_local_mut()
5461                    .unwrap()
5462                    .copy_entry(entry_id, new_path, cx)
5463                    .ok_or_else(|| anyhow!("invalid entry"))
5464            })?
5465            .await?;
5466        Ok(proto::ProjectEntryResponse {
5467            entry: Some((&entry).into()),
5468            worktree_scan_id: worktree_scan_id as u64,
5469        })
5470    }
5471
5472    async fn handle_delete_project_entry(
5473        this: ModelHandle<Self>,
5474        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
5475        _: Arc<Client>,
5476        mut cx: AsyncAppContext,
5477    ) -> Result<proto::ProjectEntryResponse> {
5478        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5479
5480        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
5481
5482        let worktree = this.read_with(&cx, |this, cx| {
5483            this.worktree_for_entry(entry_id, cx)
5484                .ok_or_else(|| anyhow!("worktree not found"))
5485        })?;
5486        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5487        worktree
5488            .update(&mut cx, |worktree, cx| {
5489                worktree
5490                    .as_local_mut()
5491                    .unwrap()
5492                    .delete_entry(entry_id, cx)
5493                    .ok_or_else(|| anyhow!("invalid entry"))
5494            })?
5495            .await?;
5496        Ok(proto::ProjectEntryResponse {
5497            entry: None,
5498            worktree_scan_id: worktree_scan_id as u64,
5499        })
5500    }
5501
5502    async fn handle_update_diagnostic_summary(
5503        this: ModelHandle<Self>,
5504        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5505        _: Arc<Client>,
5506        mut cx: AsyncAppContext,
5507    ) -> Result<()> {
5508        this.update(&mut cx, |this, cx| {
5509            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5510            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5511                if let Some(summary) = envelope.payload.summary {
5512                    let project_path = ProjectPath {
5513                        worktree_id,
5514                        path: Path::new(&summary.path).into(),
5515                    };
5516                    worktree.update(cx, |worktree, _| {
5517                        worktree
5518                            .as_remote_mut()
5519                            .unwrap()
5520                            .update_diagnostic_summary(project_path.path.clone(), &summary);
5521                    });
5522                    cx.emit(Event::DiagnosticsUpdated {
5523                        language_server_id: LanguageServerId(summary.language_server_id as usize),
5524                        path: project_path,
5525                    });
5526                }
5527            }
5528            Ok(())
5529        })
5530    }
5531
5532    async fn handle_start_language_server(
5533        this: ModelHandle<Self>,
5534        envelope: TypedEnvelope<proto::StartLanguageServer>,
5535        _: Arc<Client>,
5536        mut cx: AsyncAppContext,
5537    ) -> Result<()> {
5538        let server = envelope
5539            .payload
5540            .server
5541            .ok_or_else(|| anyhow!("invalid server"))?;
5542        this.update(&mut cx, |this, cx| {
5543            this.language_server_statuses.insert(
5544                LanguageServerId(server.id as usize),
5545                LanguageServerStatus {
5546                    name: server.name,
5547                    pending_work: Default::default(),
5548                    has_pending_diagnostic_updates: false,
5549                    progress_tokens: Default::default(),
5550                },
5551            );
5552            cx.notify();
5553        });
5554        Ok(())
5555    }
5556
5557    async fn handle_update_language_server(
5558        this: ModelHandle<Self>,
5559        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5560        _: Arc<Client>,
5561        mut cx: AsyncAppContext,
5562    ) -> Result<()> {
5563        this.update(&mut cx, |this, cx| {
5564            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
5565
5566            match envelope
5567                .payload
5568                .variant
5569                .ok_or_else(|| anyhow!("invalid variant"))?
5570            {
5571                proto::update_language_server::Variant::WorkStart(payload) => {
5572                    this.on_lsp_work_start(
5573                        language_server_id,
5574                        payload.token,
5575                        LanguageServerProgress {
5576                            message: payload.message,
5577                            percentage: payload.percentage.map(|p| p as usize),
5578                            last_update_at: Instant::now(),
5579                        },
5580                        cx,
5581                    );
5582                }
5583
5584                proto::update_language_server::Variant::WorkProgress(payload) => {
5585                    this.on_lsp_work_progress(
5586                        language_server_id,
5587                        payload.token,
5588                        LanguageServerProgress {
5589                            message: payload.message,
5590                            percentage: payload.percentage.map(|p| p as usize),
5591                            last_update_at: Instant::now(),
5592                        },
5593                        cx,
5594                    );
5595                }
5596
5597                proto::update_language_server::Variant::WorkEnd(payload) => {
5598                    this.on_lsp_work_end(language_server_id, payload.token, cx);
5599                }
5600
5601                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5602                    this.disk_based_diagnostics_started(language_server_id, cx);
5603                }
5604
5605                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5606                    this.disk_based_diagnostics_finished(language_server_id, cx)
5607                }
5608            }
5609
5610            Ok(())
5611        })
5612    }
5613
5614    async fn handle_update_buffer(
5615        this: ModelHandle<Self>,
5616        envelope: TypedEnvelope<proto::UpdateBuffer>,
5617        _: Arc<Client>,
5618        mut cx: AsyncAppContext,
5619    ) -> Result<proto::Ack> {
5620        this.update(&mut cx, |this, cx| {
5621            let payload = envelope.payload.clone();
5622            let buffer_id = payload.buffer_id;
5623            let ops = payload
5624                .operations
5625                .into_iter()
5626                .map(language::proto::deserialize_operation)
5627                .collect::<Result<Vec<_>, _>>()?;
5628            let is_remote = this.is_remote();
5629            match this.opened_buffers.entry(buffer_id) {
5630                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5631                    OpenBuffer::Strong(buffer) => {
5632                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5633                    }
5634                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5635                    OpenBuffer::Weak(_) => {}
5636                },
5637                hash_map::Entry::Vacant(e) => {
5638                    assert!(
5639                        is_remote,
5640                        "received buffer update from {:?}",
5641                        envelope.original_sender_id
5642                    );
5643                    e.insert(OpenBuffer::Operations(ops));
5644                }
5645            }
5646            Ok(proto::Ack {})
5647        })
5648    }
5649
5650    async fn handle_create_buffer_for_peer(
5651        this: ModelHandle<Self>,
5652        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5653        _: Arc<Client>,
5654        mut cx: AsyncAppContext,
5655    ) -> Result<()> {
5656        this.update(&mut cx, |this, cx| {
5657            match envelope
5658                .payload
5659                .variant
5660                .ok_or_else(|| anyhow!("missing variant"))?
5661            {
5662                proto::create_buffer_for_peer::Variant::State(mut state) => {
5663                    let mut buffer_file = None;
5664                    if let Some(file) = state.file.take() {
5665                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
5666                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5667                            anyhow!("no worktree found for id {}", file.worktree_id)
5668                        })?;
5669                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5670                            as Arc<dyn language::File>);
5671                    }
5672
5673                    let buffer_id = state.id;
5674                    let buffer = cx.add_model(|_| {
5675                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5676                    });
5677                    this.incomplete_remote_buffers
5678                        .insert(buffer_id, Some(buffer));
5679                }
5680                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5681                    let buffer = this
5682                        .incomplete_remote_buffers
5683                        .get(&chunk.buffer_id)
5684                        .cloned()
5685                        .flatten()
5686                        .ok_or_else(|| {
5687                            anyhow!(
5688                                "received chunk for buffer {} without initial state",
5689                                chunk.buffer_id
5690                            )
5691                        })?;
5692                    let operations = chunk
5693                        .operations
5694                        .into_iter()
5695                        .map(language::proto::deserialize_operation)
5696                        .collect::<Result<Vec<_>>>()?;
5697                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5698
5699                    if chunk.is_last {
5700                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5701                        this.register_buffer(&buffer, cx)?;
5702                    }
5703                }
5704            }
5705
5706            Ok(())
5707        })
5708    }
5709
5710    async fn handle_update_diff_base(
5711        this: ModelHandle<Self>,
5712        envelope: TypedEnvelope<proto::UpdateDiffBase>,
5713        _: Arc<Client>,
5714        mut cx: AsyncAppContext,
5715    ) -> Result<()> {
5716        this.update(&mut cx, |this, cx| {
5717            let buffer_id = envelope.payload.buffer_id;
5718            let diff_base = envelope.payload.diff_base;
5719            if let Some(buffer) = this
5720                .opened_buffers
5721                .get_mut(&buffer_id)
5722                .and_then(|b| b.upgrade(cx))
5723                .or_else(|| {
5724                    this.incomplete_remote_buffers
5725                        .get(&buffer_id)
5726                        .cloned()
5727                        .flatten()
5728                })
5729            {
5730                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5731            }
5732            Ok(())
5733        })
5734    }
5735
5736    async fn handle_update_buffer_file(
5737        this: ModelHandle<Self>,
5738        envelope: TypedEnvelope<proto::UpdateBufferFile>,
5739        _: Arc<Client>,
5740        mut cx: AsyncAppContext,
5741    ) -> Result<()> {
5742        let buffer_id = envelope.payload.buffer_id;
5743
5744        this.update(&mut cx, |this, cx| {
5745            let payload = envelope.payload.clone();
5746            if let Some(buffer) = this
5747                .opened_buffers
5748                .get(&buffer_id)
5749                .and_then(|b| b.upgrade(cx))
5750                .or_else(|| {
5751                    this.incomplete_remote_buffers
5752                        .get(&buffer_id)
5753                        .cloned()
5754                        .flatten()
5755                })
5756            {
5757                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5758                let worktree = this
5759                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5760                    .ok_or_else(|| anyhow!("no such worktree"))?;
5761                let file = File::from_proto(file, worktree, cx)?;
5762                buffer.update(cx, |buffer, cx| {
5763                    buffer.file_updated(Arc::new(file), cx).detach();
5764                });
5765                this.detect_language_for_buffer(&buffer, cx);
5766            }
5767            Ok(())
5768        })
5769    }
5770
5771    async fn handle_save_buffer(
5772        this: ModelHandle<Self>,
5773        envelope: TypedEnvelope<proto::SaveBuffer>,
5774        _: Arc<Client>,
5775        mut cx: AsyncAppContext,
5776    ) -> Result<proto::BufferSaved> {
5777        let buffer_id = envelope.payload.buffer_id;
5778        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5779            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5780            let buffer = this
5781                .opened_buffers
5782                .get(&buffer_id)
5783                .and_then(|buffer| buffer.upgrade(cx))
5784                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5785            anyhow::Ok((project_id, buffer))
5786        })?;
5787        buffer
5788            .update(&mut cx, |buffer, _| {
5789                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
5790            })
5791            .await?;
5792        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
5793
5794        let (saved_version, fingerprint, mtime) = this
5795            .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5796            .await?;
5797        Ok(proto::BufferSaved {
5798            project_id,
5799            buffer_id,
5800            version: serialize_version(&saved_version),
5801            mtime: Some(mtime.into()),
5802            fingerprint: language::proto::serialize_fingerprint(fingerprint),
5803        })
5804    }
5805
5806    async fn handle_reload_buffers(
5807        this: ModelHandle<Self>,
5808        envelope: TypedEnvelope<proto::ReloadBuffers>,
5809        _: Arc<Client>,
5810        mut cx: AsyncAppContext,
5811    ) -> Result<proto::ReloadBuffersResponse> {
5812        let sender_id = envelope.original_sender_id()?;
5813        let reload = this.update(&mut cx, |this, cx| {
5814            let mut buffers = HashSet::default();
5815            for buffer_id in &envelope.payload.buffer_ids {
5816                buffers.insert(
5817                    this.opened_buffers
5818                        .get(buffer_id)
5819                        .and_then(|buffer| buffer.upgrade(cx))
5820                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5821                );
5822            }
5823            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5824        })?;
5825
5826        let project_transaction = reload.await?;
5827        let project_transaction = this.update(&mut cx, |this, cx| {
5828            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5829        });
5830        Ok(proto::ReloadBuffersResponse {
5831            transaction: Some(project_transaction),
5832        })
5833    }
5834
5835    async fn handle_synchronize_buffers(
5836        this: ModelHandle<Self>,
5837        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5838        _: Arc<Client>,
5839        mut cx: AsyncAppContext,
5840    ) -> Result<proto::SynchronizeBuffersResponse> {
5841        let project_id = envelope.payload.project_id;
5842        let mut response = proto::SynchronizeBuffersResponse {
5843            buffers: Default::default(),
5844        };
5845
5846        this.update(&mut cx, |this, cx| {
5847            let Some(guest_id) = envelope.original_sender_id else {
5848                log::error!("missing original_sender_id on SynchronizeBuffers request");
5849                return;
5850            };
5851
5852            this.shared_buffers.entry(guest_id).or_default().clear();
5853            for buffer in envelope.payload.buffers {
5854                let buffer_id = buffer.id;
5855                let remote_version = language::proto::deserialize_version(&buffer.version);
5856                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5857                    this.shared_buffers
5858                        .entry(guest_id)
5859                        .or_default()
5860                        .insert(buffer_id);
5861
5862                    let buffer = buffer.read(cx);
5863                    response.buffers.push(proto::BufferVersion {
5864                        id: buffer_id,
5865                        version: language::proto::serialize_version(&buffer.version),
5866                    });
5867
5868                    let operations = buffer.serialize_ops(Some(remote_version), cx);
5869                    let client = this.client.clone();
5870                    if let Some(file) = buffer.file() {
5871                        client
5872                            .send(proto::UpdateBufferFile {
5873                                project_id,
5874                                buffer_id: buffer_id as u64,
5875                                file: Some(file.to_proto()),
5876                            })
5877                            .log_err();
5878                    }
5879
5880                    client
5881                        .send(proto::UpdateDiffBase {
5882                            project_id,
5883                            buffer_id: buffer_id as u64,
5884                            diff_base: buffer.diff_base().map(Into::into),
5885                        })
5886                        .log_err();
5887
5888                    client
5889                        .send(proto::BufferReloaded {
5890                            project_id,
5891                            buffer_id,
5892                            version: language::proto::serialize_version(buffer.saved_version()),
5893                            mtime: Some(buffer.saved_mtime().into()),
5894                            fingerprint: language::proto::serialize_fingerprint(
5895                                buffer.saved_version_fingerprint(),
5896                            ),
5897                            line_ending: language::proto::serialize_line_ending(
5898                                buffer.line_ending(),
5899                            ) as i32,
5900                        })
5901                        .log_err();
5902
5903                    cx.background()
5904                        .spawn(
5905                            async move {
5906                                let operations = operations.await;
5907                                for chunk in split_operations(operations) {
5908                                    client
5909                                        .request(proto::UpdateBuffer {
5910                                            project_id,
5911                                            buffer_id,
5912                                            operations: chunk,
5913                                        })
5914                                        .await?;
5915                                }
5916                                anyhow::Ok(())
5917                            }
5918                            .log_err(),
5919                        )
5920                        .detach();
5921                }
5922            }
5923        });
5924
5925        Ok(response)
5926    }
5927
5928    async fn handle_format_buffers(
5929        this: ModelHandle<Self>,
5930        envelope: TypedEnvelope<proto::FormatBuffers>,
5931        _: Arc<Client>,
5932        mut cx: AsyncAppContext,
5933    ) -> Result<proto::FormatBuffersResponse> {
5934        let sender_id = envelope.original_sender_id()?;
5935        let format = this.update(&mut cx, |this, cx| {
5936            let mut buffers = HashSet::default();
5937            for buffer_id in &envelope.payload.buffer_ids {
5938                buffers.insert(
5939                    this.opened_buffers
5940                        .get(buffer_id)
5941                        .and_then(|buffer| buffer.upgrade(cx))
5942                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5943                );
5944            }
5945            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5946            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5947        })?;
5948
5949        let project_transaction = format.await?;
5950        let project_transaction = this.update(&mut cx, |this, cx| {
5951            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5952        });
5953        Ok(proto::FormatBuffersResponse {
5954            transaction: Some(project_transaction),
5955        })
5956    }
5957
5958    async fn handle_apply_additional_edits_for_completion(
5959        this: ModelHandle<Self>,
5960        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5961        _: Arc<Client>,
5962        mut cx: AsyncAppContext,
5963    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5964        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5965            let buffer = this
5966                .opened_buffers
5967                .get(&envelope.payload.buffer_id)
5968                .and_then(|buffer| buffer.upgrade(cx))
5969                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5970            let language = buffer.read(cx).language();
5971            let completion = language::proto::deserialize_completion(
5972                envelope
5973                    .payload
5974                    .completion
5975                    .ok_or_else(|| anyhow!("invalid completion"))?,
5976                language.cloned(),
5977            );
5978            Ok::<_, anyhow::Error>((buffer, completion))
5979        })?;
5980
5981        let completion = completion.await?;
5982
5983        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5984            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5985        });
5986
5987        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5988            transaction: apply_additional_edits
5989                .await?
5990                .as_ref()
5991                .map(language::proto::serialize_transaction),
5992        })
5993    }
5994
5995    async fn handle_apply_code_action(
5996        this: ModelHandle<Self>,
5997        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5998        _: Arc<Client>,
5999        mut cx: AsyncAppContext,
6000    ) -> Result<proto::ApplyCodeActionResponse> {
6001        let sender_id = envelope.original_sender_id()?;
6002        let action = language::proto::deserialize_code_action(
6003            envelope
6004                .payload
6005                .action
6006                .ok_or_else(|| anyhow!("invalid action"))?,
6007        )?;
6008        let apply_code_action = this.update(&mut cx, |this, cx| {
6009            let buffer = this
6010                .opened_buffers
6011                .get(&envelope.payload.buffer_id)
6012                .and_then(|buffer| buffer.upgrade(cx))
6013                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6014            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
6015        })?;
6016
6017        let project_transaction = apply_code_action.await?;
6018        let project_transaction = this.update(&mut cx, |this, cx| {
6019            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6020        });
6021        Ok(proto::ApplyCodeActionResponse {
6022            transaction: Some(project_transaction),
6023        })
6024    }
6025
6026    async fn handle_on_type_formatting(
6027        this: ModelHandle<Self>,
6028        envelope: TypedEnvelope<proto::OnTypeFormatting>,
6029        _: Arc<Client>,
6030        mut cx: AsyncAppContext,
6031    ) -> Result<proto::OnTypeFormattingResponse> {
6032        let on_type_formatting = this.update(&mut cx, |this, cx| {
6033            let buffer = this
6034                .opened_buffers
6035                .get(&envelope.payload.buffer_id)
6036                .and_then(|buffer| buffer.upgrade(cx))
6037                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6038            let position = envelope
6039                .payload
6040                .position
6041                .and_then(deserialize_anchor)
6042                .ok_or_else(|| anyhow!("invalid position"))?;
6043            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
6044                buffer,
6045                position,
6046                envelope.payload.trigger.clone(),
6047                cx,
6048            ))
6049        })?;
6050
6051        let transaction = on_type_formatting
6052            .await?
6053            .as_ref()
6054            .map(language::proto::serialize_transaction);
6055        Ok(proto::OnTypeFormattingResponse { transaction })
6056    }
6057
6058    async fn handle_lsp_command<T: LspCommand>(
6059        this: ModelHandle<Self>,
6060        envelope: TypedEnvelope<T::ProtoRequest>,
6061        _: Arc<Client>,
6062        mut cx: AsyncAppContext,
6063    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
6064    where
6065        <T::LspRequest as lsp::request::Request>::Result: Send,
6066    {
6067        let sender_id = envelope.original_sender_id()?;
6068        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
6069        let buffer_handle = this.read_with(&cx, |this, _| {
6070            this.opened_buffers
6071                .get(&buffer_id)
6072                .and_then(|buffer| buffer.upgrade(&cx))
6073                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
6074        })?;
6075        let request = T::from_proto(
6076            envelope.payload,
6077            this.clone(),
6078            buffer_handle.clone(),
6079            cx.clone(),
6080        )
6081        .await?;
6082        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
6083        let response = this
6084            .update(&mut cx, |this, cx| {
6085                this.request_lsp(buffer_handle, request, cx)
6086            })
6087            .await?;
6088        this.update(&mut cx, |this, cx| {
6089            Ok(T::response_to_proto(
6090                response,
6091                this,
6092                sender_id,
6093                &buffer_version,
6094                cx,
6095            ))
6096        })
6097    }
6098
6099    async fn handle_get_project_symbols(
6100        this: ModelHandle<Self>,
6101        envelope: TypedEnvelope<proto::GetProjectSymbols>,
6102        _: Arc<Client>,
6103        mut cx: AsyncAppContext,
6104    ) -> Result<proto::GetProjectSymbolsResponse> {
6105        let symbols = this
6106            .update(&mut cx, |this, cx| {
6107                this.symbols(&envelope.payload.query, cx)
6108            })
6109            .await?;
6110
6111        Ok(proto::GetProjectSymbolsResponse {
6112            symbols: symbols.iter().map(serialize_symbol).collect(),
6113        })
6114    }
6115
6116    async fn handle_search_project(
6117        this: ModelHandle<Self>,
6118        envelope: TypedEnvelope<proto::SearchProject>,
6119        _: Arc<Client>,
6120        mut cx: AsyncAppContext,
6121    ) -> Result<proto::SearchProjectResponse> {
6122        let peer_id = envelope.original_sender_id()?;
6123        let query = SearchQuery::from_proto(envelope.payload)?;
6124        let result = this
6125            .update(&mut cx, |this, cx| this.search(query, cx))
6126            .await?;
6127
6128        this.update(&mut cx, |this, cx| {
6129            let mut locations = Vec::new();
6130            for (buffer, ranges) in result {
6131                for range in ranges {
6132                    let start = serialize_anchor(&range.start);
6133                    let end = serialize_anchor(&range.end);
6134                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
6135                    locations.push(proto::Location {
6136                        buffer_id,
6137                        start: Some(start),
6138                        end: Some(end),
6139                    });
6140                }
6141            }
6142            Ok(proto::SearchProjectResponse { locations })
6143        })
6144    }
6145
6146    async fn handle_open_buffer_for_symbol(
6147        this: ModelHandle<Self>,
6148        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
6149        _: Arc<Client>,
6150        mut cx: AsyncAppContext,
6151    ) -> Result<proto::OpenBufferForSymbolResponse> {
6152        let peer_id = envelope.original_sender_id()?;
6153        let symbol = envelope
6154            .payload
6155            .symbol
6156            .ok_or_else(|| anyhow!("invalid symbol"))?;
6157        let symbol = this
6158            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
6159            .await?;
6160        let symbol = this.read_with(&cx, |this, _| {
6161            let signature = this.symbol_signature(&symbol.path);
6162            if signature == symbol.signature {
6163                Ok(symbol)
6164            } else {
6165                Err(anyhow!("invalid symbol signature"))
6166            }
6167        })?;
6168        let buffer = this
6169            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
6170            .await?;
6171
6172        Ok(proto::OpenBufferForSymbolResponse {
6173            buffer_id: this.update(&mut cx, |this, cx| {
6174                this.create_buffer_for_peer(&buffer, peer_id, cx)
6175            }),
6176        })
6177    }
6178
6179    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
6180        let mut hasher = Sha256::new();
6181        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
6182        hasher.update(project_path.path.to_string_lossy().as_bytes());
6183        hasher.update(self.nonce.to_be_bytes());
6184        hasher.finalize().as_slice().try_into().unwrap()
6185    }
6186
6187    async fn handle_open_buffer_by_id(
6188        this: ModelHandle<Self>,
6189        envelope: TypedEnvelope<proto::OpenBufferById>,
6190        _: Arc<Client>,
6191        mut cx: AsyncAppContext,
6192    ) -> Result<proto::OpenBufferResponse> {
6193        let peer_id = envelope.original_sender_id()?;
6194        let buffer = this
6195            .update(&mut cx, |this, cx| {
6196                this.open_buffer_by_id(envelope.payload.id, cx)
6197            })
6198            .await?;
6199        this.update(&mut cx, |this, cx| {
6200            Ok(proto::OpenBufferResponse {
6201                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6202            })
6203        })
6204    }
6205
6206    async fn handle_open_buffer_by_path(
6207        this: ModelHandle<Self>,
6208        envelope: TypedEnvelope<proto::OpenBufferByPath>,
6209        _: Arc<Client>,
6210        mut cx: AsyncAppContext,
6211    ) -> Result<proto::OpenBufferResponse> {
6212        let peer_id = envelope.original_sender_id()?;
6213        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6214        let open_buffer = this.update(&mut cx, |this, cx| {
6215            this.open_buffer(
6216                ProjectPath {
6217                    worktree_id,
6218                    path: PathBuf::from(envelope.payload.path).into(),
6219                },
6220                cx,
6221            )
6222        });
6223
6224        let buffer = open_buffer.await?;
6225        this.update(&mut cx, |this, cx| {
6226            Ok(proto::OpenBufferResponse {
6227                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6228            })
6229        })
6230    }
6231
6232    fn serialize_project_transaction_for_peer(
6233        &mut self,
6234        project_transaction: ProjectTransaction,
6235        peer_id: proto::PeerId,
6236        cx: &mut AppContext,
6237    ) -> proto::ProjectTransaction {
6238        let mut serialized_transaction = proto::ProjectTransaction {
6239            buffer_ids: Default::default(),
6240            transactions: Default::default(),
6241        };
6242        for (buffer, transaction) in project_transaction.0 {
6243            serialized_transaction
6244                .buffer_ids
6245                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
6246            serialized_transaction
6247                .transactions
6248                .push(language::proto::serialize_transaction(&transaction));
6249        }
6250        serialized_transaction
6251    }
6252
6253    fn deserialize_project_transaction(
6254        &mut self,
6255        message: proto::ProjectTransaction,
6256        push_to_history: bool,
6257        cx: &mut ModelContext<Self>,
6258    ) -> Task<Result<ProjectTransaction>> {
6259        cx.spawn(|this, mut cx| async move {
6260            let mut project_transaction = ProjectTransaction::default();
6261            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
6262            {
6263                let buffer = this
6264                    .update(&mut cx, |this, cx| {
6265                        this.wait_for_remote_buffer(buffer_id, cx)
6266                    })
6267                    .await?;
6268                let transaction = language::proto::deserialize_transaction(transaction)?;
6269                project_transaction.0.insert(buffer, transaction);
6270            }
6271
6272            for (buffer, transaction) in &project_transaction.0 {
6273                buffer
6274                    .update(&mut cx, |buffer, _| {
6275                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
6276                    })
6277                    .await?;
6278
6279                if push_to_history {
6280                    buffer.update(&mut cx, |buffer, _| {
6281                        buffer.push_transaction(transaction.clone(), Instant::now());
6282                    });
6283                }
6284            }
6285
6286            Ok(project_transaction)
6287        })
6288    }
6289
6290    fn create_buffer_for_peer(
6291        &mut self,
6292        buffer: &ModelHandle<Buffer>,
6293        peer_id: proto::PeerId,
6294        cx: &mut AppContext,
6295    ) -> u64 {
6296        let buffer_id = buffer.read(cx).remote_id();
6297        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
6298            updates_tx
6299                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
6300                .ok();
6301        }
6302        buffer_id
6303    }
6304
6305    fn wait_for_remote_buffer(
6306        &mut self,
6307        id: u64,
6308        cx: &mut ModelContext<Self>,
6309    ) -> Task<Result<ModelHandle<Buffer>>> {
6310        let mut opened_buffer_rx = self.opened_buffer.1.clone();
6311
6312        cx.spawn_weak(|this, mut cx| async move {
6313            let buffer = loop {
6314                let Some(this) = this.upgrade(&cx) else {
6315                    return Err(anyhow!("project dropped"));
6316                };
6317
6318                let buffer = this.read_with(&cx, |this, cx| {
6319                    this.opened_buffers
6320                        .get(&id)
6321                        .and_then(|buffer| buffer.upgrade(cx))
6322                });
6323
6324                if let Some(buffer) = buffer {
6325                    break buffer;
6326                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
6327                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
6328                }
6329
6330                this.update(&mut cx, |this, _| {
6331                    this.incomplete_remote_buffers.entry(id).or_default();
6332                });
6333                drop(this);
6334
6335                opened_buffer_rx
6336                    .next()
6337                    .await
6338                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
6339            };
6340
6341            Ok(buffer)
6342        })
6343    }
6344
6345    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
6346        let project_id = match self.client_state.as_ref() {
6347            Some(ProjectClientState::Remote {
6348                sharing_has_stopped,
6349                remote_id,
6350                ..
6351            }) => {
6352                if *sharing_has_stopped {
6353                    return Task::ready(Err(anyhow!(
6354                        "can't synchronize remote buffers on a readonly project"
6355                    )));
6356                } else {
6357                    *remote_id
6358                }
6359            }
6360            Some(ProjectClientState::Local { .. }) | None => {
6361                return Task::ready(Err(anyhow!(
6362                    "can't synchronize remote buffers on a local project"
6363                )))
6364            }
6365        };
6366
6367        let client = self.client.clone();
6368        cx.spawn(|this, cx| async move {
6369            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
6370                let buffers = this
6371                    .opened_buffers
6372                    .iter()
6373                    .filter_map(|(id, buffer)| {
6374                        let buffer = buffer.upgrade(cx)?;
6375                        Some(proto::BufferVersion {
6376                            id: *id,
6377                            version: language::proto::serialize_version(&buffer.read(cx).version),
6378                        })
6379                    })
6380                    .collect();
6381                let incomplete_buffer_ids = this
6382                    .incomplete_remote_buffers
6383                    .keys()
6384                    .copied()
6385                    .collect::<Vec<_>>();
6386
6387                (buffers, incomplete_buffer_ids)
6388            });
6389            let response = client
6390                .request(proto::SynchronizeBuffers {
6391                    project_id,
6392                    buffers,
6393                })
6394                .await?;
6395
6396            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
6397                let client = client.clone();
6398                let buffer_id = buffer.id;
6399                let remote_version = language::proto::deserialize_version(&buffer.version);
6400                this.read_with(&cx, |this, cx| {
6401                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6402                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
6403                        cx.background().spawn(async move {
6404                            let operations = operations.await;
6405                            for chunk in split_operations(operations) {
6406                                client
6407                                    .request(proto::UpdateBuffer {
6408                                        project_id,
6409                                        buffer_id,
6410                                        operations: chunk,
6411                                    })
6412                                    .await?;
6413                            }
6414                            anyhow::Ok(())
6415                        })
6416                    } else {
6417                        Task::ready(Ok(()))
6418                    }
6419                })
6420            });
6421
6422            // Any incomplete buffers have open requests waiting. Request that the host sends
6423            // creates these buffers for us again to unblock any waiting futures.
6424            for id in incomplete_buffer_ids {
6425                cx.background()
6426                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
6427                    .detach();
6428            }
6429
6430            futures::future::join_all(send_updates_for_buffers)
6431                .await
6432                .into_iter()
6433                .collect()
6434        })
6435    }
6436
6437    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
6438        self.worktrees(cx)
6439            .map(|worktree| {
6440                let worktree = worktree.read(cx);
6441                proto::WorktreeMetadata {
6442                    id: worktree.id().to_proto(),
6443                    root_name: worktree.root_name().into(),
6444                    visible: worktree.is_visible(),
6445                    abs_path: worktree.abs_path().to_string_lossy().into(),
6446                }
6447            })
6448            .collect()
6449    }
6450
6451    fn set_worktrees_from_proto(
6452        &mut self,
6453        worktrees: Vec<proto::WorktreeMetadata>,
6454        cx: &mut ModelContext<Project>,
6455    ) -> Result<()> {
6456        let replica_id = self.replica_id();
6457        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
6458
6459        let mut old_worktrees_by_id = self
6460            .worktrees
6461            .drain(..)
6462            .filter_map(|worktree| {
6463                let worktree = worktree.upgrade(cx)?;
6464                Some((worktree.read(cx).id(), worktree))
6465            })
6466            .collect::<HashMap<_, _>>();
6467
6468        for worktree in worktrees {
6469            if let Some(old_worktree) =
6470                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
6471            {
6472                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
6473            } else {
6474                let worktree =
6475                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
6476                let _ = self.add_worktree(&worktree, cx);
6477            }
6478        }
6479
6480        self.metadata_changed(cx);
6481        for (id, _) in old_worktrees_by_id {
6482            cx.emit(Event::WorktreeRemoved(id));
6483        }
6484
6485        Ok(())
6486    }
6487
6488    fn set_collaborators_from_proto(
6489        &mut self,
6490        messages: Vec<proto::Collaborator>,
6491        cx: &mut ModelContext<Self>,
6492    ) -> Result<()> {
6493        let mut collaborators = HashMap::default();
6494        for message in messages {
6495            let collaborator = Collaborator::from_proto(message)?;
6496            collaborators.insert(collaborator.peer_id, collaborator);
6497        }
6498        for old_peer_id in self.collaborators.keys() {
6499            if !collaborators.contains_key(old_peer_id) {
6500                cx.emit(Event::CollaboratorLeft(*old_peer_id));
6501            }
6502        }
6503        self.collaborators = collaborators;
6504        Ok(())
6505    }
6506
6507    fn deserialize_symbol(
6508        &self,
6509        serialized_symbol: proto::Symbol,
6510    ) -> impl Future<Output = Result<Symbol>> {
6511        let languages = self.languages.clone();
6512        async move {
6513            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
6514            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
6515            let start = serialized_symbol
6516                .start
6517                .ok_or_else(|| anyhow!("invalid start"))?;
6518            let end = serialized_symbol
6519                .end
6520                .ok_or_else(|| anyhow!("invalid end"))?;
6521            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
6522            let path = ProjectPath {
6523                worktree_id,
6524                path: PathBuf::from(serialized_symbol.path).into(),
6525            };
6526            let language = languages
6527                .language_for_file(&path.path, None)
6528                .await
6529                .log_err();
6530            Ok(Symbol {
6531                language_server_name: LanguageServerName(
6532                    serialized_symbol.language_server_name.into(),
6533                ),
6534                source_worktree_id,
6535                path,
6536                label: {
6537                    match language {
6538                        Some(language) => {
6539                            language
6540                                .label_for_symbol(&serialized_symbol.name, kind)
6541                                .await
6542                        }
6543                        None => None,
6544                    }
6545                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
6546                },
6547
6548                name: serialized_symbol.name,
6549                range: Unclipped(PointUtf16::new(start.row, start.column))
6550                    ..Unclipped(PointUtf16::new(end.row, end.column)),
6551                kind,
6552                signature: serialized_symbol
6553                    .signature
6554                    .try_into()
6555                    .map_err(|_| anyhow!("invalid signature"))?,
6556            })
6557        }
6558    }
6559
6560    async fn handle_buffer_saved(
6561        this: ModelHandle<Self>,
6562        envelope: TypedEnvelope<proto::BufferSaved>,
6563        _: Arc<Client>,
6564        mut cx: AsyncAppContext,
6565    ) -> Result<()> {
6566        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
6567        let version = deserialize_version(&envelope.payload.version);
6568        let mtime = envelope
6569            .payload
6570            .mtime
6571            .ok_or_else(|| anyhow!("missing mtime"))?
6572            .into();
6573
6574        this.update(&mut cx, |this, cx| {
6575            let buffer = this
6576                .opened_buffers
6577                .get(&envelope.payload.buffer_id)
6578                .and_then(|buffer| buffer.upgrade(cx))
6579                .or_else(|| {
6580                    this.incomplete_remote_buffers
6581                        .get(&envelope.payload.buffer_id)
6582                        .and_then(|b| b.clone())
6583                });
6584            if let Some(buffer) = buffer {
6585                buffer.update(cx, |buffer, cx| {
6586                    buffer.did_save(version, fingerprint, mtime, cx);
6587                });
6588            }
6589            Ok(())
6590        })
6591    }
6592
6593    async fn handle_buffer_reloaded(
6594        this: ModelHandle<Self>,
6595        envelope: TypedEnvelope<proto::BufferReloaded>,
6596        _: Arc<Client>,
6597        mut cx: AsyncAppContext,
6598    ) -> Result<()> {
6599        let payload = envelope.payload;
6600        let version = deserialize_version(&payload.version);
6601        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
6602        let line_ending = deserialize_line_ending(
6603            proto::LineEnding::from_i32(payload.line_ending)
6604                .ok_or_else(|| anyhow!("missing line ending"))?,
6605        );
6606        let mtime = payload
6607            .mtime
6608            .ok_or_else(|| anyhow!("missing mtime"))?
6609            .into();
6610        this.update(&mut cx, |this, cx| {
6611            let buffer = this
6612                .opened_buffers
6613                .get(&payload.buffer_id)
6614                .and_then(|buffer| buffer.upgrade(cx))
6615                .or_else(|| {
6616                    this.incomplete_remote_buffers
6617                        .get(&payload.buffer_id)
6618                        .cloned()
6619                        .flatten()
6620                });
6621            if let Some(buffer) = buffer {
6622                buffer.update(cx, |buffer, cx| {
6623                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6624                });
6625            }
6626            Ok(())
6627        })
6628    }
6629
6630    #[allow(clippy::type_complexity)]
6631    fn edits_from_lsp(
6632        &mut self,
6633        buffer: &ModelHandle<Buffer>,
6634        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6635        server_id: LanguageServerId,
6636        version: Option<i32>,
6637        cx: &mut ModelContext<Self>,
6638    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6639        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
6640        cx.background().spawn(async move {
6641            let snapshot = snapshot?;
6642            let mut lsp_edits = lsp_edits
6643                .into_iter()
6644                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6645                .collect::<Vec<_>>();
6646            lsp_edits.sort_by_key(|(range, _)| range.start);
6647
6648            let mut lsp_edits = lsp_edits.into_iter().peekable();
6649            let mut edits = Vec::new();
6650            while let Some((range, mut new_text)) = lsp_edits.next() {
6651                // Clip invalid ranges provided by the language server.
6652                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6653                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
6654
6655                // Combine any LSP edits that are adjacent.
6656                //
6657                // Also, combine LSP edits that are separated from each other by only
6658                // a newline. This is important because for some code actions,
6659                // Rust-analyzer rewrites the entire buffer via a series of edits that
6660                // are separated by unchanged newline characters.
6661                //
6662                // In order for the diffing logic below to work properly, any edits that
6663                // cancel each other out must be combined into one.
6664                while let Some((next_range, next_text)) = lsp_edits.peek() {
6665                    if next_range.start.0 > range.end {
6666                        if next_range.start.0.row > range.end.row + 1
6667                            || next_range.start.0.column > 0
6668                            || snapshot.clip_point_utf16(
6669                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6670                                Bias::Left,
6671                            ) > range.end
6672                        {
6673                            break;
6674                        }
6675                        new_text.push('\n');
6676                    }
6677                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6678                    new_text.push_str(next_text);
6679                    lsp_edits.next();
6680                }
6681
6682                // For multiline edits, perform a diff of the old and new text so that
6683                // we can identify the changes more precisely, preserving the locations
6684                // of any anchors positioned in the unchanged regions.
6685                if range.end.row > range.start.row {
6686                    let mut offset = range.start.to_offset(&snapshot);
6687                    let old_text = snapshot.text_for_range(range).collect::<String>();
6688
6689                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6690                    let mut moved_since_edit = true;
6691                    for change in diff.iter_all_changes() {
6692                        let tag = change.tag();
6693                        let value = change.value();
6694                        match tag {
6695                            ChangeTag::Equal => {
6696                                offset += value.len();
6697                                moved_since_edit = true;
6698                            }
6699                            ChangeTag::Delete => {
6700                                let start = snapshot.anchor_after(offset);
6701                                let end = snapshot.anchor_before(offset + value.len());
6702                                if moved_since_edit {
6703                                    edits.push((start..end, String::new()));
6704                                } else {
6705                                    edits.last_mut().unwrap().0.end = end;
6706                                }
6707                                offset += value.len();
6708                                moved_since_edit = false;
6709                            }
6710                            ChangeTag::Insert => {
6711                                if moved_since_edit {
6712                                    let anchor = snapshot.anchor_after(offset);
6713                                    edits.push((anchor..anchor, value.to_string()));
6714                                } else {
6715                                    edits.last_mut().unwrap().1.push_str(value);
6716                                }
6717                                moved_since_edit = false;
6718                            }
6719                        }
6720                    }
6721                } else if range.end == range.start {
6722                    let anchor = snapshot.anchor_after(range.start);
6723                    edits.push((anchor..anchor, new_text));
6724                } else {
6725                    let edit_start = snapshot.anchor_after(range.start);
6726                    let edit_end = snapshot.anchor_before(range.end);
6727                    edits.push((edit_start..edit_end, new_text));
6728                }
6729            }
6730
6731            Ok(edits)
6732        })
6733    }
6734
6735    fn buffer_snapshot_for_lsp_version(
6736        &mut self,
6737        buffer: &ModelHandle<Buffer>,
6738        server_id: LanguageServerId,
6739        version: Option<i32>,
6740        cx: &AppContext,
6741    ) -> Result<TextBufferSnapshot> {
6742        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6743
6744        if let Some(version) = version {
6745            let buffer_id = buffer.read(cx).remote_id();
6746            let snapshots = self
6747                .buffer_snapshots
6748                .get_mut(&buffer_id)
6749                .and_then(|m| m.get_mut(&server_id))
6750                .ok_or_else(|| {
6751                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
6752                })?;
6753
6754            let found_snapshot = snapshots
6755                .binary_search_by_key(&version, |e| e.version)
6756                .map(|ix| snapshots[ix].snapshot.clone())
6757                .map_err(|_| {
6758                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
6759                })?;
6760
6761            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
6762            Ok(found_snapshot)
6763        } else {
6764            Ok((buffer.read(cx)).text_snapshot())
6765        }
6766    }
6767
6768    pub fn language_servers(
6769        &self,
6770    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
6771        self.language_server_ids
6772            .iter()
6773            .map(|((worktree_id, server_name), server_id)| {
6774                (*server_id, server_name.clone(), *worktree_id)
6775            })
6776    }
6777
6778    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
6779        if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
6780            Some(server.clone())
6781        } else {
6782            None
6783        }
6784    }
6785
6786    pub fn language_servers_for_buffer(
6787        &self,
6788        buffer: &Buffer,
6789        cx: &AppContext,
6790    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6791        self.language_server_ids_for_buffer(buffer, cx)
6792            .into_iter()
6793            .filter_map(|server_id| {
6794                let server = self.language_servers.get(&server_id)?;
6795                if let LanguageServerState::Running {
6796                    adapter, server, ..
6797                } = server
6798                {
6799                    Some((adapter, server))
6800                } else {
6801                    None
6802                }
6803            })
6804    }
6805
6806    fn primary_language_servers_for_buffer(
6807        &self,
6808        buffer: &Buffer,
6809        cx: &AppContext,
6810    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6811        self.language_servers_for_buffer(buffer, cx).next()
6812    }
6813
6814    fn language_server_for_buffer(
6815        &self,
6816        buffer: &Buffer,
6817        server_id: LanguageServerId,
6818        cx: &AppContext,
6819    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6820        self.language_servers_for_buffer(buffer, cx)
6821            .find(|(_, s)| s.server_id() == server_id)
6822    }
6823
6824    fn language_server_ids_for_buffer(
6825        &self,
6826        buffer: &Buffer,
6827        cx: &AppContext,
6828    ) -> Vec<LanguageServerId> {
6829        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6830            let worktree_id = file.worktree_id(cx);
6831            language
6832                .lsp_adapters()
6833                .iter()
6834                .flat_map(|adapter| {
6835                    let key = (worktree_id, adapter.name.clone());
6836                    self.language_server_ids.get(&key).copied()
6837                })
6838                .collect()
6839        } else {
6840            Vec::new()
6841        }
6842    }
6843}
6844
6845impl WorktreeHandle {
6846    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6847        match self {
6848            WorktreeHandle::Strong(handle) => Some(handle.clone()),
6849            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6850        }
6851    }
6852}
6853
6854impl OpenBuffer {
6855    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
6856        match self {
6857            OpenBuffer::Strong(handle) => Some(handle.clone()),
6858            OpenBuffer::Weak(handle) => handle.upgrade(cx),
6859            OpenBuffer::Operations(_) => None,
6860        }
6861    }
6862}
6863
6864pub struct PathMatchCandidateSet {
6865    pub snapshot: Snapshot,
6866    pub include_ignored: bool,
6867    pub include_root_name: bool,
6868}
6869
6870impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6871    type Candidates = PathMatchCandidateSetIter<'a>;
6872
6873    fn id(&self) -> usize {
6874        self.snapshot.id().to_usize()
6875    }
6876
6877    fn len(&self) -> usize {
6878        if self.include_ignored {
6879            self.snapshot.file_count()
6880        } else {
6881            self.snapshot.visible_file_count()
6882        }
6883    }
6884
6885    fn prefix(&self) -> Arc<str> {
6886        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6887            self.snapshot.root_name().into()
6888        } else if self.include_root_name {
6889            format!("{}/", self.snapshot.root_name()).into()
6890        } else {
6891            "".into()
6892        }
6893    }
6894
6895    fn candidates(&'a self, start: usize) -> Self::Candidates {
6896        PathMatchCandidateSetIter {
6897            traversal: self.snapshot.files(self.include_ignored, start),
6898        }
6899    }
6900}
6901
6902pub struct PathMatchCandidateSetIter<'a> {
6903    traversal: Traversal<'a>,
6904}
6905
6906impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6907    type Item = fuzzy::PathMatchCandidate<'a>;
6908
6909    fn next(&mut self) -> Option<Self::Item> {
6910        self.traversal.next().map(|entry| {
6911            if let EntryKind::File(char_bag) = entry.kind {
6912                fuzzy::PathMatchCandidate {
6913                    path: &entry.path,
6914                    char_bag,
6915                }
6916            } else {
6917                unreachable!()
6918            }
6919        })
6920    }
6921}
6922
6923impl Entity for Project {
6924    type Event = Event;
6925
6926    fn release(&mut self, cx: &mut gpui::AppContext) {
6927        match &self.client_state {
6928            Some(ProjectClientState::Local { .. }) => {
6929                let _ = self.unshare_internal(cx);
6930            }
6931            Some(ProjectClientState::Remote { remote_id, .. }) => {
6932                let _ = self.client.send(proto::LeaveProject {
6933                    project_id: *remote_id,
6934                });
6935                self.disconnected_from_host_internal(cx);
6936            }
6937            _ => {}
6938        }
6939    }
6940
6941    fn app_will_quit(
6942        &mut self,
6943        _: &mut AppContext,
6944    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6945        let shutdown_futures = self
6946            .language_servers
6947            .drain()
6948            .map(|(_, server_state)| async {
6949                match server_state {
6950                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6951                    LanguageServerState::Starting(starting_server) => {
6952                        starting_server.await?.shutdown()?.await
6953                    }
6954                }
6955            })
6956            .collect::<Vec<_>>();
6957
6958        Some(
6959            async move {
6960                futures::future::join_all(shutdown_futures).await;
6961            }
6962            .boxed(),
6963        )
6964    }
6965}
6966
6967impl Collaborator {
6968    fn from_proto(message: proto::Collaborator) -> Result<Self> {
6969        Ok(Self {
6970            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6971            replica_id: message.replica_id as ReplicaId,
6972        })
6973    }
6974}
6975
6976impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6977    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6978        Self {
6979            worktree_id,
6980            path: path.as_ref().into(),
6981        }
6982    }
6983}
6984
6985fn split_operations(
6986    mut operations: Vec<proto::Operation>,
6987) -> impl Iterator<Item = Vec<proto::Operation>> {
6988    #[cfg(any(test, feature = "test-support"))]
6989    const CHUNK_SIZE: usize = 5;
6990
6991    #[cfg(not(any(test, feature = "test-support")))]
6992    const CHUNK_SIZE: usize = 100;
6993
6994    let mut done = false;
6995    std::iter::from_fn(move || {
6996        if done {
6997            return None;
6998        }
6999
7000        let operations = operations
7001            .drain(..cmp::min(CHUNK_SIZE, operations.len()))
7002            .collect::<Vec<_>>();
7003        if operations.is_empty() {
7004            done = true;
7005        }
7006        Some(operations)
7007    })
7008}
7009
7010fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
7011    proto::Symbol {
7012        language_server_name: symbol.language_server_name.0.to_string(),
7013        source_worktree_id: symbol.source_worktree_id.to_proto(),
7014        worktree_id: symbol.path.worktree_id.to_proto(),
7015        path: symbol.path.path.to_string_lossy().to_string(),
7016        name: symbol.name.clone(),
7017        kind: unsafe { mem::transmute(symbol.kind) },
7018        start: Some(proto::PointUtf16 {
7019            row: symbol.range.start.0.row,
7020            column: symbol.range.start.0.column,
7021        }),
7022        end: Some(proto::PointUtf16 {
7023            row: symbol.range.end.0.row,
7024            column: symbol.range.end.0.column,
7025        }),
7026        signature: symbol.signature.to_vec(),
7027    }
7028}
7029
7030fn relativize_path(base: &Path, path: &Path) -> PathBuf {
7031    let mut path_components = path.components();
7032    let mut base_components = base.components();
7033    let mut components: Vec<Component> = Vec::new();
7034    loop {
7035        match (path_components.next(), base_components.next()) {
7036            (None, None) => break,
7037            (Some(a), None) => {
7038                components.push(a);
7039                components.extend(path_components.by_ref());
7040                break;
7041            }
7042            (None, _) => components.push(Component::ParentDir),
7043            (Some(a), Some(b)) if components.is_empty() && a == b => (),
7044            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
7045            (Some(a), Some(_)) => {
7046                components.push(Component::ParentDir);
7047                for _ in base_components {
7048                    components.push(Component::ParentDir);
7049                }
7050                components.push(a);
7051                components.extend(path_components.by_ref());
7052                break;
7053            }
7054        }
7055    }
7056    components.iter().map(|c| c.as_os_str()).collect()
7057}
7058
7059impl Item for Buffer {
7060    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
7061        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
7062    }
7063
7064    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
7065        File::from_dyn(self.file()).map(|file| ProjectPath {
7066            worktree_id: file.worktree_id(cx),
7067            path: file.path().clone(),
7068        })
7069    }
7070}
7071
7072async fn pump_loading_buffer_reciever(
7073    mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
7074) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
7075    loop {
7076        if let Some(result) = receiver.borrow().as_ref() {
7077            match result {
7078                Ok(buffer) => return Ok(buffer.to_owned()),
7079                Err(e) => return Err(e.to_owned()),
7080            }
7081        }
7082        receiver.next().await;
7083    }
7084}
7085
7086fn update_diff_base(
7087    project: &Project,
7088) -> impl Fn(Option<String>, ModelHandle<Buffer>, &mut AsyncAppContext) {
7089    let remote_id = project.remote_id();
7090    let client = project.client().clone();
7091    move |diff_base, buffer, cx| {
7092        let buffer_id = buffer.update(cx, |buffer, cx| {
7093            buffer.set_diff_base(diff_base.clone(), cx);
7094            buffer.remote_id()
7095        });
7096
7097        if let Some(project_id) = remote_id {
7098            client
7099                .send(proto::UpdateDiffBase {
7100                    project_id,
7101                    buffer_id: buffer_id as u64,
7102                    diff_base,
7103                })
7104                .log_err();
7105        }
7106    }
7107}