project.rs

   1mod ignore;
   2pub mod lsp_command;
   3pub mod lsp_ext_command;
   4mod prettier_support;
   5pub mod project_settings;
   6pub mod search;
   7pub mod terminals;
   8pub mod worktree;
   9
  10#[cfg(test)]
  11mod project_tests;
  12#[cfg(test)]
  13mod worktree_tests;
  14
  15use anyhow::{anyhow, Context as _, Result};
  16use client::{proto, Client, Collaborator, TypedEnvelope, UserStore};
  17use clock::ReplicaId;
  18use collections::{hash_map, BTreeMap, HashMap, HashSet, VecDeque};
  19use copilot::Copilot;
  20use futures::{
  21    channel::{
  22        mpsc::{self, UnboundedReceiver},
  23        oneshot,
  24    },
  25    future::{try_join_all, Shared},
  26    stream::FuturesUnordered,
  27    AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
  28};
  29use globset::{Glob, GlobSet, GlobSetBuilder};
  30use gpui::{
  31    AnyModel, AppContext, AsyncAppContext, BackgroundExecutor, Context, Entity, EventEmitter,
  32    Model, ModelContext, Task, WeakModel,
  33};
  34use itertools::Itertools;
  35use language::{
  36    language_settings::{language_settings, FormatOnSave, Formatter, InlayHintKind},
  37    point_to_lsp,
  38    proto::{
  39        deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version,
  40        serialize_anchor, serialize_version, split_operations,
  41    },
  42    range_from_lsp, range_to_lsp, Bias, Buffer, BufferSnapshot, CachedLspAdapter, Capability,
  43    CodeAction, CodeLabel, Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff,
  44    Event as BufferEvent, File as _, Language, LanguageRegistry, LanguageServerName, LocalFile,
  45    LspAdapterDelegate, OffsetRangeExt, Operation, Patch, PendingLanguageServer, PointUtf16,
  46    TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction, Unclipped,
  47};
  48use log::error;
  49use lsp::{
  50    DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
  51    DocumentHighlightKind, LanguageServer, LanguageServerBinary, LanguageServerId, OneOf,
  52};
  53use lsp_command::*;
  54use node_runtime::NodeRuntime;
  55use parking_lot::Mutex;
  56use postage::watch;
  57use prettier_support::{DefaultPrettier, PrettierInstance};
  58use project_settings::{LspSettings, ProjectSettings};
  59use rand::prelude::*;
  60use search::SearchQuery;
  61use serde::Serialize;
  62use settings::{Settings, SettingsStore};
  63use sha2::{Digest, Sha256};
  64use similar::{ChangeTag, TextDiff};
  65use smol::channel::{Receiver, Sender};
  66use smol::lock::Semaphore;
  67use std::{
  68    cmp::{self, Ordering},
  69    convert::TryInto,
  70    hash::Hash,
  71    mem,
  72    num::NonZeroU32,
  73    ops::Range,
  74    path::{self, Component, Path, PathBuf},
  75    process::Stdio,
  76    str,
  77    sync::{
  78        atomic::{AtomicUsize, Ordering::SeqCst},
  79        Arc,
  80    },
  81    time::{Duration, Instant},
  82};
  83use terminals::Terminals;
  84use text::Anchor;
  85use util::{
  86    debug_panic, defer, http::HttpClient, merge_json_value_into,
  87    paths::LOCAL_SETTINGS_RELATIVE_PATH, post_inc, ResultExt, TryFutureExt as _,
  88};
  89
  90pub use fs::*;
  91#[cfg(any(test, feature = "test-support"))]
  92pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
  93pub use worktree::*;
  94
  95const MAX_SERVER_REINSTALL_ATTEMPT_COUNT: u64 = 4;
  96
  97pub trait Item {
  98    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  99    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 100}
 101
 102// Language server state is stored across 3 collections:
 103//     language_servers =>
 104//         a mapping from unique server id to LanguageServerState which can either be a task for a
 105//         server in the process of starting, or a running server with adapter and language server arcs
 106//     language_server_ids => a mapping from worktreeId and server name to the unique server id
 107//     language_server_statuses => a mapping from unique server id to the current server status
 108//
 109// Multiple worktrees can map to the same language server for example when you jump to the definition
 110// of a file in the standard library. So language_server_ids is used to look up which server is active
 111// for a given worktree and language server name
 112//
 113// When starting a language server, first the id map is checked to make sure a server isn't already available
 114// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
 115// the Starting variant of LanguageServerState is stored in the language_servers map.
 116pub struct Project {
 117    worktrees: Vec<WorktreeHandle>,
 118    active_entry: Option<ProjectEntryId>,
 119    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 120    languages: Arc<LanguageRegistry>,
 121    supplementary_language_servers:
 122        HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
 123    language_servers: HashMap<LanguageServerId, LanguageServerState>,
 124    language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
 125    language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
 126    last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
 127    client: Arc<client::Client>,
 128    next_entry_id: Arc<AtomicUsize>,
 129    join_project_response_message_id: u32,
 130    next_diagnostic_group_id: usize,
 131    user_store: Model<UserStore>,
 132    fs: Arc<dyn Fs>,
 133    client_state: Option<ProjectClientState>,
 134    collaborators: HashMap<proto::PeerId, Collaborator>,
 135    client_subscriptions: Vec<client::Subscription>,
 136    _subscriptions: Vec<gpui::Subscription>,
 137    next_buffer_id: u64,
 138    opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
 139    shared_buffers: HashMap<proto::PeerId, HashSet<u64>>,
 140    #[allow(clippy::type_complexity)]
 141    loading_buffers_by_path: HashMap<
 142        ProjectPath,
 143        postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
 144    >,
 145    #[allow(clippy::type_complexity)]
 146    loading_local_worktrees:
 147        HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
 148    opened_buffers: HashMap<u64, OpenBuffer>,
 149    local_buffer_ids_by_path: HashMap<ProjectPath, u64>,
 150    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, u64>,
 151    /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
 152    /// Used for re-issuing buffer requests when peers temporarily disconnect
 153    incomplete_remote_buffers: HashMap<u64, Option<Model<Buffer>>>,
 154    buffer_snapshots: HashMap<u64, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
 155    buffers_being_formatted: HashSet<u64>,
 156    buffers_needing_diff: HashSet<WeakModel<Buffer>>,
 157    git_diff_debouncer: DelayedDebounced,
 158    nonce: u128,
 159    _maintain_buffer_languages: Task<()>,
 160    _maintain_workspace_config: Task<Result<()>>,
 161    terminals: Terminals,
 162    copilot_lsp_subscription: Option<gpui::Subscription>,
 163    copilot_log_subscription: Option<lsp::Subscription>,
 164    current_lsp_settings: HashMap<Arc<str>, LspSettings>,
 165    node: Option<Arc<dyn NodeRuntime>>,
 166    default_prettier: DefaultPrettier,
 167    prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
 168    prettier_instances: HashMap<PathBuf, PrettierInstance>,
 169}
 170
 171struct DelayedDebounced {
 172    task: Option<Task<()>>,
 173    cancel_channel: Option<oneshot::Sender<()>>,
 174}
 175
 176pub enum LanguageServerToQuery {
 177    Primary,
 178    Other(LanguageServerId),
 179}
 180
 181impl DelayedDebounced {
 182    fn new() -> DelayedDebounced {
 183        DelayedDebounced {
 184            task: None,
 185            cancel_channel: None,
 186        }
 187    }
 188
 189    fn fire_new<F>(&mut self, delay: Duration, cx: &mut ModelContext<Project>, func: F)
 190    where
 191        F: 'static + Send + FnOnce(&mut Project, &mut ModelContext<Project>) -> Task<()>,
 192    {
 193        if let Some(channel) = self.cancel_channel.take() {
 194            _ = channel.send(());
 195        }
 196
 197        let (sender, mut receiver) = oneshot::channel::<()>();
 198        self.cancel_channel = Some(sender);
 199
 200        let previous_task = self.task.take();
 201        self.task = Some(cx.spawn(move |project, mut cx| async move {
 202            let mut timer = cx.background_executor().timer(delay).fuse();
 203            if let Some(previous_task) = previous_task {
 204                previous_task.await;
 205            }
 206
 207            futures::select_biased! {
 208                _ = receiver => return,
 209                    _ = timer => {}
 210            }
 211
 212            if let Ok(task) = project.update(&mut cx, |project, cx| (func)(project, cx)) {
 213                task.await;
 214            }
 215        }));
 216    }
 217}
 218
 219struct LspBufferSnapshot {
 220    version: i32,
 221    snapshot: TextBufferSnapshot,
 222}
 223
 224/// Message ordered with respect to buffer operations
 225enum BufferOrderedMessage {
 226    Operation {
 227        buffer_id: u64,
 228        operation: proto::Operation,
 229    },
 230    LanguageServerUpdate {
 231        language_server_id: LanguageServerId,
 232        message: proto::update_language_server::Variant,
 233    },
 234    Resync,
 235}
 236
 237enum LocalProjectUpdate {
 238    WorktreesChanged,
 239    CreateBufferForPeer {
 240        peer_id: proto::PeerId,
 241        buffer_id: u64,
 242    },
 243}
 244
 245enum OpenBuffer {
 246    Strong(Model<Buffer>),
 247    Weak(WeakModel<Buffer>),
 248    Operations(Vec<Operation>),
 249}
 250
 251#[derive(Clone)]
 252enum WorktreeHandle {
 253    Strong(Model<Worktree>),
 254    Weak(WeakModel<Worktree>),
 255}
 256
 257enum ProjectClientState {
 258    Local {
 259        remote_id: u64,
 260        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
 261        _send_updates: Task<Result<()>>,
 262    },
 263    Remote {
 264        sharing_has_stopped: bool,
 265        capability: Capability,
 266        remote_id: u64,
 267        replica_id: ReplicaId,
 268    },
 269}
 270
 271#[derive(Clone, Debug, PartialEq)]
 272pub enum Event {
 273    LanguageServerAdded(LanguageServerId),
 274    LanguageServerRemoved(LanguageServerId),
 275    LanguageServerLog(LanguageServerId, String),
 276    Notification(String),
 277    ActiveEntryChanged(Option<ProjectEntryId>),
 278    ActivateProjectPanel,
 279    WorktreeAdded,
 280    WorktreeRemoved(WorktreeId),
 281    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 282    DiskBasedDiagnosticsStarted {
 283        language_server_id: LanguageServerId,
 284    },
 285    DiskBasedDiagnosticsFinished {
 286        language_server_id: LanguageServerId,
 287    },
 288    DiagnosticsUpdated {
 289        path: ProjectPath,
 290        language_server_id: LanguageServerId,
 291    },
 292    RemoteIdChanged(Option<u64>),
 293    DisconnectedFromHost,
 294    Closed,
 295    DeletedEntry(ProjectEntryId),
 296    CollaboratorUpdated {
 297        old_peer_id: proto::PeerId,
 298        new_peer_id: proto::PeerId,
 299    },
 300    CollaboratorJoined(proto::PeerId),
 301    CollaboratorLeft(proto::PeerId),
 302    RefreshInlayHints,
 303    RevealInProjectPanel(ProjectEntryId),
 304}
 305
 306pub enum LanguageServerState {
 307    Starting(Task<Option<Arc<LanguageServer>>>),
 308
 309    Running {
 310        language: Arc<Language>,
 311        adapter: Arc<CachedLspAdapter>,
 312        server: Arc<LanguageServer>,
 313        watched_paths: HashMap<WorktreeId, GlobSet>,
 314        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
 315    },
 316}
 317
 318#[derive(Serialize)]
 319pub struct LanguageServerStatus {
 320    pub name: String,
 321    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 322    pub has_pending_diagnostic_updates: bool,
 323    progress_tokens: HashSet<String>,
 324}
 325
 326#[derive(Clone, Debug, Serialize)]
 327pub struct LanguageServerProgress {
 328    pub message: Option<String>,
 329    pub percentage: Option<usize>,
 330    #[serde(skip_serializing)]
 331    pub last_update_at: Instant,
 332}
 333
 334#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 335pub struct ProjectPath {
 336    pub worktree_id: WorktreeId,
 337    pub path: Arc<Path>,
 338}
 339
 340#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 341pub struct DiagnosticSummary {
 342    pub error_count: usize,
 343    pub warning_count: usize,
 344}
 345
 346#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 347pub struct Location {
 348    pub buffer: Model<Buffer>,
 349    pub range: Range<language::Anchor>,
 350}
 351
 352#[derive(Debug, Clone, PartialEq, Eq)]
 353pub struct InlayHint {
 354    pub position: language::Anchor,
 355    pub label: InlayHintLabel,
 356    pub kind: Option<InlayHintKind>,
 357    pub padding_left: bool,
 358    pub padding_right: bool,
 359    pub tooltip: Option<InlayHintTooltip>,
 360    pub resolve_state: ResolveState,
 361}
 362
 363#[derive(Debug, Clone, PartialEq, Eq)]
 364pub enum ResolveState {
 365    Resolved,
 366    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 367    Resolving,
 368}
 369
 370impl InlayHint {
 371    pub fn text(&self) -> String {
 372        match &self.label {
 373            InlayHintLabel::String(s) => s.to_owned(),
 374            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
 375        }
 376    }
 377}
 378
 379#[derive(Debug, Clone, PartialEq, Eq)]
 380pub enum InlayHintLabel {
 381    String(String),
 382    LabelParts(Vec<InlayHintLabelPart>),
 383}
 384
 385#[derive(Debug, Clone, PartialEq, Eq)]
 386pub struct InlayHintLabelPart {
 387    pub value: String,
 388    pub tooltip: Option<InlayHintLabelPartTooltip>,
 389    pub location: Option<(LanguageServerId, lsp::Location)>,
 390}
 391
 392#[derive(Debug, Clone, PartialEq, Eq)]
 393pub enum InlayHintTooltip {
 394    String(String),
 395    MarkupContent(MarkupContent),
 396}
 397
 398#[derive(Debug, Clone, PartialEq, Eq)]
 399pub enum InlayHintLabelPartTooltip {
 400    String(String),
 401    MarkupContent(MarkupContent),
 402}
 403
 404#[derive(Debug, Clone, PartialEq, Eq)]
 405pub struct MarkupContent {
 406    pub kind: HoverBlockKind,
 407    pub value: String,
 408}
 409
 410#[derive(Debug, Clone)]
 411pub struct LocationLink {
 412    pub origin: Option<Location>,
 413    pub target: Location,
 414}
 415
 416#[derive(Debug)]
 417pub struct DocumentHighlight {
 418    pub range: Range<language::Anchor>,
 419    pub kind: DocumentHighlightKind,
 420}
 421
 422#[derive(Clone, Debug)]
 423pub struct Symbol {
 424    pub language_server_name: LanguageServerName,
 425    pub source_worktree_id: WorktreeId,
 426    pub path: ProjectPath,
 427    pub label: CodeLabel,
 428    pub name: String,
 429    pub kind: lsp::SymbolKind,
 430    pub range: Range<Unclipped<PointUtf16>>,
 431    pub signature: [u8; 32],
 432}
 433
 434#[derive(Clone, Debug, PartialEq)]
 435pub struct HoverBlock {
 436    pub text: String,
 437    pub kind: HoverBlockKind,
 438}
 439
 440#[derive(Clone, Debug, PartialEq, Eq)]
 441pub enum HoverBlockKind {
 442    PlainText,
 443    Markdown,
 444    Code { language: String },
 445}
 446
 447#[derive(Debug)]
 448pub struct Hover {
 449    pub contents: Vec<HoverBlock>,
 450    pub range: Option<Range<language::Anchor>>,
 451    pub language: Option<Arc<Language>>,
 452}
 453
 454impl Hover {
 455    pub fn is_empty(&self) -> bool {
 456        self.contents.iter().all(|block| block.text.is_empty())
 457    }
 458}
 459
 460#[derive(Default)]
 461pub struct ProjectTransaction(pub HashMap<Model<Buffer>, language::Transaction>);
 462
 463impl DiagnosticSummary {
 464    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 465        let mut this = Self {
 466            error_count: 0,
 467            warning_count: 0,
 468        };
 469
 470        for entry in diagnostics {
 471            if entry.diagnostic.is_primary {
 472                match entry.diagnostic.severity {
 473                    DiagnosticSeverity::ERROR => this.error_count += 1,
 474                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 475                    _ => {}
 476                }
 477            }
 478        }
 479
 480        this
 481    }
 482
 483    pub fn is_empty(&self) -> bool {
 484        self.error_count == 0 && self.warning_count == 0
 485    }
 486
 487    pub fn to_proto(
 488        &self,
 489        language_server_id: LanguageServerId,
 490        path: &Path,
 491    ) -> proto::DiagnosticSummary {
 492        proto::DiagnosticSummary {
 493            path: path.to_string_lossy().to_string(),
 494            language_server_id: language_server_id.0 as u64,
 495            error_count: self.error_count as u32,
 496            warning_count: self.warning_count as u32,
 497        }
 498    }
 499}
 500
 501#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 502pub struct ProjectEntryId(usize);
 503
 504impl ProjectEntryId {
 505    pub const MAX: Self = Self(usize::MAX);
 506
 507    pub fn new(counter: &AtomicUsize) -> Self {
 508        Self(counter.fetch_add(1, SeqCst))
 509    }
 510
 511    pub fn from_proto(id: u64) -> Self {
 512        Self(id as usize)
 513    }
 514
 515    pub fn to_proto(&self) -> u64 {
 516        self.0 as u64
 517    }
 518
 519    pub fn to_usize(&self) -> usize {
 520        self.0
 521    }
 522}
 523
 524#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 525pub enum FormatTrigger {
 526    Save,
 527    Manual,
 528}
 529
 530struct ProjectLspAdapterDelegate {
 531    project: Model<Project>,
 532    http_client: Arc<dyn HttpClient>,
 533}
 534
 535// Currently, formatting operations are represented differently depending on
 536// whether they come from a language server or an external command.
 537enum FormatOperation {
 538    Lsp(Vec<(Range<Anchor>, String)>),
 539    External(Diff),
 540    Prettier(Diff),
 541}
 542
 543impl FormatTrigger {
 544    fn from_proto(value: i32) -> FormatTrigger {
 545        match value {
 546            0 => FormatTrigger::Save,
 547            1 => FormatTrigger::Manual,
 548            _ => FormatTrigger::Save,
 549        }
 550    }
 551}
 552#[derive(Clone, Debug, PartialEq)]
 553enum SearchMatchCandidate {
 554    OpenBuffer {
 555        buffer: Model<Buffer>,
 556        // This might be an unnamed file without representation on filesystem
 557        path: Option<Arc<Path>>,
 558    },
 559    Path {
 560        worktree_id: WorktreeId,
 561        is_ignored: bool,
 562        path: Arc<Path>,
 563    },
 564}
 565
 566type SearchMatchCandidateIndex = usize;
 567impl SearchMatchCandidate {
 568    fn path(&self) -> Option<Arc<Path>> {
 569        match self {
 570            SearchMatchCandidate::OpenBuffer { path, .. } => path.clone(),
 571            SearchMatchCandidate::Path { path, .. } => Some(path.clone()),
 572        }
 573    }
 574}
 575
 576impl Project {
 577    pub fn init_settings(cx: &mut AppContext) {
 578        ProjectSettings::register(cx);
 579    }
 580
 581    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
 582        Self::init_settings(cx);
 583
 584        client.add_model_message_handler(Self::handle_add_collaborator);
 585        client.add_model_message_handler(Self::handle_update_project_collaborator);
 586        client.add_model_message_handler(Self::handle_remove_collaborator);
 587        client.add_model_message_handler(Self::handle_buffer_reloaded);
 588        client.add_model_message_handler(Self::handle_buffer_saved);
 589        client.add_model_message_handler(Self::handle_start_language_server);
 590        client.add_model_message_handler(Self::handle_update_language_server);
 591        client.add_model_message_handler(Self::handle_update_project);
 592        client.add_model_message_handler(Self::handle_unshare_project);
 593        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 594        client.add_model_message_handler(Self::handle_update_buffer_file);
 595        client.add_model_request_handler(Self::handle_update_buffer);
 596        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 597        client.add_model_message_handler(Self::handle_update_worktree);
 598        client.add_model_message_handler(Self::handle_update_worktree_settings);
 599        client.add_model_request_handler(Self::handle_create_project_entry);
 600        client.add_model_request_handler(Self::handle_rename_project_entry);
 601        client.add_model_request_handler(Self::handle_copy_project_entry);
 602        client.add_model_request_handler(Self::handle_delete_project_entry);
 603        client.add_model_request_handler(Self::handle_expand_project_entry);
 604        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 605        client.add_model_request_handler(Self::handle_apply_code_action);
 606        client.add_model_request_handler(Self::handle_on_type_formatting);
 607        client.add_model_request_handler(Self::handle_inlay_hints);
 608        client.add_model_request_handler(Self::handle_resolve_inlay_hint);
 609        client.add_model_request_handler(Self::handle_refresh_inlay_hints);
 610        client.add_model_request_handler(Self::handle_reload_buffers);
 611        client.add_model_request_handler(Self::handle_synchronize_buffers);
 612        client.add_model_request_handler(Self::handle_format_buffers);
 613        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
 614        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
 615        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 616        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 617        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
 618        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 619        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 620        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 621        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 622        client.add_model_request_handler(Self::handle_search_project);
 623        client.add_model_request_handler(Self::handle_get_project_symbols);
 624        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 625        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 626        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 627        client.add_model_request_handler(Self::handle_save_buffer);
 628        client.add_model_message_handler(Self::handle_update_diff_base);
 629        client.add_model_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
 630    }
 631
 632    pub fn local(
 633        client: Arc<Client>,
 634        node: Arc<dyn NodeRuntime>,
 635        user_store: Model<UserStore>,
 636        languages: Arc<LanguageRegistry>,
 637        fs: Arc<dyn Fs>,
 638        cx: &mut AppContext,
 639    ) -> Model<Self> {
 640        cx.new_model(|cx: &mut ModelContext<Self>| {
 641            let (tx, rx) = mpsc::unbounded();
 642            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 643                .detach();
 644            let copilot_lsp_subscription =
 645                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 646            Self {
 647                worktrees: Default::default(),
 648                buffer_ordered_messages_tx: tx,
 649                collaborators: Default::default(),
 650                next_buffer_id: 0,
 651                opened_buffers: Default::default(),
 652                shared_buffers: Default::default(),
 653                incomplete_remote_buffers: Default::default(),
 654                loading_buffers_by_path: Default::default(),
 655                loading_local_worktrees: Default::default(),
 656                local_buffer_ids_by_path: Default::default(),
 657                local_buffer_ids_by_entry_id: Default::default(),
 658                buffer_snapshots: Default::default(),
 659                join_project_response_message_id: 0,
 660                client_state: None,
 661                opened_buffer: watch::channel(),
 662                client_subscriptions: Vec::new(),
 663                _subscriptions: vec![
 664                    cx.observe_global::<SettingsStore>(Self::on_settings_changed),
 665                    cx.on_release(Self::release),
 666                    cx.on_app_quit(Self::shutdown_language_servers),
 667                ],
 668                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 669                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 670                active_entry: None,
 671                languages,
 672                client,
 673                user_store,
 674                fs,
 675                next_entry_id: Default::default(),
 676                next_diagnostic_group_id: Default::default(),
 677                supplementary_language_servers: HashMap::default(),
 678                language_servers: Default::default(),
 679                language_server_ids: Default::default(),
 680                language_server_statuses: Default::default(),
 681                last_workspace_edits_by_language_server: Default::default(),
 682                buffers_being_formatted: Default::default(),
 683                buffers_needing_diff: Default::default(),
 684                git_diff_debouncer: DelayedDebounced::new(),
 685                nonce: StdRng::from_entropy().gen(),
 686                terminals: Terminals {
 687                    local_handles: Vec::new(),
 688                },
 689                copilot_lsp_subscription,
 690                copilot_log_subscription: None,
 691                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
 692                node: Some(node),
 693                default_prettier: DefaultPrettier::default(),
 694                prettiers_per_worktree: HashMap::default(),
 695                prettier_instances: HashMap::default(),
 696            }
 697        })
 698    }
 699
 700    pub async fn remote(
 701        remote_id: u64,
 702        client: Arc<Client>,
 703        user_store: Model<UserStore>,
 704        languages: Arc<LanguageRegistry>,
 705        fs: Arc<dyn Fs>,
 706        role: proto::ChannelRole,
 707        mut cx: AsyncAppContext,
 708    ) -> Result<Model<Self>> {
 709        client.authenticate_and_connect(true, &cx).await?;
 710
 711        let subscription = client.subscribe_to_entity(remote_id)?;
 712        let response = client
 713            .request_envelope(proto::JoinProject {
 714                project_id: remote_id,
 715            })
 716            .await?;
 717        let this = cx.new_model(|cx| {
 718            let replica_id = response.payload.replica_id as ReplicaId;
 719
 720            let mut worktrees = Vec::new();
 721            for worktree in response.payload.worktrees {
 722                let worktree =
 723                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
 724                worktrees.push(worktree);
 725            }
 726
 727            let (tx, rx) = mpsc::unbounded();
 728            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 729                .detach();
 730            let copilot_lsp_subscription =
 731                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 732            let mut this = Self {
 733                worktrees: Vec::new(),
 734                buffer_ordered_messages_tx: tx,
 735                loading_buffers_by_path: Default::default(),
 736                next_buffer_id: 0,
 737                opened_buffer: watch::channel(),
 738                shared_buffers: Default::default(),
 739                incomplete_remote_buffers: Default::default(),
 740                loading_local_worktrees: Default::default(),
 741                local_buffer_ids_by_path: Default::default(),
 742                local_buffer_ids_by_entry_id: Default::default(),
 743                active_entry: None,
 744                collaborators: Default::default(),
 745                join_project_response_message_id: response.message_id,
 746                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 747                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 748                languages,
 749                user_store: user_store.clone(),
 750                fs,
 751                next_entry_id: Default::default(),
 752                next_diagnostic_group_id: Default::default(),
 753                client_subscriptions: Default::default(),
 754                _subscriptions: vec![
 755                    cx.on_release(Self::release),
 756                    cx.on_app_quit(Self::shutdown_language_servers),
 757                ],
 758                client: client.clone(),
 759                client_state: Some(ProjectClientState::Remote {
 760                    sharing_has_stopped: false,
 761                    capability: Capability::ReadWrite,
 762                    remote_id,
 763                    replica_id,
 764                }),
 765                supplementary_language_servers: HashMap::default(),
 766                language_servers: Default::default(),
 767                language_server_ids: Default::default(),
 768                language_server_statuses: response
 769                    .payload
 770                    .language_servers
 771                    .into_iter()
 772                    .map(|server| {
 773                        (
 774                            LanguageServerId(server.id as usize),
 775                            LanguageServerStatus {
 776                                name: server.name,
 777                                pending_work: Default::default(),
 778                                has_pending_diagnostic_updates: false,
 779                                progress_tokens: Default::default(),
 780                            },
 781                        )
 782                    })
 783                    .collect(),
 784                last_workspace_edits_by_language_server: Default::default(),
 785                opened_buffers: Default::default(),
 786                buffers_being_formatted: Default::default(),
 787                buffers_needing_diff: Default::default(),
 788                git_diff_debouncer: DelayedDebounced::new(),
 789                buffer_snapshots: Default::default(),
 790                nonce: StdRng::from_entropy().gen(),
 791                terminals: Terminals {
 792                    local_handles: Vec::new(),
 793                },
 794                copilot_lsp_subscription,
 795                copilot_log_subscription: None,
 796                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
 797                node: None,
 798                default_prettier: DefaultPrettier::default(),
 799                prettiers_per_worktree: HashMap::default(),
 800                prettier_instances: HashMap::default(),
 801            };
 802            this.set_role(role);
 803            for worktree in worktrees {
 804                let _ = this.add_worktree(&worktree, cx);
 805            }
 806            this
 807        })?;
 808        let subscription = subscription.set_model(&this, &mut cx);
 809
 810        let user_ids = response
 811            .payload
 812            .collaborators
 813            .iter()
 814            .map(|peer| peer.user_id)
 815            .collect();
 816        user_store
 817            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
 818            .await?;
 819
 820        this.update(&mut cx, |this, cx| {
 821            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
 822            this.client_subscriptions.push(subscription);
 823            anyhow::Ok(())
 824        })??;
 825
 826        Ok(this)
 827    }
 828
 829    fn release(&mut self, cx: &mut AppContext) {
 830        match &self.client_state {
 831            Some(ProjectClientState::Local { .. }) => {
 832                let _ = self.unshare_internal(cx);
 833            }
 834            Some(ProjectClientState::Remote { remote_id, .. }) => {
 835                let _ = self.client.send(proto::LeaveProject {
 836                    project_id: *remote_id,
 837                });
 838                self.disconnected_from_host_internal(cx);
 839            }
 840            _ => {}
 841        }
 842    }
 843
 844    fn shutdown_language_servers(
 845        &mut self,
 846        _cx: &mut ModelContext<Self>,
 847    ) -> impl Future<Output = ()> {
 848        let shutdown_futures = self
 849            .language_servers
 850            .drain()
 851            .map(|(_, server_state)| async {
 852                use LanguageServerState::*;
 853                match server_state {
 854                    Running { server, .. } => server.shutdown()?.await,
 855                    Starting(task) => task.await?.shutdown()?.await,
 856                }
 857            })
 858            .collect::<Vec<_>>();
 859
 860        async move {
 861            futures::future::join_all(shutdown_futures).await;
 862        }
 863    }
 864
 865    #[cfg(any(test, feature = "test-support"))]
 866    pub async fn test(
 867        fs: Arc<dyn Fs>,
 868        root_paths: impl IntoIterator<Item = &Path>,
 869        cx: &mut gpui::TestAppContext,
 870    ) -> Model<Project> {
 871        let mut languages = LanguageRegistry::test();
 872        languages.set_executor(cx.executor());
 873        let http_client = util::http::FakeHttpClient::with_404_response();
 874        let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
 875        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
 876        let project = cx.update(|cx| {
 877            Project::local(
 878                client,
 879                node_runtime::FakeNodeRuntime::new(),
 880                user_store,
 881                Arc::new(languages),
 882                fs,
 883                cx,
 884            )
 885        });
 886        for path in root_paths {
 887            let (tree, _) = project
 888                .update(cx, |project, cx| {
 889                    project.find_or_create_local_worktree(path, true, cx)
 890                })
 891                .await
 892                .unwrap();
 893            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 894                .await;
 895        }
 896        project
 897    }
 898
 899    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 900        let mut language_servers_to_start = Vec::new();
 901        let mut language_formatters_to_check = Vec::new();
 902        for buffer in self.opened_buffers.values() {
 903            if let Some(buffer) = buffer.upgrade() {
 904                let buffer = buffer.read(cx);
 905                let buffer_file = File::from_dyn(buffer.file());
 906                let buffer_language = buffer.language();
 907                let settings = language_settings(buffer_language, buffer.file(), cx);
 908                if let Some(language) = buffer_language {
 909                    if settings.enable_language_server {
 910                        if let Some(file) = buffer_file {
 911                            language_servers_to_start
 912                                .push((file.worktree.clone(), Arc::clone(language)));
 913                        }
 914                    }
 915                    language_formatters_to_check.push((
 916                        buffer_file.map(|f| f.worktree_id(cx)),
 917                        Arc::clone(language),
 918                        settings.clone(),
 919                    ));
 920                }
 921            }
 922        }
 923
 924        let mut language_servers_to_stop = Vec::new();
 925        let mut language_servers_to_restart = Vec::new();
 926        let languages = self.languages.to_vec();
 927
 928        let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
 929        let current_lsp_settings = &self.current_lsp_settings;
 930        for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 931            let language = languages.iter().find_map(|l| {
 932                let adapter = l
 933                    .lsp_adapters()
 934                    .iter()
 935                    .find(|adapter| &adapter.name == started_lsp_name)?;
 936                Some((l, adapter))
 937            });
 938            if let Some((language, adapter)) = language {
 939                let worktree = self.worktree_for_id(*worktree_id, cx);
 940                let file = worktree.as_ref().and_then(|tree| {
 941                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
 942                });
 943                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
 944                    language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 945                } else if let Some(worktree) = worktree {
 946                    let server_name = &adapter.name.0;
 947                    match (
 948                        current_lsp_settings.get(server_name),
 949                        new_lsp_settings.get(server_name),
 950                    ) {
 951                        (None, None) => {}
 952                        (Some(_), None) | (None, Some(_)) => {
 953                            language_servers_to_restart.push((worktree, Arc::clone(language)));
 954                        }
 955                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
 956                            if current_lsp_settings != new_lsp_settings {
 957                                language_servers_to_restart.push((worktree, Arc::clone(language)));
 958                            }
 959                        }
 960                    }
 961                }
 962            }
 963        }
 964        self.current_lsp_settings = new_lsp_settings;
 965
 966        // Stop all newly-disabled language servers.
 967        for (worktree_id, adapter_name) in language_servers_to_stop {
 968            self.stop_language_server(worktree_id, adapter_name, cx)
 969                .detach();
 970        }
 971
 972        let mut prettier_plugins_by_worktree = HashMap::default();
 973        for (worktree, language, settings) in language_formatters_to_check {
 974            if let Some(plugins) =
 975                prettier_support::prettier_plugins_for_language(&language, &settings)
 976            {
 977                prettier_plugins_by_worktree
 978                    .entry(worktree)
 979                    .or_insert_with(|| HashSet::default())
 980                    .extend(plugins);
 981            }
 982        }
 983        for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
 984            self.install_default_prettier(worktree, prettier_plugins, cx);
 985        }
 986
 987        // Start all the newly-enabled language servers.
 988        for (worktree, language) in language_servers_to_start {
 989            let worktree_path = worktree.read(cx).abs_path();
 990            self.start_language_servers(&worktree, worktree_path, language, cx);
 991        }
 992
 993        // Restart all language servers with changed initialization options.
 994        for (worktree, language) in language_servers_to_restart {
 995            self.restart_language_servers(worktree, language, cx);
 996        }
 997
 998        if self.copilot_lsp_subscription.is_none() {
 999            if let Some(copilot) = Copilot::global(cx) {
1000                for buffer in self.opened_buffers.values() {
1001                    if let Some(buffer) = buffer.upgrade() {
1002                        self.register_buffer_with_copilot(&buffer, cx);
1003                    }
1004                }
1005                self.copilot_lsp_subscription = Some(subscribe_for_copilot_events(&copilot, cx));
1006            }
1007        }
1008
1009        cx.notify();
1010    }
1011
1012    pub fn buffer_for_id(&self, remote_id: u64) -> Option<Model<Buffer>> {
1013        self.opened_buffers
1014            .get(&remote_id)
1015            .and_then(|buffer| buffer.upgrade())
1016    }
1017
1018    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1019        &self.languages
1020    }
1021
1022    pub fn client(&self) -> Arc<Client> {
1023        self.client.clone()
1024    }
1025
1026    pub fn user_store(&self) -> Model<UserStore> {
1027        self.user_store.clone()
1028    }
1029
1030    pub fn opened_buffers(&self) -> Vec<Model<Buffer>> {
1031        self.opened_buffers
1032            .values()
1033            .filter_map(|b| b.upgrade())
1034            .collect()
1035    }
1036
1037    #[cfg(any(test, feature = "test-support"))]
1038    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
1039        let path = path.into();
1040        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
1041            self.opened_buffers.iter().any(|(_, buffer)| {
1042                if let Some(buffer) = buffer.upgrade() {
1043                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1044                        if file.worktree == worktree && file.path() == &path.path {
1045                            return true;
1046                        }
1047                    }
1048                }
1049                false
1050            })
1051        } else {
1052            false
1053        }
1054    }
1055
1056    pub fn fs(&self) -> &Arc<dyn Fs> {
1057        &self.fs
1058    }
1059
1060    pub fn remote_id(&self) -> Option<u64> {
1061        match self.client_state.as_ref()? {
1062            ProjectClientState::Local { remote_id, .. }
1063            | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
1064        }
1065    }
1066
1067    pub fn replica_id(&self) -> ReplicaId {
1068        match &self.client_state {
1069            Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
1070            _ => 0,
1071        }
1072    }
1073
1074    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
1075        if let Some(ProjectClientState::Local { updates_tx, .. }) = &mut self.client_state {
1076            updates_tx
1077                .unbounded_send(LocalProjectUpdate::WorktreesChanged)
1078                .ok();
1079        }
1080        cx.notify();
1081    }
1082
1083    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1084        &self.collaborators
1085    }
1086
1087    pub fn host(&self) -> Option<&Collaborator> {
1088        self.collaborators.values().find(|c| c.replica_id == 0)
1089    }
1090
1091    /// Collect all worktrees, including ones that don't appear in the project panel
1092    pub fn worktrees<'a>(&'a self) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1093        self.worktrees
1094            .iter()
1095            .filter_map(move |worktree| worktree.upgrade())
1096    }
1097
1098    /// Collect all user-visible worktrees, the ones that appear in the project panel
1099    pub fn visible_worktrees<'a>(
1100        &'a self,
1101        cx: &'a AppContext,
1102    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1103        self.worktrees.iter().filter_map(|worktree| {
1104            worktree.upgrade().and_then(|worktree| {
1105                if worktree.read(cx).is_visible() {
1106                    Some(worktree)
1107                } else {
1108                    None
1109                }
1110            })
1111        })
1112    }
1113
1114    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1115        self.visible_worktrees(cx)
1116            .map(|tree| tree.read(cx).root_name())
1117    }
1118
1119    pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
1120        self.worktrees()
1121            .find(|worktree| worktree.read(cx).id() == id)
1122    }
1123
1124    pub fn worktree_for_entry(
1125        &self,
1126        entry_id: ProjectEntryId,
1127        cx: &AppContext,
1128    ) -> Option<Model<Worktree>> {
1129        self.worktrees()
1130            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1131    }
1132
1133    pub fn worktree_id_for_entry(
1134        &self,
1135        entry_id: ProjectEntryId,
1136        cx: &AppContext,
1137    ) -> Option<WorktreeId> {
1138        self.worktree_for_entry(entry_id, cx)
1139            .map(|worktree| worktree.read(cx).id())
1140    }
1141
1142    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1143        paths.iter().all(|path| self.contains_path(path, cx))
1144    }
1145
1146    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1147        for worktree in self.worktrees() {
1148            let worktree = worktree.read(cx).as_local();
1149            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1150                return true;
1151            }
1152        }
1153        false
1154    }
1155
1156    pub fn create_entry(
1157        &mut self,
1158        project_path: impl Into<ProjectPath>,
1159        is_directory: bool,
1160        cx: &mut ModelContext<Self>,
1161    ) -> Task<Result<Option<Entry>>> {
1162        let project_path = project_path.into();
1163        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1164            return Task::ready(Ok(None));
1165        };
1166        if self.is_local() {
1167            worktree.update(cx, |worktree, cx| {
1168                worktree
1169                    .as_local_mut()
1170                    .unwrap()
1171                    .create_entry(project_path.path, is_directory, cx)
1172            })
1173        } else {
1174            let client = self.client.clone();
1175            let project_id = self.remote_id().unwrap();
1176            cx.spawn(move |_, mut cx| async move {
1177                let response = client
1178                    .request(proto::CreateProjectEntry {
1179                        worktree_id: project_path.worktree_id.to_proto(),
1180                        project_id,
1181                        path: project_path.path.to_string_lossy().into(),
1182                        is_directory,
1183                    })
1184                    .await?;
1185                match response.entry {
1186                    Some(entry) => worktree
1187                        .update(&mut cx, |worktree, cx| {
1188                            worktree.as_remote_mut().unwrap().insert_entry(
1189                                entry,
1190                                response.worktree_scan_id as usize,
1191                                cx,
1192                            )
1193                        })?
1194                        .await
1195                        .map(Some),
1196                    None => Ok(None),
1197                }
1198            })
1199        }
1200    }
1201
1202    pub fn copy_entry(
1203        &mut self,
1204        entry_id: ProjectEntryId,
1205        new_path: impl Into<Arc<Path>>,
1206        cx: &mut ModelContext<Self>,
1207    ) -> Task<Result<Option<Entry>>> {
1208        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1209            return Task::ready(Ok(None));
1210        };
1211        let new_path = new_path.into();
1212        if self.is_local() {
1213            worktree.update(cx, |worktree, cx| {
1214                worktree
1215                    .as_local_mut()
1216                    .unwrap()
1217                    .copy_entry(entry_id, new_path, cx)
1218            })
1219        } else {
1220            let client = self.client.clone();
1221            let project_id = self.remote_id().unwrap();
1222
1223            cx.spawn(move |_, mut cx| async move {
1224                let response = client
1225                    .request(proto::CopyProjectEntry {
1226                        project_id,
1227                        entry_id: entry_id.to_proto(),
1228                        new_path: new_path.to_string_lossy().into(),
1229                    })
1230                    .await?;
1231                match response.entry {
1232                    Some(entry) => worktree
1233                        .update(&mut cx, |worktree, cx| {
1234                            worktree.as_remote_mut().unwrap().insert_entry(
1235                                entry,
1236                                response.worktree_scan_id as usize,
1237                                cx,
1238                            )
1239                        })?
1240                        .await
1241                        .map(Some),
1242                    None => Ok(None),
1243                }
1244            })
1245        }
1246    }
1247
1248    pub fn rename_entry(
1249        &mut self,
1250        entry_id: ProjectEntryId,
1251        new_path: impl Into<Arc<Path>>,
1252        cx: &mut ModelContext<Self>,
1253    ) -> Task<Result<Option<Entry>>> {
1254        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1255            return Task::ready(Ok(None));
1256        };
1257        let new_path = new_path.into();
1258        if self.is_local() {
1259            worktree.update(cx, |worktree, cx| {
1260                worktree
1261                    .as_local_mut()
1262                    .unwrap()
1263                    .rename_entry(entry_id, new_path, cx)
1264            })
1265        } else {
1266            let client = self.client.clone();
1267            let project_id = self.remote_id().unwrap();
1268
1269            cx.spawn(move |_, mut cx| async move {
1270                let response = client
1271                    .request(proto::RenameProjectEntry {
1272                        project_id,
1273                        entry_id: entry_id.to_proto(),
1274                        new_path: new_path.to_string_lossy().into(),
1275                    })
1276                    .await?;
1277                match response.entry {
1278                    Some(entry) => worktree
1279                        .update(&mut cx, |worktree, cx| {
1280                            worktree.as_remote_mut().unwrap().insert_entry(
1281                                entry,
1282                                response.worktree_scan_id as usize,
1283                                cx,
1284                            )
1285                        })?
1286                        .await
1287                        .map(Some),
1288                    None => Ok(None),
1289                }
1290            })
1291        }
1292    }
1293
1294    pub fn delete_entry(
1295        &mut self,
1296        entry_id: ProjectEntryId,
1297        cx: &mut ModelContext<Self>,
1298    ) -> Option<Task<Result<()>>> {
1299        let worktree = self.worktree_for_entry(entry_id, cx)?;
1300
1301        cx.emit(Event::DeletedEntry(entry_id));
1302
1303        if self.is_local() {
1304            worktree.update(cx, |worktree, cx| {
1305                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1306            })
1307        } else {
1308            let client = self.client.clone();
1309            let project_id = self.remote_id().unwrap();
1310            Some(cx.spawn(move |_, mut cx| async move {
1311                let response = client
1312                    .request(proto::DeleteProjectEntry {
1313                        project_id,
1314                        entry_id: entry_id.to_proto(),
1315                    })
1316                    .await?;
1317                worktree
1318                    .update(&mut cx, move |worktree, cx| {
1319                        worktree.as_remote_mut().unwrap().delete_entry(
1320                            entry_id,
1321                            response.worktree_scan_id as usize,
1322                            cx,
1323                        )
1324                    })?
1325                    .await
1326            }))
1327        }
1328    }
1329
1330    pub fn expand_entry(
1331        &mut self,
1332        worktree_id: WorktreeId,
1333        entry_id: ProjectEntryId,
1334        cx: &mut ModelContext<Self>,
1335    ) -> Option<Task<Result<()>>> {
1336        let worktree = self.worktree_for_id(worktree_id, cx)?;
1337        if self.is_local() {
1338            worktree.update(cx, |worktree, cx| {
1339                worktree.as_local_mut().unwrap().expand_entry(entry_id, cx)
1340            })
1341        } else {
1342            let worktree = worktree.downgrade();
1343            let request = self.client.request(proto::ExpandProjectEntry {
1344                project_id: self.remote_id().unwrap(),
1345                entry_id: entry_id.to_proto(),
1346            });
1347            Some(cx.spawn(move |_, mut cx| async move {
1348                let response = request.await?;
1349                if let Some(worktree) = worktree.upgrade() {
1350                    worktree
1351                        .update(&mut cx, |worktree, _| {
1352                            worktree
1353                                .as_remote_mut()
1354                                .unwrap()
1355                                .wait_for_snapshot(response.worktree_scan_id as usize)
1356                        })?
1357                        .await?;
1358                }
1359                Ok(())
1360            }))
1361        }
1362    }
1363
1364    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1365        if self.client_state.is_some() {
1366            return Err(anyhow!("project was already shared"));
1367        }
1368        self.client_subscriptions.push(
1369            self.client
1370                .subscribe_to_entity(project_id)?
1371                .set_model(&cx.handle(), &mut cx.to_async()),
1372        );
1373
1374        for open_buffer in self.opened_buffers.values_mut() {
1375            match open_buffer {
1376                OpenBuffer::Strong(_) => {}
1377                OpenBuffer::Weak(buffer) => {
1378                    if let Some(buffer) = buffer.upgrade() {
1379                        *open_buffer = OpenBuffer::Strong(buffer);
1380                    }
1381                }
1382                OpenBuffer::Operations(_) => unreachable!(),
1383            }
1384        }
1385
1386        for worktree_handle in self.worktrees.iter_mut() {
1387            match worktree_handle {
1388                WorktreeHandle::Strong(_) => {}
1389                WorktreeHandle::Weak(worktree) => {
1390                    if let Some(worktree) = worktree.upgrade() {
1391                        *worktree_handle = WorktreeHandle::Strong(worktree);
1392                    }
1393                }
1394            }
1395        }
1396
1397        for (server_id, status) in &self.language_server_statuses {
1398            self.client
1399                .send(proto::StartLanguageServer {
1400                    project_id,
1401                    server: Some(proto::LanguageServer {
1402                        id: server_id.0 as u64,
1403                        name: status.name.clone(),
1404                    }),
1405                })
1406                .log_err();
1407        }
1408
1409        let store = cx.global::<SettingsStore>();
1410        for worktree in self.worktrees() {
1411            let worktree_id = worktree.read(cx).id().to_proto();
1412            for (path, content) in store.local_settings(worktree.entity_id().as_u64() as usize) {
1413                self.client
1414                    .send(proto::UpdateWorktreeSettings {
1415                        project_id,
1416                        worktree_id,
1417                        path: path.to_string_lossy().into(),
1418                        content: Some(content),
1419                    })
1420                    .log_err();
1421            }
1422        }
1423
1424        let (updates_tx, mut updates_rx) = mpsc::unbounded();
1425        let client = self.client.clone();
1426        self.client_state = Some(ProjectClientState::Local {
1427            remote_id: project_id,
1428            updates_tx,
1429            _send_updates: cx.spawn(move |this, mut cx| async move {
1430                while let Some(update) = updates_rx.next().await {
1431                    match update {
1432                        LocalProjectUpdate::WorktreesChanged => {
1433                            let worktrees = this.update(&mut cx, |this, _cx| {
1434                                this.worktrees().collect::<Vec<_>>()
1435                            })?;
1436                            let update_project = this
1437                                .update(&mut cx, |this, cx| {
1438                                    this.client.request(proto::UpdateProject {
1439                                        project_id,
1440                                        worktrees: this.worktree_metadata_protos(cx),
1441                                    })
1442                                })?
1443                                .await;
1444                            if update_project.is_ok() {
1445                                for worktree in worktrees {
1446                                    worktree.update(&mut cx, |worktree, cx| {
1447                                        let worktree = worktree.as_local_mut().unwrap();
1448                                        worktree.share(project_id, cx).detach_and_log_err(cx)
1449                                    })?;
1450                                }
1451                            }
1452                        }
1453                        LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
1454                            let buffer = this.update(&mut cx, |this, _| {
1455                                let buffer = this.opened_buffers.get(&buffer_id).unwrap();
1456                                let shared_buffers =
1457                                    this.shared_buffers.entry(peer_id).or_default();
1458                                if shared_buffers.insert(buffer_id) {
1459                                    if let OpenBuffer::Strong(buffer) = buffer {
1460                                        Some(buffer.clone())
1461                                    } else {
1462                                        None
1463                                    }
1464                                } else {
1465                                    None
1466                                }
1467                            })?;
1468
1469                            let Some(buffer) = buffer else { continue };
1470                            let operations =
1471                                buffer.update(&mut cx, |b, cx| b.serialize_ops(None, cx))?;
1472                            let operations = operations.await;
1473                            let state = buffer.update(&mut cx, |buffer, _| buffer.to_proto())?;
1474
1475                            let initial_state = proto::CreateBufferForPeer {
1476                                project_id,
1477                                peer_id: Some(peer_id),
1478                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1479                            };
1480                            if client.send(initial_state).log_err().is_some() {
1481                                let client = client.clone();
1482                                cx.background_executor()
1483                                    .spawn(async move {
1484                                        let mut chunks = split_operations(operations).peekable();
1485                                        while let Some(chunk) = chunks.next() {
1486                                            let is_last = chunks.peek().is_none();
1487                                            client.send(proto::CreateBufferForPeer {
1488                                                project_id,
1489                                                peer_id: Some(peer_id),
1490                                                variant: Some(
1491                                                    proto::create_buffer_for_peer::Variant::Chunk(
1492                                                        proto::BufferChunk {
1493                                                            buffer_id,
1494                                                            operations: chunk,
1495                                                            is_last,
1496                                                        },
1497                                                    ),
1498                                                ),
1499                                            })?;
1500                                        }
1501                                        anyhow::Ok(())
1502                                    })
1503                                    .await
1504                                    .log_err();
1505                            }
1506                        }
1507                    }
1508                }
1509                Ok(())
1510            }),
1511        });
1512
1513        self.metadata_changed(cx);
1514        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1515        cx.notify();
1516        Ok(())
1517    }
1518
1519    pub fn reshared(
1520        &mut self,
1521        message: proto::ResharedProject,
1522        cx: &mut ModelContext<Self>,
1523    ) -> Result<()> {
1524        self.shared_buffers.clear();
1525        self.set_collaborators_from_proto(message.collaborators, cx)?;
1526        self.metadata_changed(cx);
1527        Ok(())
1528    }
1529
1530    pub fn rejoined(
1531        &mut self,
1532        message: proto::RejoinedProject,
1533        message_id: u32,
1534        cx: &mut ModelContext<Self>,
1535    ) -> Result<()> {
1536        cx.update_global::<SettingsStore, _>(|store, cx| {
1537            for worktree in &self.worktrees {
1538                store
1539                    .clear_local_settings(worktree.handle_id(), cx)
1540                    .log_err();
1541            }
1542        });
1543
1544        self.join_project_response_message_id = message_id;
1545        self.set_worktrees_from_proto(message.worktrees, cx)?;
1546        self.set_collaborators_from_proto(message.collaborators, cx)?;
1547        self.language_server_statuses = message
1548            .language_servers
1549            .into_iter()
1550            .map(|server| {
1551                (
1552                    LanguageServerId(server.id as usize),
1553                    LanguageServerStatus {
1554                        name: server.name,
1555                        pending_work: Default::default(),
1556                        has_pending_diagnostic_updates: false,
1557                        progress_tokens: Default::default(),
1558                    },
1559                )
1560            })
1561            .collect();
1562        self.buffer_ordered_messages_tx
1563            .unbounded_send(BufferOrderedMessage::Resync)
1564            .unwrap();
1565        cx.notify();
1566        Ok(())
1567    }
1568
1569    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1570        self.unshare_internal(cx)?;
1571        self.metadata_changed(cx);
1572        cx.notify();
1573        Ok(())
1574    }
1575
1576    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1577        if self.is_remote() {
1578            return Err(anyhow!("attempted to unshare a remote project"));
1579        }
1580
1581        if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1582            self.collaborators.clear();
1583            self.shared_buffers.clear();
1584            self.client_subscriptions.clear();
1585
1586            for worktree_handle in self.worktrees.iter_mut() {
1587                if let WorktreeHandle::Strong(worktree) = worktree_handle {
1588                    let is_visible = worktree.update(cx, |worktree, _| {
1589                        worktree.as_local_mut().unwrap().unshare();
1590                        worktree.is_visible()
1591                    });
1592                    if !is_visible {
1593                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1594                    }
1595                }
1596            }
1597
1598            for open_buffer in self.opened_buffers.values_mut() {
1599                // Wake up any tasks waiting for peers' edits to this buffer.
1600                if let Some(buffer) = open_buffer.upgrade() {
1601                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1602                }
1603
1604                if let OpenBuffer::Strong(buffer) = open_buffer {
1605                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1606                }
1607            }
1608
1609            self.client.send(proto::UnshareProject {
1610                project_id: remote_id,
1611            })?;
1612
1613            Ok(())
1614        } else {
1615            Err(anyhow!("attempted to unshare an unshared project"))
1616        }
1617    }
1618
1619    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1620        self.disconnected_from_host_internal(cx);
1621        cx.emit(Event::DisconnectedFromHost);
1622        cx.notify();
1623    }
1624
1625    pub fn set_role(&mut self, role: proto::ChannelRole) {
1626        if let Some(ProjectClientState::Remote { capability, .. }) = &mut self.client_state {
1627            *capability = if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin
1628            {
1629                Capability::ReadWrite
1630            } else {
1631                Capability::ReadOnly
1632            };
1633        }
1634    }
1635
1636    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1637        if let Some(ProjectClientState::Remote {
1638            sharing_has_stopped,
1639            ..
1640        }) = &mut self.client_state
1641        {
1642            *sharing_has_stopped = true;
1643
1644            self.collaborators.clear();
1645
1646            for worktree in &self.worktrees {
1647                if let Some(worktree) = worktree.upgrade() {
1648                    worktree.update(cx, |worktree, _| {
1649                        if let Some(worktree) = worktree.as_remote_mut() {
1650                            worktree.disconnected_from_host();
1651                        }
1652                    });
1653                }
1654            }
1655
1656            for open_buffer in self.opened_buffers.values_mut() {
1657                // Wake up any tasks waiting for peers' edits to this buffer.
1658                if let Some(buffer) = open_buffer.upgrade() {
1659                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1660                }
1661
1662                if let OpenBuffer::Strong(buffer) = open_buffer {
1663                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1664                }
1665            }
1666
1667            // Wake up all futures currently waiting on a buffer to get opened,
1668            // to give them a chance to fail now that we've disconnected.
1669            *self.opened_buffer.0.borrow_mut() = ();
1670        }
1671    }
1672
1673    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1674        cx.emit(Event::Closed);
1675    }
1676
1677    pub fn is_disconnected(&self) -> bool {
1678        match &self.client_state {
1679            Some(ProjectClientState::Remote {
1680                sharing_has_stopped,
1681                ..
1682            }) => *sharing_has_stopped,
1683            _ => false,
1684        }
1685    }
1686
1687    pub fn capability(&self) -> Capability {
1688        match &self.client_state {
1689            Some(ProjectClientState::Remote { capability, .. }) => *capability,
1690            Some(ProjectClientState::Local { .. }) | None => Capability::ReadWrite,
1691        }
1692    }
1693
1694    pub fn is_read_only(&self) -> bool {
1695        self.is_disconnected() || self.capability() == Capability::ReadOnly
1696    }
1697
1698    pub fn is_local(&self) -> bool {
1699        match &self.client_state {
1700            Some(ProjectClientState::Remote { .. }) => false,
1701            _ => true,
1702        }
1703    }
1704
1705    pub fn is_remote(&self) -> bool {
1706        !self.is_local()
1707    }
1708
1709    pub fn create_buffer(
1710        &mut self,
1711        text: &str,
1712        language: Option<Arc<Language>>,
1713        cx: &mut ModelContext<Self>,
1714    ) -> Result<Model<Buffer>> {
1715        if self.is_remote() {
1716            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1717        }
1718        let id = post_inc(&mut self.next_buffer_id);
1719        let buffer = cx.new_model(|cx| {
1720            Buffer::new(self.replica_id(), id, text)
1721                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1722        });
1723        self.register_buffer(&buffer, cx)?;
1724        Ok(buffer)
1725    }
1726
1727    pub fn open_path(
1728        &mut self,
1729        path: ProjectPath,
1730        cx: &mut ModelContext<Self>,
1731    ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
1732        let task = self.open_buffer(path.clone(), cx);
1733        cx.spawn(move |_, cx| async move {
1734            let buffer = task.await?;
1735            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1736                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1737            })?;
1738
1739            let buffer: &AnyModel = &buffer;
1740            Ok((project_entry_id, buffer.clone()))
1741        })
1742    }
1743
1744    pub fn open_local_buffer(
1745        &mut self,
1746        abs_path: impl AsRef<Path>,
1747        cx: &mut ModelContext<Self>,
1748    ) -> Task<Result<Model<Buffer>>> {
1749        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1750            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1751        } else {
1752            Task::ready(Err(anyhow!("no such path")))
1753        }
1754    }
1755
1756    pub fn open_buffer(
1757        &mut self,
1758        path: impl Into<ProjectPath>,
1759        cx: &mut ModelContext<Self>,
1760    ) -> Task<Result<Model<Buffer>>> {
1761        let project_path = path.into();
1762        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1763            worktree
1764        } else {
1765            return Task::ready(Err(anyhow!("no such worktree")));
1766        };
1767
1768        // If there is already a buffer for the given path, then return it.
1769        let existing_buffer = self.get_open_buffer(&project_path, cx);
1770        if let Some(existing_buffer) = existing_buffer {
1771            return Task::ready(Ok(existing_buffer));
1772        }
1773
1774        let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1775            // If the given path is already being loaded, then wait for that existing
1776            // task to complete and return the same buffer.
1777            hash_map::Entry::Occupied(e) => e.get().clone(),
1778
1779            // Otherwise, record the fact that this path is now being loaded.
1780            hash_map::Entry::Vacant(entry) => {
1781                let (mut tx, rx) = postage::watch::channel();
1782                entry.insert(rx.clone());
1783
1784                let load_buffer = if worktree.read(cx).is_local() {
1785                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1786                } else {
1787                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1788                };
1789
1790                let project_path = project_path.clone();
1791                cx.spawn(move |this, mut cx| async move {
1792                    let load_result = load_buffer.await;
1793                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1794                        // Record the fact that the buffer is no longer loading.
1795                        this.loading_buffers_by_path.remove(&project_path);
1796                        let buffer = load_result.map_err(Arc::new)?;
1797                        Ok(buffer)
1798                    })?);
1799                    anyhow::Ok(())
1800                })
1801                .detach();
1802                rx
1803            }
1804        };
1805
1806        cx.background_executor().spawn(async move {
1807            wait_for_loading_buffer(loading_watch)
1808                .await
1809                .map_err(|error| anyhow!("{project_path:?} opening failure: {error:#}"))
1810        })
1811    }
1812
1813    fn open_local_buffer_internal(
1814        &mut self,
1815        path: &Arc<Path>,
1816        worktree: &Model<Worktree>,
1817        cx: &mut ModelContext<Self>,
1818    ) -> Task<Result<Model<Buffer>>> {
1819        let buffer_id = post_inc(&mut self.next_buffer_id);
1820        let load_buffer = worktree.update(cx, |worktree, cx| {
1821            let worktree = worktree.as_local_mut().unwrap();
1822            worktree.load_buffer(buffer_id, path, cx)
1823        });
1824        cx.spawn(move |this, mut cx| async move {
1825            let buffer = load_buffer.await?;
1826            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))??;
1827            Ok(buffer)
1828        })
1829    }
1830
1831    fn open_remote_buffer_internal(
1832        &mut self,
1833        path: &Arc<Path>,
1834        worktree: &Model<Worktree>,
1835        cx: &mut ModelContext<Self>,
1836    ) -> Task<Result<Model<Buffer>>> {
1837        let rpc = self.client.clone();
1838        let project_id = self.remote_id().unwrap();
1839        let remote_worktree_id = worktree.read(cx).id();
1840        let path = path.clone();
1841        let path_string = path.to_string_lossy().to_string();
1842        cx.spawn(move |this, mut cx| async move {
1843            let response = rpc
1844                .request(proto::OpenBufferByPath {
1845                    project_id,
1846                    worktree_id: remote_worktree_id.to_proto(),
1847                    path: path_string,
1848                })
1849                .await?;
1850            this.update(&mut cx, |this, cx| {
1851                this.wait_for_remote_buffer(response.buffer_id, cx)
1852            })?
1853            .await
1854        })
1855    }
1856
1857    /// LanguageServerName is owned, because it is inserted into a map
1858    pub fn open_local_buffer_via_lsp(
1859        &mut self,
1860        abs_path: lsp::Url,
1861        language_server_id: LanguageServerId,
1862        language_server_name: LanguageServerName,
1863        cx: &mut ModelContext<Self>,
1864    ) -> Task<Result<Model<Buffer>>> {
1865        cx.spawn(move |this, mut cx| async move {
1866            let abs_path = abs_path
1867                .to_file_path()
1868                .map_err(|_| anyhow!("can't convert URI to path"))?;
1869            let (worktree, relative_path) = if let Some(result) =
1870                this.update(&mut cx, |this, cx| this.find_local_worktree(&abs_path, cx))?
1871            {
1872                result
1873            } else {
1874                let worktree = this
1875                    .update(&mut cx, |this, cx| {
1876                        this.create_local_worktree(&abs_path, false, cx)
1877                    })?
1878                    .await?;
1879                this.update(&mut cx, |this, cx| {
1880                    this.language_server_ids.insert(
1881                        (worktree.read(cx).id(), language_server_name),
1882                        language_server_id,
1883                    );
1884                })
1885                .ok();
1886                (worktree, PathBuf::new())
1887            };
1888
1889            let project_path = ProjectPath {
1890                worktree_id: worktree.update(&mut cx, |worktree, _| worktree.id())?,
1891                path: relative_path.into(),
1892            };
1893            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))?
1894                .await
1895        })
1896    }
1897
1898    pub fn open_buffer_by_id(
1899        &mut self,
1900        id: u64,
1901        cx: &mut ModelContext<Self>,
1902    ) -> Task<Result<Model<Buffer>>> {
1903        if let Some(buffer) = self.buffer_for_id(id) {
1904            Task::ready(Ok(buffer))
1905        } else if self.is_local() {
1906            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1907        } else if let Some(project_id) = self.remote_id() {
1908            let request = self
1909                .client
1910                .request(proto::OpenBufferById { project_id, id });
1911            cx.spawn(move |this, mut cx| async move {
1912                let buffer_id = request.await?.buffer_id;
1913                this.update(&mut cx, |this, cx| {
1914                    this.wait_for_remote_buffer(buffer_id, cx)
1915                })?
1916                .await
1917            })
1918        } else {
1919            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1920        }
1921    }
1922
1923    pub fn save_buffers(
1924        &self,
1925        buffers: HashSet<Model<Buffer>>,
1926        cx: &mut ModelContext<Self>,
1927    ) -> Task<Result<()>> {
1928        cx.spawn(move |this, mut cx| async move {
1929            let save_tasks = buffers.into_iter().filter_map(|buffer| {
1930                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
1931                    .ok()
1932            });
1933            try_join_all(save_tasks).await?;
1934            Ok(())
1935        })
1936    }
1937
1938    pub fn save_buffer(
1939        &self,
1940        buffer: Model<Buffer>,
1941        cx: &mut ModelContext<Self>,
1942    ) -> Task<Result<()>> {
1943        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1944            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1945        };
1946        let worktree = file.worktree.clone();
1947        let path = file.path.clone();
1948        worktree.update(cx, |worktree, cx| match worktree {
1949            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1950            Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1951        })
1952    }
1953
1954    pub fn save_buffer_as(
1955        &mut self,
1956        buffer: Model<Buffer>,
1957        abs_path: PathBuf,
1958        cx: &mut ModelContext<Self>,
1959    ) -> Task<Result<()>> {
1960        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1961        let old_file = File::from_dyn(buffer.read(cx).file())
1962            .filter(|f| f.is_local())
1963            .cloned();
1964        cx.spawn(move |this, mut cx| async move {
1965            if let Some(old_file) = &old_file {
1966                this.update(&mut cx, |this, cx| {
1967                    this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
1968                })?;
1969            }
1970            let (worktree, path) = worktree_task.await?;
1971            worktree
1972                .update(&mut cx, |worktree, cx| match worktree {
1973                    Worktree::Local(worktree) => {
1974                        worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1975                    }
1976                    Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1977                })?
1978                .await?;
1979
1980            this.update(&mut cx, |this, cx| {
1981                this.detect_language_for_buffer(&buffer, cx);
1982                this.register_buffer_with_language_servers(&buffer, cx);
1983            })?;
1984            Ok(())
1985        })
1986    }
1987
1988    pub fn get_open_buffer(
1989        &mut self,
1990        path: &ProjectPath,
1991        cx: &mut ModelContext<Self>,
1992    ) -> Option<Model<Buffer>> {
1993        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1994        self.opened_buffers.values().find_map(|buffer| {
1995            let buffer = buffer.upgrade()?;
1996            let file = File::from_dyn(buffer.read(cx).file())?;
1997            if file.worktree == worktree && file.path() == &path.path {
1998                Some(buffer)
1999            } else {
2000                None
2001            }
2002        })
2003    }
2004
2005    fn register_buffer(
2006        &mut self,
2007        buffer: &Model<Buffer>,
2008        cx: &mut ModelContext<Self>,
2009    ) -> Result<()> {
2010        self.request_buffer_diff_recalculation(buffer, cx);
2011        buffer.update(cx, |buffer, _| {
2012            buffer.set_language_registry(self.languages.clone())
2013        });
2014
2015        let remote_id = buffer.read(cx).remote_id();
2016        let is_remote = self.is_remote();
2017        let open_buffer = if is_remote || self.is_shared() {
2018            OpenBuffer::Strong(buffer.clone())
2019        } else {
2020            OpenBuffer::Weak(buffer.downgrade())
2021        };
2022
2023        match self.opened_buffers.entry(remote_id) {
2024            hash_map::Entry::Vacant(entry) => {
2025                entry.insert(open_buffer);
2026            }
2027            hash_map::Entry::Occupied(mut entry) => {
2028                if let OpenBuffer::Operations(operations) = entry.get_mut() {
2029                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
2030                } else if entry.get().upgrade().is_some() {
2031                    if is_remote {
2032                        return Ok(());
2033                    } else {
2034                        debug_panic!("buffer {} was already registered", remote_id);
2035                        Err(anyhow!("buffer {} was already registered", remote_id))?;
2036                    }
2037                }
2038                entry.insert(open_buffer);
2039            }
2040        }
2041        cx.subscribe(buffer, |this, buffer, event, cx| {
2042            this.on_buffer_event(buffer, event, cx);
2043        })
2044        .detach();
2045
2046        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2047            if file.is_local {
2048                self.local_buffer_ids_by_path.insert(
2049                    ProjectPath {
2050                        worktree_id: file.worktree_id(cx),
2051                        path: file.path.clone(),
2052                    },
2053                    remote_id,
2054                );
2055
2056                if let Some(entry_id) = file.entry_id {
2057                    self.local_buffer_ids_by_entry_id
2058                        .insert(entry_id, remote_id);
2059                }
2060            }
2061        }
2062
2063        self.detect_language_for_buffer(buffer, cx);
2064        self.register_buffer_with_language_servers(buffer, cx);
2065        self.register_buffer_with_copilot(buffer, cx);
2066        cx.observe_release(buffer, |this, buffer, cx| {
2067            if let Some(file) = File::from_dyn(buffer.file()) {
2068                if file.is_local() {
2069                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2070                    for server in this.language_servers_for_buffer(buffer, cx) {
2071                        server
2072                            .1
2073                            .notify::<lsp::notification::DidCloseTextDocument>(
2074                                lsp::DidCloseTextDocumentParams {
2075                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
2076                                },
2077                            )
2078                            .log_err();
2079                    }
2080                }
2081            }
2082        })
2083        .detach();
2084
2085        *self.opened_buffer.0.borrow_mut() = ();
2086        Ok(())
2087    }
2088
2089    fn register_buffer_with_language_servers(
2090        &mut self,
2091        buffer_handle: &Model<Buffer>,
2092        cx: &mut ModelContext<Self>,
2093    ) {
2094        let buffer = buffer_handle.read(cx);
2095        let buffer_id = buffer.remote_id();
2096
2097        if let Some(file) = File::from_dyn(buffer.file()) {
2098            if !file.is_local() {
2099                return;
2100            }
2101
2102            let abs_path = file.abs_path(cx);
2103            let uri = lsp::Url::from_file_path(&abs_path)
2104                .unwrap_or_else(|()| panic!("Failed to register file {abs_path:?}"));
2105            let initial_snapshot = buffer.text_snapshot();
2106            let language = buffer.language().cloned();
2107            let worktree_id = file.worktree_id(cx);
2108
2109            if let Some(local_worktree) = file.worktree.read(cx).as_local() {
2110                for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
2111                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
2112                        .log_err();
2113                }
2114            }
2115
2116            if let Some(language) = language {
2117                for adapter in language.lsp_adapters() {
2118                    let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
2119                    let server = self
2120                        .language_server_ids
2121                        .get(&(worktree_id, adapter.name.clone()))
2122                        .and_then(|id| self.language_servers.get(id))
2123                        .and_then(|server_state| {
2124                            if let LanguageServerState::Running { server, .. } = server_state {
2125                                Some(server.clone())
2126                            } else {
2127                                None
2128                            }
2129                        });
2130                    let server = match server {
2131                        Some(server) => server,
2132                        None => continue,
2133                    };
2134
2135                    server
2136                        .notify::<lsp::notification::DidOpenTextDocument>(
2137                            lsp::DidOpenTextDocumentParams {
2138                                text_document: lsp::TextDocumentItem::new(
2139                                    uri.clone(),
2140                                    language_id.unwrap_or_default(),
2141                                    0,
2142                                    initial_snapshot.text(),
2143                                ),
2144                            },
2145                        )
2146                        .log_err();
2147
2148                    buffer_handle.update(cx, |buffer, cx| {
2149                        buffer.set_completion_triggers(
2150                            server
2151                                .capabilities()
2152                                .completion_provider
2153                                .as_ref()
2154                                .and_then(|provider| provider.trigger_characters.clone())
2155                                .unwrap_or_default(),
2156                            cx,
2157                        );
2158                    });
2159
2160                    let snapshot = LspBufferSnapshot {
2161                        version: 0,
2162                        snapshot: initial_snapshot.clone(),
2163                    };
2164                    self.buffer_snapshots
2165                        .entry(buffer_id)
2166                        .or_default()
2167                        .insert(server.server_id(), vec![snapshot]);
2168                }
2169            }
2170        }
2171    }
2172
2173    fn unregister_buffer_from_language_servers(
2174        &mut self,
2175        buffer: &Model<Buffer>,
2176        old_file: &File,
2177        cx: &mut ModelContext<Self>,
2178    ) {
2179        let old_path = match old_file.as_local() {
2180            Some(local) => local.abs_path(cx),
2181            None => return,
2182        };
2183
2184        buffer.update(cx, |buffer, cx| {
2185            let worktree_id = old_file.worktree_id(cx);
2186            let ids = &self.language_server_ids;
2187
2188            let language = buffer.language().cloned();
2189            let adapters = language.iter().flat_map(|language| language.lsp_adapters());
2190            for &server_id in adapters.flat_map(|a| ids.get(&(worktree_id, a.name.clone()))) {
2191                buffer.update_diagnostics(server_id, Default::default(), cx);
2192            }
2193
2194            self.buffer_snapshots.remove(&buffer.remote_id());
2195            let file_url = lsp::Url::from_file_path(old_path).unwrap();
2196            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2197                language_server
2198                    .notify::<lsp::notification::DidCloseTextDocument>(
2199                        lsp::DidCloseTextDocumentParams {
2200                            text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
2201                        },
2202                    )
2203                    .log_err();
2204            }
2205        });
2206    }
2207
2208    fn register_buffer_with_copilot(
2209        &self,
2210        buffer_handle: &Model<Buffer>,
2211        cx: &mut ModelContext<Self>,
2212    ) {
2213        if let Some(copilot) = Copilot::global(cx) {
2214            copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
2215        }
2216    }
2217
2218    async fn send_buffer_ordered_messages(
2219        this: WeakModel<Self>,
2220        rx: UnboundedReceiver<BufferOrderedMessage>,
2221        mut cx: AsyncAppContext,
2222    ) -> Result<()> {
2223        const MAX_BATCH_SIZE: usize = 128;
2224
2225        let mut operations_by_buffer_id = HashMap::default();
2226        async fn flush_operations(
2227            this: &WeakModel<Project>,
2228            operations_by_buffer_id: &mut HashMap<u64, Vec<proto::Operation>>,
2229            needs_resync_with_host: &mut bool,
2230            is_local: bool,
2231            cx: &mut AsyncAppContext,
2232        ) -> Result<()> {
2233            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2234                let request = this.update(cx, |this, _| {
2235                    let project_id = this.remote_id()?;
2236                    Some(this.client.request(proto::UpdateBuffer {
2237                        buffer_id,
2238                        project_id,
2239                        operations,
2240                    }))
2241                })?;
2242                if let Some(request) = request {
2243                    if request.await.is_err() && !is_local {
2244                        *needs_resync_with_host = true;
2245                        break;
2246                    }
2247                }
2248            }
2249            Ok(())
2250        }
2251
2252        let mut needs_resync_with_host = false;
2253        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2254
2255        while let Some(changes) = changes.next().await {
2256            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
2257
2258            for change in changes {
2259                match change {
2260                    BufferOrderedMessage::Operation {
2261                        buffer_id,
2262                        operation,
2263                    } => {
2264                        if needs_resync_with_host {
2265                            continue;
2266                        }
2267
2268                        operations_by_buffer_id
2269                            .entry(buffer_id)
2270                            .or_insert(Vec::new())
2271                            .push(operation);
2272                    }
2273
2274                    BufferOrderedMessage::Resync => {
2275                        operations_by_buffer_id.clear();
2276                        if this
2277                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2278                            .await
2279                            .is_ok()
2280                        {
2281                            needs_resync_with_host = false;
2282                        }
2283                    }
2284
2285                    BufferOrderedMessage::LanguageServerUpdate {
2286                        language_server_id,
2287                        message,
2288                    } => {
2289                        flush_operations(
2290                            &this,
2291                            &mut operations_by_buffer_id,
2292                            &mut needs_resync_with_host,
2293                            is_local,
2294                            &mut cx,
2295                        )
2296                        .await?;
2297
2298                        this.update(&mut cx, |this, _| {
2299                            if let Some(project_id) = this.remote_id() {
2300                                this.client
2301                                    .send(proto::UpdateLanguageServer {
2302                                        project_id,
2303                                        language_server_id: language_server_id.0 as u64,
2304                                        variant: Some(message),
2305                                    })
2306                                    .log_err();
2307                            }
2308                        })?;
2309                    }
2310                }
2311            }
2312
2313            flush_operations(
2314                &this,
2315                &mut operations_by_buffer_id,
2316                &mut needs_resync_with_host,
2317                is_local,
2318                &mut cx,
2319            )
2320            .await?;
2321        }
2322
2323        Ok(())
2324    }
2325
2326    fn on_buffer_event(
2327        &mut self,
2328        buffer: Model<Buffer>,
2329        event: &BufferEvent,
2330        cx: &mut ModelContext<Self>,
2331    ) -> Option<()> {
2332        if matches!(
2333            event,
2334            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2335        ) {
2336            self.request_buffer_diff_recalculation(&buffer, cx);
2337        }
2338
2339        match event {
2340            BufferEvent::Operation(operation) => {
2341                self.buffer_ordered_messages_tx
2342                    .unbounded_send(BufferOrderedMessage::Operation {
2343                        buffer_id: buffer.read(cx).remote_id(),
2344                        operation: language::proto::serialize_operation(operation),
2345                    })
2346                    .ok();
2347            }
2348
2349            BufferEvent::Edited { .. } => {
2350                let buffer = buffer.read(cx);
2351                let file = File::from_dyn(buffer.file())?;
2352                let abs_path = file.as_local()?.abs_path(cx);
2353                let uri = lsp::Url::from_file_path(abs_path).unwrap();
2354                let next_snapshot = buffer.text_snapshot();
2355
2356                let language_servers: Vec<_> = self
2357                    .language_servers_for_buffer(buffer, cx)
2358                    .map(|i| i.1.clone())
2359                    .collect();
2360
2361                for language_server in language_servers {
2362                    let language_server = language_server.clone();
2363
2364                    let buffer_snapshots = self
2365                        .buffer_snapshots
2366                        .get_mut(&buffer.remote_id())
2367                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
2368                    let previous_snapshot = buffer_snapshots.last()?;
2369
2370                    let build_incremental_change = || {
2371                        buffer
2372                            .edits_since::<(PointUtf16, usize)>(
2373                                previous_snapshot.snapshot.version(),
2374                            )
2375                            .map(|edit| {
2376                                let edit_start = edit.new.start.0;
2377                                let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
2378                                let new_text = next_snapshot
2379                                    .text_for_range(edit.new.start.1..edit.new.end.1)
2380                                    .collect();
2381                                lsp::TextDocumentContentChangeEvent {
2382                                    range: Some(lsp::Range::new(
2383                                        point_to_lsp(edit_start),
2384                                        point_to_lsp(edit_end),
2385                                    )),
2386                                    range_length: None,
2387                                    text: new_text,
2388                                }
2389                            })
2390                            .collect()
2391                    };
2392
2393                    let document_sync_kind = language_server
2394                        .capabilities()
2395                        .text_document_sync
2396                        .as_ref()
2397                        .and_then(|sync| match sync {
2398                            lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
2399                            lsp::TextDocumentSyncCapability::Options(options) => options.change,
2400                        });
2401
2402                    let content_changes: Vec<_> = match document_sync_kind {
2403                        Some(lsp::TextDocumentSyncKind::FULL) => {
2404                            vec![lsp::TextDocumentContentChangeEvent {
2405                                range: None,
2406                                range_length: None,
2407                                text: next_snapshot.text(),
2408                            }]
2409                        }
2410                        Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
2411                        _ => {
2412                            #[cfg(any(test, feature = "test-support"))]
2413                            {
2414                                build_incremental_change()
2415                            }
2416
2417                            #[cfg(not(any(test, feature = "test-support")))]
2418                            {
2419                                continue;
2420                            }
2421                        }
2422                    };
2423
2424                    let next_version = previous_snapshot.version + 1;
2425
2426                    buffer_snapshots.push(LspBufferSnapshot {
2427                        version: next_version,
2428                        snapshot: next_snapshot.clone(),
2429                    });
2430
2431                    language_server
2432                        .notify::<lsp::notification::DidChangeTextDocument>(
2433                            lsp::DidChangeTextDocumentParams {
2434                                text_document: lsp::VersionedTextDocumentIdentifier::new(
2435                                    uri.clone(),
2436                                    next_version,
2437                                ),
2438                                content_changes,
2439                            },
2440                        )
2441                        .log_err();
2442                }
2443            }
2444
2445            BufferEvent::Saved => {
2446                let file = File::from_dyn(buffer.read(cx).file())?;
2447                let worktree_id = file.worktree_id(cx);
2448                let abs_path = file.as_local()?.abs_path(cx);
2449                let text_document = lsp::TextDocumentIdentifier {
2450                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
2451                };
2452
2453                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
2454                    let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
2455
2456                    server
2457                        .notify::<lsp::notification::DidSaveTextDocument>(
2458                            lsp::DidSaveTextDocumentParams {
2459                                text_document: text_document.clone(),
2460                                text,
2461                            },
2462                        )
2463                        .log_err();
2464                }
2465
2466                let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
2467                for language_server_id in language_server_ids {
2468                    if let Some(LanguageServerState::Running {
2469                        adapter,
2470                        simulate_disk_based_diagnostics_completion,
2471                        ..
2472                    }) = self.language_servers.get_mut(&language_server_id)
2473                    {
2474                        // After saving a buffer using a language server that doesn't provide
2475                        // a disk-based progress token, kick off a timer that will reset every
2476                        // time the buffer is saved. If the timer eventually fires, simulate
2477                        // disk-based diagnostics being finished so that other pieces of UI
2478                        // (e.g., project diagnostics view, diagnostic status bar) can update.
2479                        // We don't emit an event right away because the language server might take
2480                        // some time to publish diagnostics.
2481                        if adapter.disk_based_diagnostics_progress_token.is_none() {
2482                            const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
2483                                Duration::from_secs(1);
2484
2485                            let task = cx.spawn(move |this, mut cx| async move {
2486                                cx.background_executor().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
2487                                if let Some(this) = this.upgrade() {
2488                                    this.update(&mut cx, |this, cx| {
2489                                        this.disk_based_diagnostics_finished(
2490                                            language_server_id,
2491                                            cx,
2492                                        );
2493                                        this.buffer_ordered_messages_tx
2494                                            .unbounded_send(
2495                                                BufferOrderedMessage::LanguageServerUpdate {
2496                                                    language_server_id,
2497                                                    message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
2498                                                },
2499                                            )
2500                                            .ok();
2501                                    }).ok();
2502                                }
2503                            });
2504                            *simulate_disk_based_diagnostics_completion = Some(task);
2505                        }
2506                    }
2507                }
2508            }
2509            BufferEvent::FileHandleChanged => {
2510                let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
2511                    return None;
2512                };
2513
2514                let remote_id = buffer.read(cx).remote_id();
2515                if let Some(entry_id) = file.entry_id {
2516                    match self.local_buffer_ids_by_entry_id.get(&entry_id) {
2517                        Some(_) => {
2518                            return None;
2519                        }
2520                        None => {
2521                            self.local_buffer_ids_by_entry_id
2522                                .insert(entry_id, remote_id);
2523                        }
2524                    }
2525                };
2526                self.local_buffer_ids_by_path.insert(
2527                    ProjectPath {
2528                        worktree_id: file.worktree_id(cx),
2529                        path: file.path.clone(),
2530                    },
2531                    remote_id,
2532                );
2533            }
2534            _ => {}
2535        }
2536
2537        None
2538    }
2539
2540    fn request_buffer_diff_recalculation(
2541        &mut self,
2542        buffer: &Model<Buffer>,
2543        cx: &mut ModelContext<Self>,
2544    ) {
2545        self.buffers_needing_diff.insert(buffer.downgrade());
2546        let first_insertion = self.buffers_needing_diff.len() == 1;
2547
2548        let settings = ProjectSettings::get_global(cx);
2549        let delay = if let Some(delay) = settings.git.gutter_debounce {
2550            delay
2551        } else {
2552            if first_insertion {
2553                let this = cx.weak_model();
2554                cx.defer(move |cx| {
2555                    if let Some(this) = this.upgrade() {
2556                        this.update(cx, |this, cx| {
2557                            this.recalculate_buffer_diffs(cx).detach();
2558                        });
2559                    }
2560                });
2561            }
2562            return;
2563        };
2564
2565        const MIN_DELAY: u64 = 50;
2566        let delay = delay.max(MIN_DELAY);
2567        let duration = Duration::from_millis(delay);
2568
2569        self.git_diff_debouncer
2570            .fire_new(duration, cx, move |this, cx| {
2571                this.recalculate_buffer_diffs(cx)
2572            });
2573    }
2574
2575    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2576        let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2577        cx.spawn(move |this, mut cx| async move {
2578            let tasks: Vec<_> = buffers
2579                .iter()
2580                .filter_map(|buffer| {
2581                    let buffer = buffer.upgrade()?;
2582                    buffer
2583                        .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
2584                        .ok()
2585                        .flatten()
2586                })
2587                .collect();
2588
2589            futures::future::join_all(tasks).await;
2590
2591            this.update(&mut cx, |this, cx| {
2592                if !this.buffers_needing_diff.is_empty() {
2593                    this.recalculate_buffer_diffs(cx).detach();
2594                } else {
2595                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2596                    for buffer in buffers {
2597                        if let Some(buffer) = buffer.upgrade() {
2598                            buffer.update(cx, |_, cx| cx.notify());
2599                        }
2600                    }
2601                }
2602            })
2603            .ok();
2604        })
2605    }
2606
2607    fn language_servers_for_worktree(
2608        &self,
2609        worktree_id: WorktreeId,
2610    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2611        self.language_server_ids
2612            .iter()
2613            .filter_map(move |((language_server_worktree_id, _), id)| {
2614                if *language_server_worktree_id == worktree_id {
2615                    if let Some(LanguageServerState::Running {
2616                        adapter,
2617                        language,
2618                        server,
2619                        ..
2620                    }) = self.language_servers.get(id)
2621                    {
2622                        return Some((adapter, language, server));
2623                    }
2624                }
2625                None
2626            })
2627    }
2628
2629    fn maintain_buffer_languages(
2630        languages: Arc<LanguageRegistry>,
2631        cx: &mut ModelContext<Project>,
2632    ) -> Task<()> {
2633        let mut subscription = languages.subscribe();
2634        let mut prev_reload_count = languages.reload_count();
2635        cx.spawn(move |project, mut cx| async move {
2636            while let Some(()) = subscription.next().await {
2637                if let Some(project) = project.upgrade() {
2638                    // If the language registry has been reloaded, then remove and
2639                    // re-assign the languages on all open buffers.
2640                    let reload_count = languages.reload_count();
2641                    if reload_count > prev_reload_count {
2642                        prev_reload_count = reload_count;
2643                        project
2644                            .update(&mut cx, |this, cx| {
2645                                let buffers = this
2646                                    .opened_buffers
2647                                    .values()
2648                                    .filter_map(|b| b.upgrade())
2649                                    .collect::<Vec<_>>();
2650                                for buffer in buffers {
2651                                    if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
2652                                    {
2653                                        this.unregister_buffer_from_language_servers(
2654                                            &buffer, &f, cx,
2655                                        );
2656                                        buffer
2657                                            .update(cx, |buffer, cx| buffer.set_language(None, cx));
2658                                    }
2659                                }
2660                            })
2661                            .ok();
2662                    }
2663
2664                    project
2665                        .update(&mut cx, |project, cx| {
2666                            let mut plain_text_buffers = Vec::new();
2667                            let mut buffers_with_unknown_injections = Vec::new();
2668                            for buffer in project.opened_buffers.values() {
2669                                if let Some(handle) = buffer.upgrade() {
2670                                    let buffer = &handle.read(cx);
2671                                    if buffer.language().is_none()
2672                                        || buffer.language() == Some(&*language::PLAIN_TEXT)
2673                                    {
2674                                        plain_text_buffers.push(handle);
2675                                    } else if buffer.contains_unknown_injections() {
2676                                        buffers_with_unknown_injections.push(handle);
2677                                    }
2678                                }
2679                            }
2680
2681                            for buffer in plain_text_buffers {
2682                                project.detect_language_for_buffer(&buffer, cx);
2683                                project.register_buffer_with_language_servers(&buffer, cx);
2684                            }
2685
2686                            for buffer in buffers_with_unknown_injections {
2687                                buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2688                            }
2689                        })
2690                        .ok();
2691                }
2692            }
2693        })
2694    }
2695
2696    fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<Result<()>> {
2697        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2698        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2699
2700        let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
2701            *settings_changed_tx.borrow_mut() = ();
2702        });
2703
2704        cx.spawn(move |this, mut cx| async move {
2705            while let Some(_) = settings_changed_rx.next().await {
2706                let servers: Vec<_> = this.update(&mut cx, |this, _| {
2707                    this.language_servers
2708                        .values()
2709                        .filter_map(|state| match state {
2710                            LanguageServerState::Starting(_) => None,
2711                            LanguageServerState::Running {
2712                                adapter, server, ..
2713                            } => Some((adapter.clone(), server.clone())),
2714                        })
2715                        .collect()
2716                })?;
2717
2718                for (adapter, server) in servers {
2719                    let workspace_config = cx
2720                        .update(|cx| adapter.workspace_configuration(server.root_path(), cx))?
2721                        .await;
2722                    server
2723                        .notify::<lsp::notification::DidChangeConfiguration>(
2724                            lsp::DidChangeConfigurationParams {
2725                                settings: workspace_config.clone(),
2726                            },
2727                        )
2728                        .ok();
2729                }
2730            }
2731
2732            drop(settings_observation);
2733            anyhow::Ok(())
2734        })
2735    }
2736
2737    fn detect_language_for_buffer(
2738        &mut self,
2739        buffer_handle: &Model<Buffer>,
2740        cx: &mut ModelContext<Self>,
2741    ) -> Option<()> {
2742        // If the buffer has a language, set it and start the language server if we haven't already.
2743        let buffer = buffer_handle.read(cx);
2744        let full_path = buffer.file()?.full_path(cx);
2745        let content = buffer.as_rope();
2746        let new_language = self
2747            .languages
2748            .language_for_file(&full_path, Some(content))
2749            .now_or_never()?
2750            .ok()?;
2751        self.set_language_for_buffer(buffer_handle, new_language, cx);
2752        None
2753    }
2754
2755    pub fn set_language_for_buffer(
2756        &mut self,
2757        buffer: &Model<Buffer>,
2758        new_language: Arc<Language>,
2759        cx: &mut ModelContext<Self>,
2760    ) {
2761        buffer.update(cx, |buffer, cx| {
2762            if buffer.language().map_or(true, |old_language| {
2763                !Arc::ptr_eq(old_language, &new_language)
2764            }) {
2765                buffer.set_language(Some(new_language.clone()), cx);
2766            }
2767        });
2768
2769        let buffer_file = buffer.read(cx).file().cloned();
2770        let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
2771        let buffer_file = File::from_dyn(buffer_file.as_ref());
2772        let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
2773        if let Some(prettier_plugins) =
2774            prettier_support::prettier_plugins_for_language(&new_language, &settings)
2775        {
2776            self.install_default_prettier(worktree, prettier_plugins, cx);
2777        };
2778        if let Some(file) = buffer_file {
2779            let worktree = file.worktree.clone();
2780            if let Some(tree) = worktree.read(cx).as_local() {
2781                self.start_language_servers(&worktree, tree.abs_path().clone(), new_language, cx);
2782            }
2783        }
2784    }
2785
2786    fn start_language_servers(
2787        &mut self,
2788        worktree: &Model<Worktree>,
2789        worktree_path: Arc<Path>,
2790        language: Arc<Language>,
2791        cx: &mut ModelContext<Self>,
2792    ) {
2793        let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
2794        let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
2795        if !settings.enable_language_server {
2796            return;
2797        }
2798
2799        let worktree_id = worktree.read(cx).id();
2800        for adapter in language.lsp_adapters() {
2801            self.start_language_server(
2802                worktree_id,
2803                worktree_path.clone(),
2804                adapter.clone(),
2805                language.clone(),
2806                cx,
2807            );
2808        }
2809    }
2810
2811    fn start_language_server(
2812        &mut self,
2813        worktree_id: WorktreeId,
2814        worktree_path: Arc<Path>,
2815        adapter: Arc<CachedLspAdapter>,
2816        language: Arc<Language>,
2817        cx: &mut ModelContext<Self>,
2818    ) {
2819        if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2820            return;
2821        }
2822
2823        let key = (worktree_id, adapter.name.clone());
2824        if self.language_server_ids.contains_key(&key) {
2825            return;
2826        }
2827
2828        let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
2829        let pending_server = match self.languages.create_pending_language_server(
2830            stderr_capture.clone(),
2831            language.clone(),
2832            adapter.clone(),
2833            Arc::clone(&worktree_path),
2834            ProjectLspAdapterDelegate::new(self, cx),
2835            cx,
2836        ) {
2837            Some(pending_server) => pending_server,
2838            None => return,
2839        };
2840
2841        let project_settings = ProjectSettings::get_global(cx);
2842        let lsp = project_settings.lsp.get(&adapter.name.0);
2843        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2844
2845        let server_id = pending_server.server_id;
2846        let container_dir = pending_server.container_dir.clone();
2847        let state = LanguageServerState::Starting({
2848            let adapter = adapter.clone();
2849            let server_name = adapter.name.0.clone();
2850            let language = language.clone();
2851            let key = key.clone();
2852
2853            cx.spawn(move |this, mut cx| async move {
2854                let result = Self::setup_and_insert_language_server(
2855                    this.clone(),
2856                    &worktree_path,
2857                    override_options,
2858                    pending_server,
2859                    adapter.clone(),
2860                    language.clone(),
2861                    server_id,
2862                    key,
2863                    &mut cx,
2864                )
2865                .await;
2866
2867                match result {
2868                    Ok(server) => {
2869                        stderr_capture.lock().take();
2870                        server
2871                    }
2872
2873                    Err(err) => {
2874                        log::error!("failed to start language server {server_name:?}: {err}");
2875                        log::error!("server stderr: {:?}", stderr_capture.lock().take());
2876
2877                        let this = this.upgrade()?;
2878                        let container_dir = container_dir?;
2879
2880                        let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
2881                        if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2882                            let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
2883                            log::error!("Hit {max} reinstallation attempts for {server_name:?}");
2884                            return None;
2885                        }
2886
2887                        let installation_test_binary = adapter
2888                            .installation_test_binary(container_dir.to_path_buf())
2889                            .await;
2890
2891                        this.update(&mut cx, |_, cx| {
2892                            Self::check_errored_server(
2893                                language,
2894                                adapter,
2895                                server_id,
2896                                installation_test_binary,
2897                                cx,
2898                            )
2899                        })
2900                        .ok();
2901
2902                        None
2903                    }
2904                }
2905            })
2906        });
2907
2908        self.language_servers.insert(server_id, state);
2909        self.language_server_ids.insert(key, server_id);
2910    }
2911
2912    fn reinstall_language_server(
2913        &mut self,
2914        language: Arc<Language>,
2915        adapter: Arc<CachedLspAdapter>,
2916        server_id: LanguageServerId,
2917        cx: &mut ModelContext<Self>,
2918    ) -> Option<Task<()>> {
2919        log::info!("beginning to reinstall server");
2920
2921        let existing_server = match self.language_servers.remove(&server_id) {
2922            Some(LanguageServerState::Running { server, .. }) => Some(server),
2923            _ => None,
2924        };
2925
2926        for worktree in &self.worktrees {
2927            if let Some(worktree) = worktree.upgrade() {
2928                let key = (worktree.read(cx).id(), adapter.name.clone());
2929                self.language_server_ids.remove(&key);
2930            }
2931        }
2932
2933        Some(cx.spawn(move |this, mut cx| async move {
2934            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2935                log::info!("shutting down existing server");
2936                task.await;
2937            }
2938
2939            // TODO: This is race-safe with regards to preventing new instances from
2940            // starting while deleting, but existing instances in other projects are going
2941            // to be very confused and messed up
2942            let Some(task) = this
2943                .update(&mut cx, |this, cx| {
2944                    this.languages.delete_server_container(adapter.clone(), cx)
2945                })
2946                .log_err()
2947            else {
2948                return;
2949            };
2950            task.await;
2951
2952            this.update(&mut cx, |this, mut cx| {
2953                let worktrees = this.worktrees.clone();
2954                for worktree in worktrees {
2955                    let worktree = match worktree.upgrade() {
2956                        Some(worktree) => worktree.read(cx),
2957                        None => continue,
2958                    };
2959                    let worktree_id = worktree.id();
2960                    let root_path = worktree.abs_path();
2961
2962                    this.start_language_server(
2963                        worktree_id,
2964                        root_path,
2965                        adapter.clone(),
2966                        language.clone(),
2967                        &mut cx,
2968                    );
2969                }
2970            })
2971            .ok();
2972        }))
2973    }
2974
2975    async fn setup_and_insert_language_server(
2976        this: WeakModel<Self>,
2977        worktree_path: &Path,
2978        override_initialization_options: Option<serde_json::Value>,
2979        pending_server: PendingLanguageServer,
2980        adapter: Arc<CachedLspAdapter>,
2981        language: Arc<Language>,
2982        server_id: LanguageServerId,
2983        key: (WorktreeId, LanguageServerName),
2984        cx: &mut AsyncAppContext,
2985    ) -> Result<Option<Arc<LanguageServer>>> {
2986        let language_server = Self::setup_pending_language_server(
2987            this.clone(),
2988            override_initialization_options,
2989            pending_server,
2990            worktree_path,
2991            adapter.clone(),
2992            server_id,
2993            cx,
2994        )
2995        .await?;
2996
2997        let this = match this.upgrade() {
2998            Some(this) => this,
2999            None => return Err(anyhow!("failed to upgrade project handle")),
3000        };
3001
3002        this.update(cx, |this, cx| {
3003            this.insert_newly_running_language_server(
3004                language,
3005                adapter,
3006                language_server.clone(),
3007                server_id,
3008                key,
3009                cx,
3010            )
3011        })??;
3012
3013        Ok(Some(language_server))
3014    }
3015
3016    async fn setup_pending_language_server(
3017        this: WeakModel<Self>,
3018        override_options: Option<serde_json::Value>,
3019        pending_server: PendingLanguageServer,
3020        worktree_path: &Path,
3021        adapter: Arc<CachedLspAdapter>,
3022        server_id: LanguageServerId,
3023        cx: &mut AsyncAppContext,
3024    ) -> Result<Arc<LanguageServer>> {
3025        let workspace_config = cx
3026            .update(|cx| adapter.workspace_configuration(worktree_path, cx))?
3027            .await;
3028        let language_server = pending_server.task.await?;
3029
3030        language_server
3031            .on_notification::<lsp::notification::PublishDiagnostics, _>({
3032                let adapter = adapter.clone();
3033                let this = this.clone();
3034                move |mut params, mut cx| {
3035                    let adapter = adapter.clone();
3036                    if let Some(this) = this.upgrade() {
3037                        adapter.process_diagnostics(&mut params);
3038                        this.update(&mut cx, |this, cx| {
3039                            this.update_diagnostics(
3040                                server_id,
3041                                params,
3042                                &adapter.disk_based_diagnostic_sources,
3043                                cx,
3044                            )
3045                            .log_err();
3046                        })
3047                        .ok();
3048                    }
3049                }
3050            })
3051            .detach();
3052
3053        language_server
3054            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
3055                let adapter = adapter.clone();
3056                let worktree_path = worktree_path.to_path_buf();
3057                move |params, cx| {
3058                    let adapter = adapter.clone();
3059                    let worktree_path = worktree_path.clone();
3060                    async move {
3061                        let workspace_config = cx
3062                            .update(|cx| adapter.workspace_configuration(&worktree_path, cx))?
3063                            .await;
3064                        Ok(params
3065                            .items
3066                            .into_iter()
3067                            .map(|item| {
3068                                if let Some(section) = &item.section {
3069                                    workspace_config
3070                                        .get(section)
3071                                        .cloned()
3072                                        .unwrap_or(serde_json::Value::Null)
3073                                } else {
3074                                    workspace_config.clone()
3075                                }
3076                            })
3077                            .collect())
3078                    }
3079                }
3080            })
3081            .detach();
3082
3083        // Even though we don't have handling for these requests, respond to them to
3084        // avoid stalling any language server like `gopls` which waits for a response
3085        // to these requests when initializing.
3086        language_server
3087            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
3088                let this = this.clone();
3089                move |params, mut cx| {
3090                    let this = this.clone();
3091                    async move {
3092                        this.update(&mut cx, |this, _| {
3093                            if let Some(status) = this.language_server_statuses.get_mut(&server_id)
3094                            {
3095                                if let lsp::NumberOrString::String(token) = params.token {
3096                                    status.progress_tokens.insert(token);
3097                                }
3098                            }
3099                        })?;
3100
3101                        Ok(())
3102                    }
3103                }
3104            })
3105            .detach();
3106
3107        language_server
3108            .on_request::<lsp::request::RegisterCapability, _, _>({
3109                let this = this.clone();
3110                move |params, mut cx| {
3111                    let this = this.clone();
3112                    async move {
3113                        for reg in params.registrations {
3114                            if reg.method == "workspace/didChangeWatchedFiles" {
3115                                if let Some(options) = reg.register_options {
3116                                    let options = serde_json::from_value(options)?;
3117                                    this.update(&mut cx, |this, cx| {
3118                                        this.on_lsp_did_change_watched_files(
3119                                            server_id, options, cx,
3120                                        );
3121                                    })?;
3122                                }
3123                            }
3124                        }
3125                        Ok(())
3126                    }
3127                }
3128            })
3129            .detach();
3130
3131        language_server
3132            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
3133                let adapter = adapter.clone();
3134                let this = this.clone();
3135                move |params, cx| {
3136                    Self::on_lsp_workspace_edit(
3137                        this.clone(),
3138                        params,
3139                        server_id,
3140                        adapter.clone(),
3141                        cx,
3142                    )
3143                }
3144            })
3145            .detach();
3146
3147        language_server
3148            .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
3149                let this = this.clone();
3150                move |(), mut cx| {
3151                    let this = this.clone();
3152                    async move {
3153                        this.update(&mut cx, |project, cx| {
3154                            cx.emit(Event::RefreshInlayHints);
3155                            project.remote_id().map(|project_id| {
3156                                project.client.send(proto::RefreshInlayHints { project_id })
3157                            })
3158                        })?
3159                        .transpose()?;
3160                        Ok(())
3161                    }
3162                }
3163            })
3164            .detach();
3165
3166        let disk_based_diagnostics_progress_token =
3167            adapter.disk_based_diagnostics_progress_token.clone();
3168
3169        language_server
3170            .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
3171                if let Some(this) = this.upgrade() {
3172                    this.update(&mut cx, |this, cx| {
3173                        this.on_lsp_progress(
3174                            params,
3175                            server_id,
3176                            disk_based_diagnostics_progress_token.clone(),
3177                            cx,
3178                        );
3179                    })
3180                    .ok();
3181                }
3182            })
3183            .detach();
3184        let mut initialization_options = adapter.adapter.initialization_options().await;
3185        match (&mut initialization_options, override_options) {
3186            (Some(initialization_options), Some(override_options)) => {
3187                merge_json_value_into(override_options, initialization_options);
3188            }
3189            (None, override_options) => initialization_options = override_options,
3190            _ => {}
3191        }
3192        let language_server = language_server.initialize(initialization_options).await?;
3193
3194        language_server
3195            .notify::<lsp::notification::DidChangeConfiguration>(
3196                lsp::DidChangeConfigurationParams {
3197                    settings: workspace_config,
3198                },
3199            )
3200            .ok();
3201
3202        Ok(language_server)
3203    }
3204
3205    fn insert_newly_running_language_server(
3206        &mut self,
3207        language: Arc<Language>,
3208        adapter: Arc<CachedLspAdapter>,
3209        language_server: Arc<LanguageServer>,
3210        server_id: LanguageServerId,
3211        key: (WorktreeId, LanguageServerName),
3212        cx: &mut ModelContext<Self>,
3213    ) -> Result<()> {
3214        // If the language server for this key doesn't match the server id, don't store the
3215        // server. Which will cause it to be dropped, killing the process
3216        if self
3217            .language_server_ids
3218            .get(&key)
3219            .map(|id| id != &server_id)
3220            .unwrap_or(false)
3221        {
3222            return Ok(());
3223        }
3224
3225        // Update language_servers collection with Running variant of LanguageServerState
3226        // indicating that the server is up and running and ready
3227        self.language_servers.insert(
3228            server_id,
3229            LanguageServerState::Running {
3230                adapter: adapter.clone(),
3231                language: language.clone(),
3232                watched_paths: Default::default(),
3233                server: language_server.clone(),
3234                simulate_disk_based_diagnostics_completion: None,
3235            },
3236        );
3237
3238        self.language_server_statuses.insert(
3239            server_id,
3240            LanguageServerStatus {
3241                name: language_server.name().to_string(),
3242                pending_work: Default::default(),
3243                has_pending_diagnostic_updates: false,
3244                progress_tokens: Default::default(),
3245            },
3246        );
3247
3248        cx.emit(Event::LanguageServerAdded(server_id));
3249
3250        if let Some(project_id) = self.remote_id() {
3251            self.client.send(proto::StartLanguageServer {
3252                project_id,
3253                server: Some(proto::LanguageServer {
3254                    id: server_id.0 as u64,
3255                    name: language_server.name().to_string(),
3256                }),
3257            })?;
3258        }
3259
3260        // Tell the language server about every open buffer in the worktree that matches the language.
3261        for buffer in self.opened_buffers.values() {
3262            if let Some(buffer_handle) = buffer.upgrade() {
3263                let buffer = buffer_handle.read(cx);
3264                let file = match File::from_dyn(buffer.file()) {
3265                    Some(file) => file,
3266                    None => continue,
3267                };
3268                let language = match buffer.language() {
3269                    Some(language) => language,
3270                    None => continue,
3271                };
3272
3273                if file.worktree.read(cx).id() != key.0
3274                    || !language.lsp_adapters().iter().any(|a| a.name == key.1)
3275                {
3276                    continue;
3277                }
3278
3279                let file = match file.as_local() {
3280                    Some(file) => file,
3281                    None => continue,
3282                };
3283
3284                let versions = self
3285                    .buffer_snapshots
3286                    .entry(buffer.remote_id())
3287                    .or_default()
3288                    .entry(server_id)
3289                    .or_insert_with(|| {
3290                        vec![LspBufferSnapshot {
3291                            version: 0,
3292                            snapshot: buffer.text_snapshot(),
3293                        }]
3294                    });
3295
3296                let snapshot = versions.last().unwrap();
3297                let version = snapshot.version;
3298                let initial_snapshot = &snapshot.snapshot;
3299                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3300                language_server.notify::<lsp::notification::DidOpenTextDocument>(
3301                    lsp::DidOpenTextDocumentParams {
3302                        text_document: lsp::TextDocumentItem::new(
3303                            uri,
3304                            adapter
3305                                .language_ids
3306                                .get(language.name().as_ref())
3307                                .cloned()
3308                                .unwrap_or_default(),
3309                            version,
3310                            initial_snapshot.text(),
3311                        ),
3312                    },
3313                )?;
3314
3315                buffer_handle.update(cx, |buffer, cx| {
3316                    buffer.set_completion_triggers(
3317                        language_server
3318                            .capabilities()
3319                            .completion_provider
3320                            .as_ref()
3321                            .and_then(|provider| provider.trigger_characters.clone())
3322                            .unwrap_or_default(),
3323                        cx,
3324                    )
3325                });
3326            }
3327        }
3328
3329        cx.notify();
3330        Ok(())
3331    }
3332
3333    // Returns a list of all of the worktrees which no longer have a language server and the root path
3334    // for the stopped server
3335    fn stop_language_server(
3336        &mut self,
3337        worktree_id: WorktreeId,
3338        adapter_name: LanguageServerName,
3339        cx: &mut ModelContext<Self>,
3340    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
3341        let key = (worktree_id, adapter_name);
3342        if let Some(server_id) = self.language_server_ids.remove(&key) {
3343            log::info!("stopping language server {}", key.1 .0);
3344
3345            // Remove other entries for this language server as well
3346            let mut orphaned_worktrees = vec![worktree_id];
3347            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3348            for other_key in other_keys {
3349                if self.language_server_ids.get(&other_key) == Some(&server_id) {
3350                    self.language_server_ids.remove(&other_key);
3351                    orphaned_worktrees.push(other_key.0);
3352                }
3353            }
3354
3355            for buffer in self.opened_buffers.values() {
3356                if let Some(buffer) = buffer.upgrade() {
3357                    buffer.update(cx, |buffer, cx| {
3358                        buffer.update_diagnostics(server_id, Default::default(), cx);
3359                    });
3360                }
3361            }
3362            for worktree in &self.worktrees {
3363                if let Some(worktree) = worktree.upgrade() {
3364                    worktree.update(cx, |worktree, cx| {
3365                        if let Some(worktree) = worktree.as_local_mut() {
3366                            worktree.clear_diagnostics_for_language_server(server_id, cx);
3367                        }
3368                    });
3369                }
3370            }
3371
3372            self.language_server_statuses.remove(&server_id);
3373            cx.notify();
3374
3375            let server_state = self.language_servers.remove(&server_id);
3376            cx.emit(Event::LanguageServerRemoved(server_id));
3377            cx.spawn(move |this, mut cx| async move {
3378                let mut root_path = None;
3379
3380                let server = match server_state {
3381                    Some(LanguageServerState::Starting(task)) => task.await,
3382                    Some(LanguageServerState::Running { server, .. }) => Some(server),
3383                    None => None,
3384                };
3385
3386                if let Some(server) = server {
3387                    root_path = Some(server.root_path().clone());
3388                    if let Some(shutdown) = server.shutdown() {
3389                        shutdown.await;
3390                    }
3391                }
3392
3393                if let Some(this) = this.upgrade() {
3394                    this.update(&mut cx, |this, cx| {
3395                        this.language_server_statuses.remove(&server_id);
3396                        cx.notify();
3397                    })
3398                    .ok();
3399                }
3400
3401                (root_path, orphaned_worktrees)
3402            })
3403        } else {
3404            Task::ready((None, Vec::new()))
3405        }
3406    }
3407
3408    pub fn restart_language_servers_for_buffers(
3409        &mut self,
3410        buffers: impl IntoIterator<Item = Model<Buffer>>,
3411        cx: &mut ModelContext<Self>,
3412    ) -> Option<()> {
3413        let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
3414            .into_iter()
3415            .filter_map(|buffer| {
3416                let buffer = buffer.read(cx);
3417                let file = File::from_dyn(buffer.file())?;
3418                let full_path = file.full_path(cx);
3419                let language = self
3420                    .languages
3421                    .language_for_file(&full_path, Some(buffer.as_rope()))
3422                    .now_or_never()?
3423                    .ok()?;
3424                Some((file.worktree.clone(), language))
3425            })
3426            .collect();
3427        for (worktree, language) in language_server_lookup_info {
3428            self.restart_language_servers(worktree, language, cx);
3429        }
3430
3431        None
3432    }
3433
3434    // TODO This will break in the case where the adapter's root paths and worktrees are not equal
3435    fn restart_language_servers(
3436        &mut self,
3437        worktree: Model<Worktree>,
3438        language: Arc<Language>,
3439        cx: &mut ModelContext<Self>,
3440    ) {
3441        let worktree_id = worktree.read(cx).id();
3442        let fallback_path = worktree.read(cx).abs_path();
3443
3444        let mut stops = Vec::new();
3445        for adapter in language.lsp_adapters() {
3446            stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
3447        }
3448
3449        if stops.is_empty() {
3450            return;
3451        }
3452        let mut stops = stops.into_iter();
3453
3454        cx.spawn(move |this, mut cx| async move {
3455            let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
3456            for stop in stops {
3457                let (_, worktrees) = stop.await;
3458                orphaned_worktrees.extend_from_slice(&worktrees);
3459            }
3460
3461            let this = match this.upgrade() {
3462                Some(this) => this,
3463                None => return,
3464            };
3465
3466            this.update(&mut cx, |this, cx| {
3467                // Attempt to restart using original server path. Fallback to passed in
3468                // path if we could not retrieve the root path
3469                let root_path = original_root_path
3470                    .map(|path_buf| Arc::from(path_buf.as_path()))
3471                    .unwrap_or(fallback_path);
3472
3473                this.start_language_servers(&worktree, root_path, language.clone(), cx);
3474
3475                // Lookup new server ids and set them for each of the orphaned worktrees
3476                for adapter in language.lsp_adapters() {
3477                    if let Some(new_server_id) = this
3478                        .language_server_ids
3479                        .get(&(worktree_id, adapter.name.clone()))
3480                        .cloned()
3481                    {
3482                        for &orphaned_worktree in &orphaned_worktrees {
3483                            this.language_server_ids
3484                                .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
3485                        }
3486                    }
3487                }
3488            })
3489            .ok();
3490        })
3491        .detach();
3492    }
3493
3494    fn check_errored_server(
3495        language: Arc<Language>,
3496        adapter: Arc<CachedLspAdapter>,
3497        server_id: LanguageServerId,
3498        installation_test_binary: Option<LanguageServerBinary>,
3499        cx: &mut ModelContext<Self>,
3500    ) {
3501        if !adapter.can_be_reinstalled() {
3502            log::info!(
3503                "Validation check requested for {:?} but it cannot be reinstalled",
3504                adapter.name.0
3505            );
3506            return;
3507        }
3508
3509        cx.spawn(move |this, mut cx| async move {
3510            log::info!("About to spawn test binary");
3511
3512            // A lack of test binary counts as a failure
3513            let process = installation_test_binary.and_then(|binary| {
3514                smol::process::Command::new(&binary.path)
3515                    .current_dir(&binary.path)
3516                    .args(binary.arguments)
3517                    .stdin(Stdio::piped())
3518                    .stdout(Stdio::piped())
3519                    .stderr(Stdio::inherit())
3520                    .kill_on_drop(true)
3521                    .spawn()
3522                    .ok()
3523            });
3524
3525            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3526            let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
3527
3528            let mut errored = false;
3529            if let Some(mut process) = process {
3530                futures::select! {
3531                    status = process.status().fuse() => match status {
3532                        Ok(status) => errored = !status.success(),
3533                        Err(_) => errored = true,
3534                    },
3535
3536                    _ = timeout => {
3537                        log::info!("test binary time-ed out, this counts as a success");
3538                        _ = process.kill();
3539                    }
3540                }
3541            } else {
3542                log::warn!("test binary failed to launch");
3543                errored = true;
3544            }
3545
3546            if errored {
3547                log::warn!("test binary check failed");
3548                let task = this
3549                    .update(&mut cx, move |this, mut cx| {
3550                        this.reinstall_language_server(language, adapter, server_id, &mut cx)
3551                    })
3552                    .ok()
3553                    .flatten();
3554
3555                if let Some(task) = task {
3556                    task.await;
3557                }
3558            }
3559        })
3560        .detach();
3561    }
3562
3563    fn on_lsp_progress(
3564        &mut self,
3565        progress: lsp::ProgressParams,
3566        language_server_id: LanguageServerId,
3567        disk_based_diagnostics_progress_token: Option<String>,
3568        cx: &mut ModelContext<Self>,
3569    ) {
3570        let token = match progress.token {
3571            lsp::NumberOrString::String(token) => token,
3572            lsp::NumberOrString::Number(token) => {
3573                log::info!("skipping numeric progress token {}", token);
3574                return;
3575            }
3576        };
3577        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3578        let language_server_status =
3579            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3580                status
3581            } else {
3582                return;
3583            };
3584
3585        if !language_server_status.progress_tokens.contains(&token) {
3586            return;
3587        }
3588
3589        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3590            .as_ref()
3591            .map_or(false, |disk_based_token| {
3592                token.starts_with(disk_based_token)
3593            });
3594
3595        match progress {
3596            lsp::WorkDoneProgress::Begin(report) => {
3597                if is_disk_based_diagnostics_progress {
3598                    language_server_status.has_pending_diagnostic_updates = true;
3599                    self.disk_based_diagnostics_started(language_server_id, cx);
3600                    self.buffer_ordered_messages_tx
3601                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3602                            language_server_id,
3603                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3604                        })
3605                        .ok();
3606                } else {
3607                    self.on_lsp_work_start(
3608                        language_server_id,
3609                        token.clone(),
3610                        LanguageServerProgress {
3611                            message: report.message.clone(),
3612                            percentage: report.percentage.map(|p| p as usize),
3613                            last_update_at: Instant::now(),
3614                        },
3615                        cx,
3616                    );
3617                    self.buffer_ordered_messages_tx
3618                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3619                            language_server_id,
3620                            message: proto::update_language_server::Variant::WorkStart(
3621                                proto::LspWorkStart {
3622                                    token,
3623                                    message: report.message,
3624                                    percentage: report.percentage.map(|p| p as u32),
3625                                },
3626                            ),
3627                        })
3628                        .ok();
3629                }
3630            }
3631            lsp::WorkDoneProgress::Report(report) => {
3632                if !is_disk_based_diagnostics_progress {
3633                    self.on_lsp_work_progress(
3634                        language_server_id,
3635                        token.clone(),
3636                        LanguageServerProgress {
3637                            message: report.message.clone(),
3638                            percentage: report.percentage.map(|p| p as usize),
3639                            last_update_at: Instant::now(),
3640                        },
3641                        cx,
3642                    );
3643                    self.buffer_ordered_messages_tx
3644                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3645                            language_server_id,
3646                            message: proto::update_language_server::Variant::WorkProgress(
3647                                proto::LspWorkProgress {
3648                                    token,
3649                                    message: report.message,
3650                                    percentage: report.percentage.map(|p| p as u32),
3651                                },
3652                            ),
3653                        })
3654                        .ok();
3655                }
3656            }
3657            lsp::WorkDoneProgress::End(_) => {
3658                language_server_status.progress_tokens.remove(&token);
3659
3660                if is_disk_based_diagnostics_progress {
3661                    language_server_status.has_pending_diagnostic_updates = false;
3662                    self.disk_based_diagnostics_finished(language_server_id, cx);
3663                    self.buffer_ordered_messages_tx
3664                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3665                            language_server_id,
3666                            message:
3667                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3668                                    Default::default(),
3669                                ),
3670                        })
3671                        .ok();
3672                } else {
3673                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
3674                    self.buffer_ordered_messages_tx
3675                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3676                            language_server_id,
3677                            message: proto::update_language_server::Variant::WorkEnd(
3678                                proto::LspWorkEnd { token },
3679                            ),
3680                        })
3681                        .ok();
3682                }
3683            }
3684        }
3685    }
3686
3687    fn on_lsp_work_start(
3688        &mut self,
3689        language_server_id: LanguageServerId,
3690        token: String,
3691        progress: LanguageServerProgress,
3692        cx: &mut ModelContext<Self>,
3693    ) {
3694        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3695            status.pending_work.insert(token, progress);
3696            cx.notify();
3697        }
3698    }
3699
3700    fn on_lsp_work_progress(
3701        &mut self,
3702        language_server_id: LanguageServerId,
3703        token: String,
3704        progress: LanguageServerProgress,
3705        cx: &mut ModelContext<Self>,
3706    ) {
3707        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3708            let entry = status
3709                .pending_work
3710                .entry(token)
3711                .or_insert(LanguageServerProgress {
3712                    message: Default::default(),
3713                    percentage: Default::default(),
3714                    last_update_at: progress.last_update_at,
3715                });
3716            if progress.message.is_some() {
3717                entry.message = progress.message;
3718            }
3719            if progress.percentage.is_some() {
3720                entry.percentage = progress.percentage;
3721            }
3722            entry.last_update_at = progress.last_update_at;
3723            cx.notify();
3724        }
3725    }
3726
3727    fn on_lsp_work_end(
3728        &mut self,
3729        language_server_id: LanguageServerId,
3730        token: String,
3731        cx: &mut ModelContext<Self>,
3732    ) {
3733        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3734            cx.emit(Event::RefreshInlayHints);
3735            status.pending_work.remove(&token);
3736            cx.notify();
3737        }
3738    }
3739
3740    fn on_lsp_did_change_watched_files(
3741        &mut self,
3742        language_server_id: LanguageServerId,
3743        params: DidChangeWatchedFilesRegistrationOptions,
3744        cx: &mut ModelContext<Self>,
3745    ) {
3746        if let Some(LanguageServerState::Running { watched_paths, .. }) =
3747            self.language_servers.get_mut(&language_server_id)
3748        {
3749            let mut builders = HashMap::default();
3750            for watcher in params.watchers {
3751                for worktree in &self.worktrees {
3752                    if let Some(worktree) = worktree.upgrade() {
3753                        let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3754                            if let Some(abs_path) = tree.abs_path().to_str() {
3755                                let relative_glob_pattern = match &watcher.glob_pattern {
3756                                    lsp::GlobPattern::String(s) => s
3757                                        .strip_prefix(abs_path)
3758                                        .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3759                                    lsp::GlobPattern::Relative(rp) => {
3760                                        let base_uri = match &rp.base_uri {
3761                                            lsp::OneOf::Left(workspace_folder) => {
3762                                                &workspace_folder.uri
3763                                            }
3764                                            lsp::OneOf::Right(base_uri) => base_uri,
3765                                        };
3766                                        base_uri.to_file_path().ok().and_then(|file_path| {
3767                                            (file_path.to_str() == Some(abs_path))
3768                                                .then_some(rp.pattern.as_str())
3769                                        })
3770                                    }
3771                                };
3772                                if let Some(relative_glob_pattern) = relative_glob_pattern {
3773                                    let literal_prefix =
3774                                        glob_literal_prefix(&relative_glob_pattern);
3775                                    tree.as_local_mut()
3776                                        .unwrap()
3777                                        .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3778                                    if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3779                                        builders
3780                                            .entry(tree.id())
3781                                            .or_insert_with(|| GlobSetBuilder::new())
3782                                            .add(glob);
3783                                    }
3784                                    return true;
3785                                }
3786                            }
3787                            false
3788                        });
3789                        if glob_is_inside_worktree {
3790                            break;
3791                        }
3792                    }
3793                }
3794            }
3795
3796            watched_paths.clear();
3797            for (worktree_id, builder) in builders {
3798                if let Ok(globset) = builder.build() {
3799                    watched_paths.insert(worktree_id, globset);
3800                }
3801            }
3802
3803            cx.notify();
3804        }
3805    }
3806
3807    async fn on_lsp_workspace_edit(
3808        this: WeakModel<Self>,
3809        params: lsp::ApplyWorkspaceEditParams,
3810        server_id: LanguageServerId,
3811        adapter: Arc<CachedLspAdapter>,
3812        mut cx: AsyncAppContext,
3813    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3814        let this = this
3815            .upgrade()
3816            .ok_or_else(|| anyhow!("project project closed"))?;
3817        let language_server = this
3818            .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
3819            .ok_or_else(|| anyhow!("language server not found"))?;
3820        let transaction = Self::deserialize_workspace_edit(
3821            this.clone(),
3822            params.edit,
3823            true,
3824            adapter.clone(),
3825            language_server.clone(),
3826            &mut cx,
3827        )
3828        .await
3829        .log_err();
3830        this.update(&mut cx, |this, _| {
3831            if let Some(transaction) = transaction {
3832                this.last_workspace_edits_by_language_server
3833                    .insert(server_id, transaction);
3834            }
3835        })?;
3836        Ok(lsp::ApplyWorkspaceEditResponse {
3837            applied: true,
3838            failed_change: None,
3839            failure_reason: None,
3840        })
3841    }
3842
3843    pub fn language_server_statuses(
3844        &self,
3845    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3846        self.language_server_statuses.values()
3847    }
3848
3849    pub fn update_diagnostics(
3850        &mut self,
3851        language_server_id: LanguageServerId,
3852        mut params: lsp::PublishDiagnosticsParams,
3853        disk_based_sources: &[String],
3854        cx: &mut ModelContext<Self>,
3855    ) -> Result<()> {
3856        let abs_path = params
3857            .uri
3858            .to_file_path()
3859            .map_err(|_| anyhow!("URI is not a file"))?;
3860        let mut diagnostics = Vec::default();
3861        let mut primary_diagnostic_group_ids = HashMap::default();
3862        let mut sources_by_group_id = HashMap::default();
3863        let mut supporting_diagnostics = HashMap::default();
3864
3865        // Ensure that primary diagnostics are always the most severe
3866        params.diagnostics.sort_by_key(|item| item.severity);
3867
3868        for diagnostic in &params.diagnostics {
3869            let source = diagnostic.source.as_ref();
3870            let code = diagnostic.code.as_ref().map(|code| match code {
3871                lsp::NumberOrString::Number(code) => code.to_string(),
3872                lsp::NumberOrString::String(code) => code.clone(),
3873            });
3874            let range = range_from_lsp(diagnostic.range);
3875            let is_supporting = diagnostic
3876                .related_information
3877                .as_ref()
3878                .map_or(false, |infos| {
3879                    infos.iter().any(|info| {
3880                        primary_diagnostic_group_ids.contains_key(&(
3881                            source,
3882                            code.clone(),
3883                            range_from_lsp(info.location.range),
3884                        ))
3885                    })
3886                });
3887
3888            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3889                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3890            });
3891
3892            if is_supporting {
3893                supporting_diagnostics.insert(
3894                    (source, code.clone(), range),
3895                    (diagnostic.severity, is_unnecessary),
3896                );
3897            } else {
3898                let group_id = post_inc(&mut self.next_diagnostic_group_id);
3899                let is_disk_based =
3900                    source.map_or(false, |source| disk_based_sources.contains(source));
3901
3902                sources_by_group_id.insert(group_id, source);
3903                primary_diagnostic_group_ids
3904                    .insert((source, code.clone(), range.clone()), group_id);
3905
3906                diagnostics.push(DiagnosticEntry {
3907                    range,
3908                    diagnostic: Diagnostic {
3909                        source: diagnostic.source.clone(),
3910                        code: code.clone(),
3911                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3912                        message: diagnostic.message.clone(),
3913                        group_id,
3914                        is_primary: true,
3915                        is_valid: true,
3916                        is_disk_based,
3917                        is_unnecessary,
3918                    },
3919                });
3920                if let Some(infos) = &diagnostic.related_information {
3921                    for info in infos {
3922                        if info.location.uri == params.uri && !info.message.is_empty() {
3923                            let range = range_from_lsp(info.location.range);
3924                            diagnostics.push(DiagnosticEntry {
3925                                range,
3926                                diagnostic: Diagnostic {
3927                                    source: diagnostic.source.clone(),
3928                                    code: code.clone(),
3929                                    severity: DiagnosticSeverity::INFORMATION,
3930                                    message: info.message.clone(),
3931                                    group_id,
3932                                    is_primary: false,
3933                                    is_valid: true,
3934                                    is_disk_based,
3935                                    is_unnecessary: false,
3936                                },
3937                            });
3938                        }
3939                    }
3940                }
3941            }
3942        }
3943
3944        for entry in &mut diagnostics {
3945            let diagnostic = &mut entry.diagnostic;
3946            if !diagnostic.is_primary {
3947                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3948                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3949                    source,
3950                    diagnostic.code.clone(),
3951                    entry.range.clone(),
3952                )) {
3953                    if let Some(severity) = severity {
3954                        diagnostic.severity = severity;
3955                    }
3956                    diagnostic.is_unnecessary = is_unnecessary;
3957                }
3958            }
3959        }
3960
3961        self.update_diagnostic_entries(
3962            language_server_id,
3963            abs_path,
3964            params.version,
3965            diagnostics,
3966            cx,
3967        )?;
3968        Ok(())
3969    }
3970
3971    pub fn update_diagnostic_entries(
3972        &mut self,
3973        server_id: LanguageServerId,
3974        abs_path: PathBuf,
3975        version: Option<i32>,
3976        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3977        cx: &mut ModelContext<Project>,
3978    ) -> Result<(), anyhow::Error> {
3979        let (worktree, relative_path) = self
3980            .find_local_worktree(&abs_path, cx)
3981            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3982
3983        let project_path = ProjectPath {
3984            worktree_id: worktree.read(cx).id(),
3985            path: relative_path.into(),
3986        };
3987
3988        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3989            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3990        }
3991
3992        let updated = worktree.update(cx, |worktree, cx| {
3993            worktree
3994                .as_local_mut()
3995                .ok_or_else(|| anyhow!("not a local worktree"))?
3996                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3997        })?;
3998        if updated {
3999            cx.emit(Event::DiagnosticsUpdated {
4000                language_server_id: server_id,
4001                path: project_path,
4002            });
4003        }
4004        Ok(())
4005    }
4006
4007    fn update_buffer_diagnostics(
4008        &mut self,
4009        buffer: &Model<Buffer>,
4010        server_id: LanguageServerId,
4011        version: Option<i32>,
4012        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4013        cx: &mut ModelContext<Self>,
4014    ) -> Result<()> {
4015        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
4016            Ordering::Equal
4017                .then_with(|| b.is_primary.cmp(&a.is_primary))
4018                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
4019                .then_with(|| a.severity.cmp(&b.severity))
4020                .then_with(|| a.message.cmp(&b.message))
4021        }
4022
4023        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
4024
4025        diagnostics.sort_unstable_by(|a, b| {
4026            Ordering::Equal
4027                .then_with(|| a.range.start.cmp(&b.range.start))
4028                .then_with(|| b.range.end.cmp(&a.range.end))
4029                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
4030        });
4031
4032        let mut sanitized_diagnostics = Vec::new();
4033        let edits_since_save = Patch::new(
4034            snapshot
4035                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
4036                .collect(),
4037        );
4038        for entry in diagnostics {
4039            let start;
4040            let end;
4041            if entry.diagnostic.is_disk_based {
4042                // Some diagnostics are based on files on disk instead of buffers'
4043                // current contents. Adjust these diagnostics' ranges to reflect
4044                // any unsaved edits.
4045                start = edits_since_save.old_to_new(entry.range.start);
4046                end = edits_since_save.old_to_new(entry.range.end);
4047            } else {
4048                start = entry.range.start;
4049                end = entry.range.end;
4050            }
4051
4052            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
4053                ..snapshot.clip_point_utf16(end, Bias::Right);
4054
4055            // Expand empty ranges by one codepoint
4056            if range.start == range.end {
4057                // This will be go to the next boundary when being clipped
4058                range.end.column += 1;
4059                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
4060                if range.start == range.end && range.end.column > 0 {
4061                    range.start.column -= 1;
4062                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
4063                }
4064            }
4065
4066            sanitized_diagnostics.push(DiagnosticEntry {
4067                range,
4068                diagnostic: entry.diagnostic,
4069            });
4070        }
4071        drop(edits_since_save);
4072
4073        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
4074        buffer.update(cx, |buffer, cx| {
4075            buffer.update_diagnostics(server_id, set, cx)
4076        });
4077        Ok(())
4078    }
4079
4080    pub fn reload_buffers(
4081        &self,
4082        buffers: HashSet<Model<Buffer>>,
4083        push_to_history: bool,
4084        cx: &mut ModelContext<Self>,
4085    ) -> Task<Result<ProjectTransaction>> {
4086        let mut local_buffers = Vec::new();
4087        let mut remote_buffers = None;
4088        for buffer_handle in buffers {
4089            let buffer = buffer_handle.read(cx);
4090            if buffer.is_dirty() {
4091                if let Some(file) = File::from_dyn(buffer.file()) {
4092                    if file.is_local() {
4093                        local_buffers.push(buffer_handle);
4094                    } else {
4095                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
4096                    }
4097                }
4098            }
4099        }
4100
4101        let remote_buffers = self.remote_id().zip(remote_buffers);
4102        let client = self.client.clone();
4103
4104        cx.spawn(move |this, mut cx| async move {
4105            let mut project_transaction = ProjectTransaction::default();
4106
4107            if let Some((project_id, remote_buffers)) = remote_buffers {
4108                let response = client
4109                    .request(proto::ReloadBuffers {
4110                        project_id,
4111                        buffer_ids: remote_buffers
4112                            .iter()
4113                            .filter_map(|buffer| {
4114                                buffer.update(&mut cx, |buffer, _| buffer.remote_id()).ok()
4115                            })
4116                            .collect(),
4117                    })
4118                    .await?
4119                    .transaction
4120                    .ok_or_else(|| anyhow!("missing transaction"))?;
4121                project_transaction = this
4122                    .update(&mut cx, |this, cx| {
4123                        this.deserialize_project_transaction(response, push_to_history, cx)
4124                    })?
4125                    .await?;
4126            }
4127
4128            for buffer in local_buffers {
4129                let transaction = buffer
4130                    .update(&mut cx, |buffer, cx| buffer.reload(cx))?
4131                    .await?;
4132                buffer.update(&mut cx, |buffer, cx| {
4133                    if let Some(transaction) = transaction {
4134                        if !push_to_history {
4135                            buffer.forget_transaction(transaction.id);
4136                        }
4137                        project_transaction.0.insert(cx.handle(), transaction);
4138                    }
4139                })?;
4140            }
4141
4142            Ok(project_transaction)
4143        })
4144    }
4145
4146    pub fn format(
4147        &mut self,
4148        buffers: HashSet<Model<Buffer>>,
4149        push_to_history: bool,
4150        trigger: FormatTrigger,
4151        cx: &mut ModelContext<Project>,
4152    ) -> Task<anyhow::Result<ProjectTransaction>> {
4153        if self.is_local() {
4154            let mut buffers_with_paths_and_servers = buffers
4155                .into_iter()
4156                .filter_map(|buffer_handle| {
4157                    let buffer = buffer_handle.read(cx);
4158                    let file = File::from_dyn(buffer.file())?;
4159                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
4160                    let server = self
4161                        .primary_language_server_for_buffer(buffer, cx)
4162                        .map(|s| s.1.clone());
4163                    Some((buffer_handle, buffer_abs_path, server))
4164                })
4165                .collect::<Vec<_>>();
4166
4167            cx.spawn(move |project, mut cx| async move {
4168                // Do not allow multiple concurrent formatting requests for the
4169                // same buffer.
4170                project.update(&mut cx, |this, cx| {
4171                    buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
4172                        this.buffers_being_formatted
4173                            .insert(buffer.read(cx).remote_id())
4174                    });
4175                })?;
4176
4177                let _cleanup = defer({
4178                    let this = project.clone();
4179                    let mut cx = cx.clone();
4180                    let buffers = &buffers_with_paths_and_servers;
4181                    move || {
4182                        this.update(&mut cx, |this, cx| {
4183                            for (buffer, _, _) in buffers {
4184                                this.buffers_being_formatted
4185                                    .remove(&buffer.read(cx).remote_id());
4186                            }
4187                        })
4188                        .ok();
4189                    }
4190                });
4191
4192                let mut project_transaction = ProjectTransaction::default();
4193                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
4194                    let settings = buffer.update(&mut cx, |buffer, cx| {
4195                        language_settings(buffer.language(), buffer.file(), cx).clone()
4196                    })?;
4197
4198                    let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
4199                    let ensure_final_newline = settings.ensure_final_newline_on_save;
4200                    let tab_size = settings.tab_size;
4201
4202                    // First, format buffer's whitespace according to the settings.
4203                    let trailing_whitespace_diff = if remove_trailing_whitespace {
4204                        Some(
4205                            buffer
4206                                .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
4207                                .await,
4208                        )
4209                    } else {
4210                        None
4211                    };
4212                    let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
4213                        buffer.finalize_last_transaction();
4214                        buffer.start_transaction();
4215                        if let Some(diff) = trailing_whitespace_diff {
4216                            buffer.apply_diff(diff, cx);
4217                        }
4218                        if ensure_final_newline {
4219                            buffer.ensure_final_newline(cx);
4220                        }
4221                        buffer.end_transaction(cx)
4222                    })?;
4223
4224                    // Apply language-specific formatting using either a language server
4225                    // or external command.
4226                    let mut format_operation = None;
4227                    match (&settings.formatter, &settings.format_on_save) {
4228                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4229
4230                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4231                        | (_, FormatOnSave::LanguageServer) => {
4232                            if let Some((language_server, buffer_abs_path)) =
4233                                language_server.as_ref().zip(buffer_abs_path.as_ref())
4234                            {
4235                                format_operation = Some(FormatOperation::Lsp(
4236                                    Self::format_via_lsp(
4237                                        &project,
4238                                        &buffer,
4239                                        buffer_abs_path,
4240                                        &language_server,
4241                                        tab_size,
4242                                        &mut cx,
4243                                    )
4244                                    .await
4245                                    .context("failed to format via language server")?,
4246                                ));
4247                            }
4248                        }
4249
4250                        (
4251                            Formatter::External { command, arguments },
4252                            FormatOnSave::On | FormatOnSave::Off,
4253                        )
4254                        | (_, FormatOnSave::External { command, arguments }) => {
4255                            if let Some(buffer_abs_path) = buffer_abs_path {
4256                                format_operation = Self::format_via_external_command(
4257                                    buffer,
4258                                    buffer_abs_path,
4259                                    &command,
4260                                    &arguments,
4261                                    &mut cx,
4262                                )
4263                                .await
4264                                .context(format!(
4265                                    "failed to format via external command {:?}",
4266                                    command
4267                                ))?
4268                                .map(FormatOperation::External);
4269                            }
4270                        }
4271                        (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4272                            if let Some(new_operation) =
4273                                prettier_support::format_with_prettier(&project, buffer, &mut cx)
4274                                    .await
4275                            {
4276                                format_operation = Some(new_operation);
4277                            } else if let Some((language_server, buffer_abs_path)) =
4278                                language_server.as_ref().zip(buffer_abs_path.as_ref())
4279                            {
4280                                format_operation = Some(FormatOperation::Lsp(
4281                                    Self::format_via_lsp(
4282                                        &project,
4283                                        &buffer,
4284                                        buffer_abs_path,
4285                                        &language_server,
4286                                        tab_size,
4287                                        &mut cx,
4288                                    )
4289                                    .await
4290                                    .context("failed to format via language server")?,
4291                                ));
4292                            }
4293                        }
4294                        (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
4295                            if let Some(new_operation) =
4296                                prettier_support::format_with_prettier(&project, buffer, &mut cx)
4297                                    .await
4298                            {
4299                                format_operation = Some(new_operation);
4300                            }
4301                        }
4302                    };
4303
4304                    buffer.update(&mut cx, |b, cx| {
4305                        // If the buffer had its whitespace formatted and was edited while the language-specific
4306                        // formatting was being computed, avoid applying the language-specific formatting, because
4307                        // it can't be grouped with the whitespace formatting in the undo history.
4308                        if let Some(transaction_id) = whitespace_transaction_id {
4309                            if b.peek_undo_stack()
4310                                .map_or(true, |e| e.transaction_id() != transaction_id)
4311                            {
4312                                format_operation.take();
4313                            }
4314                        }
4315
4316                        // Apply any language-specific formatting, and group the two formatting operations
4317                        // in the buffer's undo history.
4318                        if let Some(operation) = format_operation {
4319                            match operation {
4320                                FormatOperation::Lsp(edits) => {
4321                                    b.edit(edits, None, cx);
4322                                }
4323                                FormatOperation::External(diff) => {
4324                                    b.apply_diff(diff, cx);
4325                                }
4326                                FormatOperation::Prettier(diff) => {
4327                                    b.apply_diff(diff, cx);
4328                                }
4329                            }
4330
4331                            if let Some(transaction_id) = whitespace_transaction_id {
4332                                b.group_until_transaction(transaction_id);
4333                            }
4334                        }
4335
4336                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
4337                            if !push_to_history {
4338                                b.forget_transaction(transaction.id);
4339                            }
4340                            project_transaction.0.insert(buffer.clone(), transaction);
4341                        }
4342                    })?;
4343                }
4344
4345                Ok(project_transaction)
4346            })
4347        } else {
4348            let remote_id = self.remote_id();
4349            let client = self.client.clone();
4350            cx.spawn(move |this, mut cx| async move {
4351                let mut project_transaction = ProjectTransaction::default();
4352                if let Some(project_id) = remote_id {
4353                    let response = client
4354                        .request(proto::FormatBuffers {
4355                            project_id,
4356                            trigger: trigger as i32,
4357                            buffer_ids: buffers
4358                                .iter()
4359                                .map(|buffer| {
4360                                    buffer.update(&mut cx, |buffer, _| buffer.remote_id())
4361                                })
4362                                .collect::<Result<_>>()?,
4363                        })
4364                        .await?
4365                        .transaction
4366                        .ok_or_else(|| anyhow!("missing transaction"))?;
4367                    project_transaction = this
4368                        .update(&mut cx, |this, cx| {
4369                            this.deserialize_project_transaction(response, push_to_history, cx)
4370                        })?
4371                        .await?;
4372                }
4373                Ok(project_transaction)
4374            })
4375        }
4376    }
4377
4378    async fn format_via_lsp(
4379        this: &WeakModel<Self>,
4380        buffer: &Model<Buffer>,
4381        abs_path: &Path,
4382        language_server: &Arc<LanguageServer>,
4383        tab_size: NonZeroU32,
4384        cx: &mut AsyncAppContext,
4385    ) -> Result<Vec<(Range<Anchor>, String)>> {
4386        let uri = lsp::Url::from_file_path(abs_path)
4387            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4388        let text_document = lsp::TextDocumentIdentifier::new(uri);
4389        let capabilities = &language_server.capabilities();
4390
4391        let formatting_provider = capabilities.document_formatting_provider.as_ref();
4392        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4393
4394        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4395            language_server
4396                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4397                    text_document,
4398                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4399                    work_done_progress_params: Default::default(),
4400                })
4401                .await?
4402        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4403            let buffer_start = lsp::Position::new(0, 0);
4404            let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
4405
4406            language_server
4407                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4408                    text_document,
4409                    range: lsp::Range::new(buffer_start, buffer_end),
4410                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4411                    work_done_progress_params: Default::default(),
4412                })
4413                .await?
4414        } else {
4415            None
4416        };
4417
4418        if let Some(lsp_edits) = lsp_edits {
4419            this.update(cx, |this, cx| {
4420                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4421            })?
4422            .await
4423        } else {
4424            Ok(Vec::new())
4425        }
4426    }
4427
4428    async fn format_via_external_command(
4429        buffer: &Model<Buffer>,
4430        buffer_abs_path: &Path,
4431        command: &str,
4432        arguments: &[String],
4433        cx: &mut AsyncAppContext,
4434    ) -> Result<Option<Diff>> {
4435        let working_dir_path = buffer.update(cx, |buffer, cx| {
4436            let file = File::from_dyn(buffer.file())?;
4437            let worktree = file.worktree.read(cx).as_local()?;
4438            let mut worktree_path = worktree.abs_path().to_path_buf();
4439            if worktree.root_entry()?.is_file() {
4440                worktree_path.pop();
4441            }
4442            Some(worktree_path)
4443        })?;
4444
4445        if let Some(working_dir_path) = working_dir_path {
4446            let mut child =
4447                smol::process::Command::new(command)
4448                    .args(arguments.iter().map(|arg| {
4449                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4450                    }))
4451                    .current_dir(&working_dir_path)
4452                    .stdin(smol::process::Stdio::piped())
4453                    .stdout(smol::process::Stdio::piped())
4454                    .stderr(smol::process::Stdio::piped())
4455                    .spawn()?;
4456            let stdin = child
4457                .stdin
4458                .as_mut()
4459                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4460            let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
4461            for chunk in text.chunks() {
4462                stdin.write_all(chunk.as_bytes()).await?;
4463            }
4464            stdin.flush().await?;
4465
4466            let output = child.output().await?;
4467            if !output.status.success() {
4468                return Err(anyhow!(
4469                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4470                    output.status.code(),
4471                    String::from_utf8_lossy(&output.stdout),
4472                    String::from_utf8_lossy(&output.stderr),
4473                ));
4474            }
4475
4476            let stdout = String::from_utf8(output.stdout)?;
4477            Ok(Some(
4478                buffer
4479                    .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
4480                    .await,
4481            ))
4482        } else {
4483            Ok(None)
4484        }
4485    }
4486
4487    pub fn definition<T: ToPointUtf16>(
4488        &self,
4489        buffer: &Model<Buffer>,
4490        position: T,
4491        cx: &mut ModelContext<Self>,
4492    ) -> Task<Result<Vec<LocationLink>>> {
4493        let position = position.to_point_utf16(buffer.read(cx));
4494        self.request_lsp(
4495            buffer.clone(),
4496            LanguageServerToQuery::Primary,
4497            GetDefinition { position },
4498            cx,
4499        )
4500    }
4501
4502    pub fn type_definition<T: ToPointUtf16>(
4503        &self,
4504        buffer: &Model<Buffer>,
4505        position: T,
4506        cx: &mut ModelContext<Self>,
4507    ) -> Task<Result<Vec<LocationLink>>> {
4508        let position = position.to_point_utf16(buffer.read(cx));
4509        self.request_lsp(
4510            buffer.clone(),
4511            LanguageServerToQuery::Primary,
4512            GetTypeDefinition { position },
4513            cx,
4514        )
4515    }
4516
4517    pub fn references<T: ToPointUtf16>(
4518        &self,
4519        buffer: &Model<Buffer>,
4520        position: T,
4521        cx: &mut ModelContext<Self>,
4522    ) -> Task<Result<Vec<Location>>> {
4523        let position = position.to_point_utf16(buffer.read(cx));
4524        self.request_lsp(
4525            buffer.clone(),
4526            LanguageServerToQuery::Primary,
4527            GetReferences { position },
4528            cx,
4529        )
4530    }
4531
4532    pub fn document_highlights<T: ToPointUtf16>(
4533        &self,
4534        buffer: &Model<Buffer>,
4535        position: T,
4536        cx: &mut ModelContext<Self>,
4537    ) -> Task<Result<Vec<DocumentHighlight>>> {
4538        let position = position.to_point_utf16(buffer.read(cx));
4539        self.request_lsp(
4540            buffer.clone(),
4541            LanguageServerToQuery::Primary,
4542            GetDocumentHighlights { position },
4543            cx,
4544        )
4545    }
4546
4547    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4548        if self.is_local() {
4549            let mut requests = Vec::new();
4550            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4551                let worktree_id = *worktree_id;
4552                let worktree_handle = self.worktree_for_id(worktree_id, cx);
4553                let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4554                    Some(worktree) => worktree,
4555                    None => continue,
4556                };
4557                let worktree_abs_path = worktree.abs_path().clone();
4558
4559                let (adapter, language, server) = match self.language_servers.get(server_id) {
4560                    Some(LanguageServerState::Running {
4561                        adapter,
4562                        language,
4563                        server,
4564                        ..
4565                    }) => (adapter.clone(), language.clone(), server),
4566
4567                    _ => continue,
4568                };
4569
4570                requests.push(
4571                    server
4572                        .request::<lsp::request::WorkspaceSymbolRequest>(
4573                            lsp::WorkspaceSymbolParams {
4574                                query: query.to_string(),
4575                                ..Default::default()
4576                            },
4577                        )
4578                        .log_err()
4579                        .map(move |response| {
4580                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4581                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4582                                    flat_responses.into_iter().map(|lsp_symbol| {
4583                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4584                                    }).collect::<Vec<_>>()
4585                                }
4586                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4587                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
4588                                        let location = match lsp_symbol.location {
4589                                            OneOf::Left(location) => location,
4590                                            OneOf::Right(_) => {
4591                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4592                                                return None
4593                                            }
4594                                        };
4595                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
4596                                    }).collect::<Vec<_>>()
4597                                }
4598                            }).unwrap_or_default();
4599
4600                            (
4601                                adapter,
4602                                language,
4603                                worktree_id,
4604                                worktree_abs_path,
4605                                lsp_symbols,
4606                            )
4607                        }),
4608                );
4609            }
4610
4611            cx.spawn(move |this, mut cx| async move {
4612                let responses = futures::future::join_all(requests).await;
4613                let this = match this.upgrade() {
4614                    Some(this) => this,
4615                    None => return Ok(Vec::new()),
4616                };
4617
4618                let symbols = this.update(&mut cx, |this, cx| {
4619                    let mut symbols = Vec::new();
4620                    for (
4621                        adapter,
4622                        adapter_language,
4623                        source_worktree_id,
4624                        worktree_abs_path,
4625                        lsp_symbols,
4626                    ) in responses
4627                    {
4628                        symbols.extend(lsp_symbols.into_iter().filter_map(
4629                            |(symbol_name, symbol_kind, symbol_location)| {
4630                                let abs_path = symbol_location.uri.to_file_path().ok()?;
4631                                let mut worktree_id = source_worktree_id;
4632                                let path;
4633                                if let Some((worktree, rel_path)) =
4634                                    this.find_local_worktree(&abs_path, cx)
4635                                {
4636                                    worktree_id = worktree.read(cx).id();
4637                                    path = rel_path;
4638                                } else {
4639                                    path = relativize_path(&worktree_abs_path, &abs_path);
4640                                }
4641
4642                                let project_path = ProjectPath {
4643                                    worktree_id,
4644                                    path: path.into(),
4645                                };
4646                                let signature = this.symbol_signature(&project_path);
4647                                let adapter_language = adapter_language.clone();
4648                                let language = this
4649                                    .languages
4650                                    .language_for_file(&project_path.path, None)
4651                                    .unwrap_or_else(move |_| adapter_language);
4652                                let language_server_name = adapter.name.clone();
4653                                Some(async move {
4654                                    let language = language.await;
4655                                    let label =
4656                                        language.label_for_symbol(&symbol_name, symbol_kind).await;
4657
4658                                    Symbol {
4659                                        language_server_name,
4660                                        source_worktree_id,
4661                                        path: project_path,
4662                                        label: label.unwrap_or_else(|| {
4663                                            CodeLabel::plain(symbol_name.clone(), None)
4664                                        }),
4665                                        kind: symbol_kind,
4666                                        name: symbol_name,
4667                                        range: range_from_lsp(symbol_location.range),
4668                                        signature,
4669                                    }
4670                                })
4671                            },
4672                        ));
4673                    }
4674
4675                    symbols
4676                })?;
4677
4678                Ok(futures::future::join_all(symbols).await)
4679            })
4680        } else if let Some(project_id) = self.remote_id() {
4681            let request = self.client.request(proto::GetProjectSymbols {
4682                project_id,
4683                query: query.to_string(),
4684            });
4685            cx.spawn(move |this, mut cx| async move {
4686                let response = request.await?;
4687                let mut symbols = Vec::new();
4688                if let Some(this) = this.upgrade() {
4689                    let new_symbols = this.update(&mut cx, |this, _| {
4690                        response
4691                            .symbols
4692                            .into_iter()
4693                            .map(|symbol| this.deserialize_symbol(symbol))
4694                            .collect::<Vec<_>>()
4695                    })?;
4696                    symbols = futures::future::join_all(new_symbols)
4697                        .await
4698                        .into_iter()
4699                        .filter_map(|symbol| symbol.log_err())
4700                        .collect::<Vec<_>>();
4701                }
4702                Ok(symbols)
4703            })
4704        } else {
4705            Task::ready(Ok(Default::default()))
4706        }
4707    }
4708
4709    pub fn open_buffer_for_symbol(
4710        &mut self,
4711        symbol: &Symbol,
4712        cx: &mut ModelContext<Self>,
4713    ) -> Task<Result<Model<Buffer>>> {
4714        if self.is_local() {
4715            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4716                symbol.source_worktree_id,
4717                symbol.language_server_name.clone(),
4718            )) {
4719                *id
4720            } else {
4721                return Task::ready(Err(anyhow!(
4722                    "language server for worktree and language not found"
4723                )));
4724            };
4725
4726            let worktree_abs_path = if let Some(worktree_abs_path) = self
4727                .worktree_for_id(symbol.path.worktree_id, cx)
4728                .and_then(|worktree| worktree.read(cx).as_local())
4729                .map(|local_worktree| local_worktree.abs_path())
4730            {
4731                worktree_abs_path
4732            } else {
4733                return Task::ready(Err(anyhow!("worktree not found for symbol")));
4734            };
4735            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
4736            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4737                uri
4738            } else {
4739                return Task::ready(Err(anyhow!("invalid symbol path")));
4740            };
4741
4742            self.open_local_buffer_via_lsp(
4743                symbol_uri,
4744                language_server_id,
4745                symbol.language_server_name.clone(),
4746                cx,
4747            )
4748        } else if let Some(project_id) = self.remote_id() {
4749            let request = self.client.request(proto::OpenBufferForSymbol {
4750                project_id,
4751                symbol: Some(serialize_symbol(symbol)),
4752            });
4753            cx.spawn(move |this, mut cx| async move {
4754                let response = request.await?;
4755                this.update(&mut cx, |this, cx| {
4756                    this.wait_for_remote_buffer(response.buffer_id, cx)
4757                })?
4758                .await
4759            })
4760        } else {
4761            Task::ready(Err(anyhow!("project does not have a remote id")))
4762        }
4763    }
4764
4765    pub fn hover<T: ToPointUtf16>(
4766        &self,
4767        buffer: &Model<Buffer>,
4768        position: T,
4769        cx: &mut ModelContext<Self>,
4770    ) -> Task<Result<Option<Hover>>> {
4771        let position = position.to_point_utf16(buffer.read(cx));
4772        self.request_lsp(
4773            buffer.clone(),
4774            LanguageServerToQuery::Primary,
4775            GetHover { position },
4776            cx,
4777        )
4778    }
4779
4780    pub fn completions<T: ToOffset + ToPointUtf16>(
4781        &self,
4782        buffer: &Model<Buffer>,
4783        position: T,
4784        cx: &mut ModelContext<Self>,
4785    ) -> Task<Result<Vec<Completion>>> {
4786        let position = position.to_point_utf16(buffer.read(cx));
4787        if self.is_local() {
4788            let snapshot = buffer.read(cx).snapshot();
4789            let offset = position.to_offset(&snapshot);
4790            let scope = snapshot.language_scope_at(offset);
4791
4792            let server_ids: Vec<_> = self
4793                .language_servers_for_buffer(buffer.read(cx), cx)
4794                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4795                .filter(|(adapter, _)| {
4796                    scope
4797                        .as_ref()
4798                        .map(|scope| scope.language_allowed(&adapter.name))
4799                        .unwrap_or(true)
4800                })
4801                .map(|(_, server)| server.server_id())
4802                .collect();
4803
4804            let buffer = buffer.clone();
4805            cx.spawn(move |this, mut cx| async move {
4806                let mut tasks = Vec::with_capacity(server_ids.len());
4807                this.update(&mut cx, |this, cx| {
4808                    for server_id in server_ids {
4809                        tasks.push(this.request_lsp(
4810                            buffer.clone(),
4811                            LanguageServerToQuery::Other(server_id),
4812                            GetCompletions { position },
4813                            cx,
4814                        ));
4815                    }
4816                })?;
4817
4818                let mut completions = Vec::new();
4819                for task in tasks {
4820                    if let Ok(new_completions) = task.await {
4821                        completions.extend_from_slice(&new_completions);
4822                    }
4823                }
4824
4825                Ok(completions)
4826            })
4827        } else if let Some(project_id) = self.remote_id() {
4828            self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4829        } else {
4830            Task::ready(Ok(Default::default()))
4831        }
4832    }
4833
4834    pub fn apply_additional_edits_for_completion(
4835        &self,
4836        buffer_handle: Model<Buffer>,
4837        completion: Completion,
4838        push_to_history: bool,
4839        cx: &mut ModelContext<Self>,
4840    ) -> Task<Result<Option<Transaction>>> {
4841        let buffer = buffer_handle.read(cx);
4842        let buffer_id = buffer.remote_id();
4843
4844        if self.is_local() {
4845            let server_id = completion.server_id;
4846            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
4847                Some((_, server)) => server.clone(),
4848                _ => return Task::ready(Ok(Default::default())),
4849            };
4850
4851            cx.spawn(move |this, mut cx| async move {
4852                let can_resolve = lang_server
4853                    .capabilities()
4854                    .completion_provider
4855                    .as_ref()
4856                    .and_then(|options| options.resolve_provider)
4857                    .unwrap_or(false);
4858                let additional_text_edits = if can_resolve {
4859                    lang_server
4860                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4861                        .await?
4862                        .additional_text_edits
4863                } else {
4864                    completion.lsp_completion.additional_text_edits
4865                };
4866                if let Some(edits) = additional_text_edits {
4867                    let edits = this
4868                        .update(&mut cx, |this, cx| {
4869                            this.edits_from_lsp(
4870                                &buffer_handle,
4871                                edits,
4872                                lang_server.server_id(),
4873                                None,
4874                                cx,
4875                            )
4876                        })?
4877                        .await?;
4878
4879                    buffer_handle.update(&mut cx, |buffer, cx| {
4880                        buffer.finalize_last_transaction();
4881                        buffer.start_transaction();
4882
4883                        for (range, text) in edits {
4884                            let primary = &completion.old_range;
4885                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
4886                                && primary.end.cmp(&range.start, buffer).is_ge();
4887                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
4888                                && range.end.cmp(&primary.end, buffer).is_ge();
4889
4890                            //Skip additional edits which overlap with the primary completion edit
4891                            //https://github.com/zed-industries/zed/pull/1871
4892                            if !start_within && !end_within {
4893                                buffer.edit([(range, text)], None, cx);
4894                            }
4895                        }
4896
4897                        let transaction = if buffer.end_transaction(cx).is_some() {
4898                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4899                            if !push_to_history {
4900                                buffer.forget_transaction(transaction.id);
4901                            }
4902                            Some(transaction)
4903                        } else {
4904                            None
4905                        };
4906                        Ok(transaction)
4907                    })?
4908                } else {
4909                    Ok(None)
4910                }
4911            })
4912        } else if let Some(project_id) = self.remote_id() {
4913            let client = self.client.clone();
4914            cx.spawn(move |_, mut cx| async move {
4915                let response = client
4916                    .request(proto::ApplyCompletionAdditionalEdits {
4917                        project_id,
4918                        buffer_id,
4919                        completion: Some(language::proto::serialize_completion(&completion)),
4920                    })
4921                    .await?;
4922
4923                if let Some(transaction) = response.transaction {
4924                    let transaction = language::proto::deserialize_transaction(transaction)?;
4925                    buffer_handle
4926                        .update(&mut cx, |buffer, _| {
4927                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4928                        })?
4929                        .await?;
4930                    if push_to_history {
4931                        buffer_handle.update(&mut cx, |buffer, _| {
4932                            buffer.push_transaction(transaction.clone(), Instant::now());
4933                        })?;
4934                    }
4935                    Ok(Some(transaction))
4936                } else {
4937                    Ok(None)
4938                }
4939            })
4940        } else {
4941            Task::ready(Err(anyhow!("project does not have a remote id")))
4942        }
4943    }
4944
4945    pub fn code_actions<T: Clone + ToOffset>(
4946        &self,
4947        buffer_handle: &Model<Buffer>,
4948        range: Range<T>,
4949        cx: &mut ModelContext<Self>,
4950    ) -> Task<Result<Vec<CodeAction>>> {
4951        let buffer = buffer_handle.read(cx);
4952        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4953        self.request_lsp(
4954            buffer_handle.clone(),
4955            LanguageServerToQuery::Primary,
4956            GetCodeActions { range },
4957            cx,
4958        )
4959    }
4960
4961    pub fn apply_code_action(
4962        &self,
4963        buffer_handle: Model<Buffer>,
4964        mut action: CodeAction,
4965        push_to_history: bool,
4966        cx: &mut ModelContext<Self>,
4967    ) -> Task<Result<ProjectTransaction>> {
4968        if self.is_local() {
4969            let buffer = buffer_handle.read(cx);
4970            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4971                self.language_server_for_buffer(buffer, action.server_id, cx)
4972            {
4973                (adapter.clone(), server.clone())
4974            } else {
4975                return Task::ready(Ok(Default::default()));
4976            };
4977            let range = action.range.to_point_utf16(buffer);
4978
4979            cx.spawn(move |this, mut cx| async move {
4980                if let Some(lsp_range) = action
4981                    .lsp_action
4982                    .data
4983                    .as_mut()
4984                    .and_then(|d| d.get_mut("codeActionParams"))
4985                    .and_then(|d| d.get_mut("range"))
4986                {
4987                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4988                    action.lsp_action = lang_server
4989                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4990                        .await?;
4991                } else {
4992                    let actions = this
4993                        .update(&mut cx, |this, cx| {
4994                            this.code_actions(&buffer_handle, action.range, cx)
4995                        })?
4996                        .await?;
4997                    action.lsp_action = actions
4998                        .into_iter()
4999                        .find(|a| a.lsp_action.title == action.lsp_action.title)
5000                        .ok_or_else(|| anyhow!("code action is outdated"))?
5001                        .lsp_action;
5002                }
5003
5004                if let Some(edit) = action.lsp_action.edit {
5005                    if edit.changes.is_some() || edit.document_changes.is_some() {
5006                        return Self::deserialize_workspace_edit(
5007                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5008                            edit,
5009                            push_to_history,
5010                            lsp_adapter.clone(),
5011                            lang_server.clone(),
5012                            &mut cx,
5013                        )
5014                        .await;
5015                    }
5016                }
5017
5018                if let Some(command) = action.lsp_action.command {
5019                    this.update(&mut cx, |this, _| {
5020                        this.last_workspace_edits_by_language_server
5021                            .remove(&lang_server.server_id());
5022                    })?;
5023
5024                    let result = lang_server
5025                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5026                            command: command.command,
5027                            arguments: command.arguments.unwrap_or_default(),
5028                            ..Default::default()
5029                        })
5030                        .await;
5031
5032                    if let Err(err) = result {
5033                        // TODO: LSP ERROR
5034                        return Err(err);
5035                    }
5036
5037                    return Ok(this.update(&mut cx, |this, _| {
5038                        this.last_workspace_edits_by_language_server
5039                            .remove(&lang_server.server_id())
5040                            .unwrap_or_default()
5041                    })?);
5042                }
5043
5044                Ok(ProjectTransaction::default())
5045            })
5046        } else if let Some(project_id) = self.remote_id() {
5047            let client = self.client.clone();
5048            let request = proto::ApplyCodeAction {
5049                project_id,
5050                buffer_id: buffer_handle.read(cx).remote_id(),
5051                action: Some(language::proto::serialize_code_action(&action)),
5052            };
5053            cx.spawn(move |this, mut cx| async move {
5054                let response = client
5055                    .request(request)
5056                    .await?
5057                    .transaction
5058                    .ok_or_else(|| anyhow!("missing transaction"))?;
5059                this.update(&mut cx, |this, cx| {
5060                    this.deserialize_project_transaction(response, push_to_history, cx)
5061                })?
5062                .await
5063            })
5064        } else {
5065            Task::ready(Err(anyhow!("project does not have a remote id")))
5066        }
5067    }
5068
5069    fn apply_on_type_formatting(
5070        &self,
5071        buffer: Model<Buffer>,
5072        position: Anchor,
5073        trigger: String,
5074        cx: &mut ModelContext<Self>,
5075    ) -> Task<Result<Option<Transaction>>> {
5076        if self.is_local() {
5077            cx.spawn(move |this, mut cx| async move {
5078                // Do not allow multiple concurrent formatting requests for the
5079                // same buffer.
5080                this.update(&mut cx, |this, cx| {
5081                    this.buffers_being_formatted
5082                        .insert(buffer.read(cx).remote_id())
5083                })?;
5084
5085                let _cleanup = defer({
5086                    let this = this.clone();
5087                    let mut cx = cx.clone();
5088                    let closure_buffer = buffer.clone();
5089                    move || {
5090                        this.update(&mut cx, |this, cx| {
5091                            this.buffers_being_formatted
5092                                .remove(&closure_buffer.read(cx).remote_id());
5093                        })
5094                        .ok();
5095                    }
5096                });
5097
5098                buffer
5099                    .update(&mut cx, |buffer, _| {
5100                        buffer.wait_for_edits(Some(position.timestamp))
5101                    })?
5102                    .await?;
5103                this.update(&mut cx, |this, cx| {
5104                    let position = position.to_point_utf16(buffer.read(cx));
5105                    this.on_type_format(buffer, position, trigger, false, cx)
5106                })?
5107                .await
5108            })
5109        } else if let Some(project_id) = self.remote_id() {
5110            let client = self.client.clone();
5111            let request = proto::OnTypeFormatting {
5112                project_id,
5113                buffer_id: buffer.read(cx).remote_id(),
5114                position: Some(serialize_anchor(&position)),
5115                trigger,
5116                version: serialize_version(&buffer.read(cx).version()),
5117            };
5118            cx.spawn(move |_, _| async move {
5119                client
5120                    .request(request)
5121                    .await?
5122                    .transaction
5123                    .map(language::proto::deserialize_transaction)
5124                    .transpose()
5125            })
5126        } else {
5127            Task::ready(Err(anyhow!("project does not have a remote id")))
5128        }
5129    }
5130
5131    async fn deserialize_edits(
5132        this: Model<Self>,
5133        buffer_to_edit: Model<Buffer>,
5134        edits: Vec<lsp::TextEdit>,
5135        push_to_history: bool,
5136        _: Arc<CachedLspAdapter>,
5137        language_server: Arc<LanguageServer>,
5138        cx: &mut AsyncAppContext,
5139    ) -> Result<Option<Transaction>> {
5140        let edits = this
5141            .update(cx, |this, cx| {
5142                this.edits_from_lsp(
5143                    &buffer_to_edit,
5144                    edits,
5145                    language_server.server_id(),
5146                    None,
5147                    cx,
5148                )
5149            })?
5150            .await?;
5151
5152        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5153            buffer.finalize_last_transaction();
5154            buffer.start_transaction();
5155            for (range, text) in edits {
5156                buffer.edit([(range, text)], None, cx);
5157            }
5158
5159            if buffer.end_transaction(cx).is_some() {
5160                let transaction = buffer.finalize_last_transaction().unwrap().clone();
5161                if !push_to_history {
5162                    buffer.forget_transaction(transaction.id);
5163                }
5164                Some(transaction)
5165            } else {
5166                None
5167            }
5168        })?;
5169
5170        Ok(transaction)
5171    }
5172
5173    async fn deserialize_workspace_edit(
5174        this: Model<Self>,
5175        edit: lsp::WorkspaceEdit,
5176        push_to_history: bool,
5177        lsp_adapter: Arc<CachedLspAdapter>,
5178        language_server: Arc<LanguageServer>,
5179        cx: &mut AsyncAppContext,
5180    ) -> Result<ProjectTransaction> {
5181        let fs = this.update(cx, |this, _| this.fs.clone())?;
5182        let mut operations = Vec::new();
5183        if let Some(document_changes) = edit.document_changes {
5184            match document_changes {
5185                lsp::DocumentChanges::Edits(edits) => {
5186                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5187                }
5188                lsp::DocumentChanges::Operations(ops) => operations = ops,
5189            }
5190        } else if let Some(changes) = edit.changes {
5191            operations.extend(changes.into_iter().map(|(uri, edits)| {
5192                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5193                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5194                        uri,
5195                        version: None,
5196                    },
5197                    edits: edits.into_iter().map(OneOf::Left).collect(),
5198                })
5199            }));
5200        }
5201
5202        let mut project_transaction = ProjectTransaction::default();
5203        for operation in operations {
5204            match operation {
5205                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5206                    let abs_path = op
5207                        .uri
5208                        .to_file_path()
5209                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5210
5211                    if let Some(parent_path) = abs_path.parent() {
5212                        fs.create_dir(parent_path).await?;
5213                    }
5214                    if abs_path.ends_with("/") {
5215                        fs.create_dir(&abs_path).await?;
5216                    } else {
5217                        fs.create_file(
5218                            &abs_path,
5219                            op.options
5220                                .map(|options| fs::CreateOptions {
5221                                    overwrite: options.overwrite.unwrap_or(false),
5222                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5223                                })
5224                                .unwrap_or_default(),
5225                        )
5226                        .await?;
5227                    }
5228                }
5229
5230                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5231                    let source_abs_path = op
5232                        .old_uri
5233                        .to_file_path()
5234                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5235                    let target_abs_path = op
5236                        .new_uri
5237                        .to_file_path()
5238                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5239                    fs.rename(
5240                        &source_abs_path,
5241                        &target_abs_path,
5242                        op.options
5243                            .map(|options| fs::RenameOptions {
5244                                overwrite: options.overwrite.unwrap_or(false),
5245                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5246                            })
5247                            .unwrap_or_default(),
5248                    )
5249                    .await?;
5250                }
5251
5252                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5253                    let abs_path = op
5254                        .uri
5255                        .to_file_path()
5256                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5257                    let options = op
5258                        .options
5259                        .map(|options| fs::RemoveOptions {
5260                            recursive: options.recursive.unwrap_or(false),
5261                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5262                        })
5263                        .unwrap_or_default();
5264                    if abs_path.ends_with("/") {
5265                        fs.remove_dir(&abs_path, options).await?;
5266                    } else {
5267                        fs.remove_file(&abs_path, options).await?;
5268                    }
5269                }
5270
5271                lsp::DocumentChangeOperation::Edit(op) => {
5272                    let buffer_to_edit = this
5273                        .update(cx, |this, cx| {
5274                            this.open_local_buffer_via_lsp(
5275                                op.text_document.uri,
5276                                language_server.server_id(),
5277                                lsp_adapter.name.clone(),
5278                                cx,
5279                            )
5280                        })?
5281                        .await?;
5282
5283                    let edits = this
5284                        .update(cx, |this, cx| {
5285                            let edits = op.edits.into_iter().map(|edit| match edit {
5286                                OneOf::Left(edit) => edit,
5287                                OneOf::Right(edit) => edit.text_edit,
5288                            });
5289                            this.edits_from_lsp(
5290                                &buffer_to_edit,
5291                                edits,
5292                                language_server.server_id(),
5293                                op.text_document.version,
5294                                cx,
5295                            )
5296                        })?
5297                        .await?;
5298
5299                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5300                        buffer.finalize_last_transaction();
5301                        buffer.start_transaction();
5302                        for (range, text) in edits {
5303                            buffer.edit([(range, text)], None, cx);
5304                        }
5305                        let transaction = if buffer.end_transaction(cx).is_some() {
5306                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5307                            if !push_to_history {
5308                                buffer.forget_transaction(transaction.id);
5309                            }
5310                            Some(transaction)
5311                        } else {
5312                            None
5313                        };
5314
5315                        transaction
5316                    })?;
5317                    if let Some(transaction) = transaction {
5318                        project_transaction.0.insert(buffer_to_edit, transaction);
5319                    }
5320                }
5321            }
5322        }
5323
5324        Ok(project_transaction)
5325    }
5326
5327    pub fn prepare_rename<T: ToPointUtf16>(
5328        &self,
5329        buffer: Model<Buffer>,
5330        position: T,
5331        cx: &mut ModelContext<Self>,
5332    ) -> Task<Result<Option<Range<Anchor>>>> {
5333        let position = position.to_point_utf16(buffer.read(cx));
5334        self.request_lsp(
5335            buffer,
5336            LanguageServerToQuery::Primary,
5337            PrepareRename { position },
5338            cx,
5339        )
5340    }
5341
5342    pub fn perform_rename<T: ToPointUtf16>(
5343        &self,
5344        buffer: Model<Buffer>,
5345        position: T,
5346        new_name: String,
5347        push_to_history: bool,
5348        cx: &mut ModelContext<Self>,
5349    ) -> Task<Result<ProjectTransaction>> {
5350        let position = position.to_point_utf16(buffer.read(cx));
5351        self.request_lsp(
5352            buffer,
5353            LanguageServerToQuery::Primary,
5354            PerformRename {
5355                position,
5356                new_name,
5357                push_to_history,
5358            },
5359            cx,
5360        )
5361    }
5362
5363    pub fn on_type_format<T: ToPointUtf16>(
5364        &self,
5365        buffer: Model<Buffer>,
5366        position: T,
5367        trigger: String,
5368        push_to_history: bool,
5369        cx: &mut ModelContext<Self>,
5370    ) -> Task<Result<Option<Transaction>>> {
5371        let (position, tab_size) = buffer.update(cx, |buffer, cx| {
5372            let position = position.to_point_utf16(buffer);
5373            (
5374                position,
5375                language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
5376                    .tab_size,
5377            )
5378        });
5379        self.request_lsp(
5380            buffer.clone(),
5381            LanguageServerToQuery::Primary,
5382            OnTypeFormatting {
5383                position,
5384                trigger,
5385                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5386                push_to_history,
5387            },
5388            cx,
5389        )
5390    }
5391
5392    pub fn inlay_hints<T: ToOffset>(
5393        &self,
5394        buffer_handle: Model<Buffer>,
5395        range: Range<T>,
5396        cx: &mut ModelContext<Self>,
5397    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5398        let buffer = buffer_handle.read(cx);
5399        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5400        let range_start = range.start;
5401        let range_end = range.end;
5402        let buffer_id = buffer.remote_id();
5403        let buffer_version = buffer.version().clone();
5404        let lsp_request = InlayHints { range };
5405
5406        if self.is_local() {
5407            let lsp_request_task = self.request_lsp(
5408                buffer_handle.clone(),
5409                LanguageServerToQuery::Primary,
5410                lsp_request,
5411                cx,
5412            );
5413            cx.spawn(move |_, mut cx| async move {
5414                buffer_handle
5415                    .update(&mut cx, |buffer, _| {
5416                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5417                    })?
5418                    .await
5419                    .context("waiting for inlay hint request range edits")?;
5420                lsp_request_task.await.context("inlay hints LSP request")
5421            })
5422        } else if let Some(project_id) = self.remote_id() {
5423            let client = self.client.clone();
5424            let request = proto::InlayHints {
5425                project_id,
5426                buffer_id,
5427                start: Some(serialize_anchor(&range_start)),
5428                end: Some(serialize_anchor(&range_end)),
5429                version: serialize_version(&buffer_version),
5430            };
5431            cx.spawn(move |project, cx| async move {
5432                let response = client
5433                    .request(request)
5434                    .await
5435                    .context("inlay hints proto request")?;
5436                let hints_request_result = LspCommand::response_from_proto(
5437                    lsp_request,
5438                    response,
5439                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5440                    buffer_handle.clone(),
5441                    cx,
5442                )
5443                .await;
5444
5445                hints_request_result.context("inlay hints proto response conversion")
5446            })
5447        } else {
5448            Task::ready(Err(anyhow!("project does not have a remote id")))
5449        }
5450    }
5451
5452    pub fn resolve_inlay_hint(
5453        &self,
5454        hint: InlayHint,
5455        buffer_handle: Model<Buffer>,
5456        server_id: LanguageServerId,
5457        cx: &mut ModelContext<Self>,
5458    ) -> Task<anyhow::Result<InlayHint>> {
5459        if self.is_local() {
5460            let buffer = buffer_handle.read(cx);
5461            let (_, lang_server) = if let Some((adapter, server)) =
5462                self.language_server_for_buffer(buffer, server_id, cx)
5463            {
5464                (adapter.clone(), server.clone())
5465            } else {
5466                return Task::ready(Ok(hint));
5467            };
5468            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5469                return Task::ready(Ok(hint));
5470            }
5471
5472            let buffer_snapshot = buffer.snapshot();
5473            cx.spawn(move |_, mut cx| async move {
5474                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5475                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5476                );
5477                let resolved_hint = resolve_task
5478                    .await
5479                    .context("inlay hint resolve LSP request")?;
5480                let resolved_hint = InlayHints::lsp_to_project_hint(
5481                    resolved_hint,
5482                    &buffer_handle,
5483                    server_id,
5484                    ResolveState::Resolved,
5485                    false,
5486                    &mut cx,
5487                )
5488                .await?;
5489                Ok(resolved_hint)
5490            })
5491        } else if let Some(project_id) = self.remote_id() {
5492            let client = self.client.clone();
5493            let request = proto::ResolveInlayHint {
5494                project_id,
5495                buffer_id: buffer_handle.read(cx).remote_id(),
5496                language_server_id: server_id.0 as u64,
5497                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5498            };
5499            cx.spawn(move |_, _| async move {
5500                let response = client
5501                    .request(request)
5502                    .await
5503                    .context("inlay hints proto request")?;
5504                match response.hint {
5505                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5506                        .context("inlay hints proto resolve response conversion"),
5507                    None => Ok(hint),
5508                }
5509            })
5510        } else {
5511            Task::ready(Err(anyhow!("project does not have a remote id")))
5512        }
5513    }
5514
5515    #[allow(clippy::type_complexity)]
5516    pub fn search(
5517        &self,
5518        query: SearchQuery,
5519        cx: &mut ModelContext<Self>,
5520    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5521        if self.is_local() {
5522            self.search_local(query, cx)
5523        } else if let Some(project_id) = self.remote_id() {
5524            let (tx, rx) = smol::channel::unbounded();
5525            let request = self.client.request(query.to_proto(project_id));
5526            cx.spawn(move |this, mut cx| async move {
5527                let response = request.await?;
5528                let mut result = HashMap::default();
5529                for location in response.locations {
5530                    let target_buffer = this
5531                        .update(&mut cx, |this, cx| {
5532                            this.wait_for_remote_buffer(location.buffer_id, cx)
5533                        })?
5534                        .await?;
5535                    let start = location
5536                        .start
5537                        .and_then(deserialize_anchor)
5538                        .ok_or_else(|| anyhow!("missing target start"))?;
5539                    let end = location
5540                        .end
5541                        .and_then(deserialize_anchor)
5542                        .ok_or_else(|| anyhow!("missing target end"))?;
5543                    result
5544                        .entry(target_buffer)
5545                        .or_insert(Vec::new())
5546                        .push(start..end)
5547                }
5548                for (buffer, ranges) in result {
5549                    let _ = tx.send((buffer, ranges)).await;
5550                }
5551                Result::<(), anyhow::Error>::Ok(())
5552            })
5553            .detach_and_log_err(cx);
5554            rx
5555        } else {
5556            unimplemented!();
5557        }
5558    }
5559
5560    pub fn search_local(
5561        &self,
5562        query: SearchQuery,
5563        cx: &mut ModelContext<Self>,
5564    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5565        // Local search is split into several phases.
5566        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5567        // and the second phase that finds positions of all the matches found in the candidate files.
5568        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5569        //
5570        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5571        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5572        //
5573        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5574        //    Then, we go through a worktree and check for files that do match a predicate. If the file had an opened version, we skip the scan
5575        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5576        // 2. At this point, we have a list of all potentially matching buffers/files.
5577        //    We sort that list by buffer path - this list is retained for later use.
5578        //    We ensure that all buffers are now opened and available in project.
5579        // 3. We run a scan over all the candidate buffers on multiple background threads.
5580        //    We cannot assume that there will even be a match - while at least one match
5581        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5582        //    There is also an auxilliary background thread responsible for result gathering.
5583        //    This is where the sorted list of buffers comes into play to maintain sorted order; Whenever this background thread receives a notification (buffer has/doesn't have matches),
5584        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5585        //    As soon as the match info on next position in sorted order becomes available, it reports it (if it's a match) or skips to the next
5586        //    entry - which might already be available thanks to out-of-order processing.
5587        //
5588        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5589        // This however would mean that project search (that is the main user of this function) would have to do the sorting itself, on the go.
5590        // This isn't as straightforward as running an insertion sort sadly, and would also mean that it would have to care about maintaining match index
5591        // in face of constantly updating list of sorted matches.
5592        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5593        let snapshots = self
5594            .visible_worktrees(cx)
5595            .filter_map(|tree| {
5596                let tree = tree.read(cx).as_local()?;
5597                Some(tree.snapshot())
5598            })
5599            .collect::<Vec<_>>();
5600
5601        let background = cx.background_executor().clone();
5602        let path_count: usize = snapshots
5603            .iter()
5604            .map(|s| {
5605                if query.include_ignored() {
5606                    s.file_count()
5607                } else {
5608                    s.visible_file_count()
5609                }
5610            })
5611            .sum();
5612        if path_count == 0 {
5613            let (_, rx) = smol::channel::bounded(1024);
5614            return rx;
5615        }
5616        let workers = background.num_cpus().min(path_count);
5617        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5618        let mut unnamed_files = vec![];
5619        let opened_buffers = self
5620            .opened_buffers
5621            .iter()
5622            .filter_map(|(_, b)| {
5623                let buffer = b.upgrade()?;
5624                let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
5625                    let is_ignored = buffer
5626                        .project_path(cx)
5627                        .and_then(|path| self.entry_for_path(&path, cx))
5628                        .map_or(false, |entry| entry.is_ignored);
5629                    (is_ignored, buffer.snapshot())
5630                });
5631                if is_ignored && !query.include_ignored() {
5632                    return None;
5633                } else if let Some(path) = snapshot.file().map(|file| file.path()) {
5634                    Some((path.clone(), (buffer, snapshot)))
5635                } else {
5636                    unnamed_files.push(buffer);
5637                    None
5638                }
5639            })
5640            .collect();
5641        cx.background_executor()
5642            .spawn(Self::background_search(
5643                unnamed_files,
5644                opened_buffers,
5645                cx.background_executor().clone(),
5646                self.fs.clone(),
5647                workers,
5648                query.clone(),
5649                path_count,
5650                snapshots,
5651                matching_paths_tx,
5652            ))
5653            .detach();
5654
5655        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5656        let background = cx.background_executor().clone();
5657        let (result_tx, result_rx) = smol::channel::bounded(1024);
5658        cx.background_executor()
5659            .spawn(async move {
5660                let Ok(buffers) = buffers.await else {
5661                    return;
5662                };
5663
5664                let buffers_len = buffers.len();
5665                if buffers_len == 0 {
5666                    return;
5667                }
5668                let query = &query;
5669                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5670                background
5671                    .scoped(|scope| {
5672                        #[derive(Clone)]
5673                        struct FinishedStatus {
5674                            entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
5675                            buffer_index: SearchMatchCandidateIndex,
5676                        }
5677
5678                        for _ in 0..workers {
5679                            let finished_tx = finished_tx.clone();
5680                            let mut buffers_rx = buffers_rx.clone();
5681                            scope.spawn(async move {
5682                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
5683                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5684                                    {
5685                                        if query.file_matches(
5686                                            snapshot.file().map(|file| file.path().as_ref()),
5687                                        ) {
5688                                            query
5689                                                .search(&snapshot, None)
5690                                                .await
5691                                                .iter()
5692                                                .map(|range| {
5693                                                    snapshot.anchor_before(range.start)
5694                                                        ..snapshot.anchor_after(range.end)
5695                                                })
5696                                                .collect()
5697                                        } else {
5698                                            Vec::new()
5699                                        }
5700                                    } else {
5701                                        Vec::new()
5702                                    };
5703
5704                                    let status = if !buffer_matches.is_empty() {
5705                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
5706                                            Some((buffer.clone(), buffer_matches))
5707                                        } else {
5708                                            None
5709                                        };
5710                                        FinishedStatus {
5711                                            entry,
5712                                            buffer_index,
5713                                        }
5714                                    } else {
5715                                        FinishedStatus {
5716                                            entry: None,
5717                                            buffer_index,
5718                                        }
5719                                    };
5720                                    if finished_tx.send(status).await.is_err() {
5721                                        break;
5722                                    }
5723                                }
5724                            });
5725                        }
5726                        // Report sorted matches
5727                        scope.spawn(async move {
5728                            let mut current_index = 0;
5729                            let mut scratch = vec![None; buffers_len];
5730                            while let Some(status) = finished_rx.next().await {
5731                                debug_assert!(
5732                                    scratch[status.buffer_index].is_none(),
5733                                    "Got match status of position {} twice",
5734                                    status.buffer_index
5735                                );
5736                                let index = status.buffer_index;
5737                                scratch[index] = Some(status);
5738                                while current_index < buffers_len {
5739                                    let Some(current_entry) = scratch[current_index].take() else {
5740                                        // We intentionally **do not** increment `current_index` here. When next element arrives
5741                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5742                                        // this time.
5743                                        break;
5744                                    };
5745                                    if let Some(entry) = current_entry.entry {
5746                                        result_tx.send(entry).await.log_err();
5747                                    }
5748                                    current_index += 1;
5749                                }
5750                                if current_index == buffers_len {
5751                                    break;
5752                                }
5753                            }
5754                        });
5755                    })
5756                    .await;
5757            })
5758            .detach();
5759        result_rx
5760    }
5761
5762    /// Pick paths that might potentially contain a match of a given search query.
5763    async fn background_search(
5764        unnamed_buffers: Vec<Model<Buffer>>,
5765        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
5766        executor: BackgroundExecutor,
5767        fs: Arc<dyn Fs>,
5768        workers: usize,
5769        query: SearchQuery,
5770        path_count: usize,
5771        snapshots: Vec<LocalSnapshot>,
5772        matching_paths_tx: Sender<SearchMatchCandidate>,
5773    ) {
5774        let fs = &fs;
5775        let query = &query;
5776        let matching_paths_tx = &matching_paths_tx;
5777        let snapshots = &snapshots;
5778        let paths_per_worker = (path_count + workers - 1) / workers;
5779        for buffer in unnamed_buffers {
5780            matching_paths_tx
5781                .send(SearchMatchCandidate::OpenBuffer {
5782                    buffer: buffer.clone(),
5783                    path: None,
5784                })
5785                .await
5786                .log_err();
5787        }
5788        for (path, (buffer, _)) in opened_buffers.iter() {
5789            matching_paths_tx
5790                .send(SearchMatchCandidate::OpenBuffer {
5791                    buffer: buffer.clone(),
5792                    path: Some(path.clone()),
5793                })
5794                .await
5795                .log_err();
5796        }
5797        executor
5798            .scoped(|scope| {
5799                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
5800
5801                for worker_ix in 0..workers {
5802                    let worker_start_ix = worker_ix * paths_per_worker;
5803                    let worker_end_ix = worker_start_ix + paths_per_worker;
5804                    let unnamed_buffers = opened_buffers.clone();
5805                    let limiter = Arc::clone(&max_concurrent_workers);
5806                    scope.spawn(async move {
5807                        let _guard = limiter.acquire().await;
5808                        let mut snapshot_start_ix = 0;
5809                        let mut abs_path = PathBuf::new();
5810                        for snapshot in snapshots {
5811                            let snapshot_end_ix = snapshot_start_ix
5812                                + if query.include_ignored() {
5813                                    snapshot.file_count()
5814                                } else {
5815                                    snapshot.visible_file_count()
5816                                };
5817                            if worker_end_ix <= snapshot_start_ix {
5818                                break;
5819                            } else if worker_start_ix > snapshot_end_ix {
5820                                snapshot_start_ix = snapshot_end_ix;
5821                                continue;
5822                            } else {
5823                                let start_in_snapshot =
5824                                    worker_start_ix.saturating_sub(snapshot_start_ix);
5825                                let end_in_snapshot =
5826                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5827
5828                                for entry in snapshot
5829                                    .files(query.include_ignored(), start_in_snapshot)
5830                                    .take(end_in_snapshot - start_in_snapshot)
5831                                {
5832                                    if matching_paths_tx.is_closed() {
5833                                        break;
5834                                    }
5835                                    if unnamed_buffers.contains_key(&entry.path) {
5836                                        continue;
5837                                    }
5838                                    let matches = if query.file_matches(Some(&entry.path)) {
5839                                        abs_path.clear();
5840                                        abs_path.push(&snapshot.abs_path());
5841                                        abs_path.push(&entry.path);
5842                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
5843                                        {
5844                                            query.detect(file).unwrap_or(false)
5845                                        } else {
5846                                            false
5847                                        }
5848                                    } else {
5849                                        false
5850                                    };
5851
5852                                    if matches {
5853                                        let project_path = SearchMatchCandidate::Path {
5854                                            worktree_id: snapshot.id(),
5855                                            path: entry.path.clone(),
5856                                            is_ignored: entry.is_ignored,
5857                                        };
5858                                        if matching_paths_tx.send(project_path).await.is_err() {
5859                                            break;
5860                                        }
5861                                    }
5862                                }
5863
5864                                snapshot_start_ix = snapshot_end_ix;
5865                            }
5866                        }
5867                    });
5868                }
5869
5870                if query.include_ignored() {
5871                    for snapshot in snapshots {
5872                        for ignored_entry in snapshot
5873                            .entries(query.include_ignored())
5874                            .filter(|e| e.is_ignored)
5875                        {
5876                            let limiter = Arc::clone(&max_concurrent_workers);
5877                            scope.spawn(async move {
5878                                let _guard = limiter.acquire().await;
5879                                let mut ignored_paths_to_process =
5880                                    VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
5881                                while let Some(ignored_abs_path) =
5882                                    ignored_paths_to_process.pop_front()
5883                                {
5884                                    if let Some(fs_metadata) = fs
5885                                        .metadata(&ignored_abs_path)
5886                                        .await
5887                                        .with_context(|| {
5888                                            format!("fetching fs metadata for {ignored_abs_path:?}")
5889                                        })
5890                                        .log_err()
5891                                        .flatten()
5892                                    {
5893                                        if fs_metadata.is_dir {
5894                                            if let Some(mut subfiles) = fs
5895                                                .read_dir(&ignored_abs_path)
5896                                                .await
5897                                                .with_context(|| {
5898                                                    format!(
5899                                                        "listing ignored path {ignored_abs_path:?}"
5900                                                    )
5901                                                })
5902                                                .log_err()
5903                                            {
5904                                                while let Some(subfile) = subfiles.next().await {
5905                                                    if let Some(subfile) = subfile.log_err() {
5906                                                        ignored_paths_to_process.push_back(subfile);
5907                                                    }
5908                                                }
5909                                            }
5910                                        } else if !fs_metadata.is_symlink {
5911                                            if !query.file_matches(Some(&ignored_abs_path))
5912                                                || snapshot.is_path_excluded(
5913                                                    ignored_entry.path.to_path_buf(),
5914                                                )
5915                                            {
5916                                                continue;
5917                                            }
5918                                            let matches = if let Some(file) = fs
5919                                                .open_sync(&ignored_abs_path)
5920                                                .await
5921                                                .with_context(|| {
5922                                                    format!(
5923                                                        "Opening ignored path {ignored_abs_path:?}"
5924                                                    )
5925                                                })
5926                                                .log_err()
5927                                            {
5928                                                query.detect(file).unwrap_or(false)
5929                                            } else {
5930                                                false
5931                                            };
5932                                            if matches {
5933                                                let project_path = SearchMatchCandidate::Path {
5934                                                    worktree_id: snapshot.id(),
5935                                                    path: Arc::from(
5936                                                        ignored_abs_path
5937                                                            .strip_prefix(snapshot.abs_path())
5938                                                            .expect(
5939                                                                "scanning worktree-related files",
5940                                                            ),
5941                                                    ),
5942                                                    is_ignored: true,
5943                                                };
5944                                                if matching_paths_tx
5945                                                    .send(project_path)
5946                                                    .await
5947                                                    .is_err()
5948                                                {
5949                                                    return;
5950                                                }
5951                                            }
5952                                        }
5953                                    }
5954                                }
5955                            });
5956                        }
5957                    }
5958                }
5959            })
5960            .await;
5961    }
5962
5963    pub fn request_lsp<R: LspCommand>(
5964        &self,
5965        buffer_handle: Model<Buffer>,
5966        server: LanguageServerToQuery,
5967        request: R,
5968        cx: &mut ModelContext<Self>,
5969    ) -> Task<Result<R::Response>>
5970    where
5971        <R::LspRequest as lsp::request::Request>::Result: Send,
5972        <R::LspRequest as lsp::request::Request>::Params: Send,
5973    {
5974        let buffer = buffer_handle.read(cx);
5975        if self.is_local() {
5976            let language_server = match server {
5977                LanguageServerToQuery::Primary => {
5978                    match self.primary_language_server_for_buffer(buffer, cx) {
5979                        Some((_, server)) => Some(Arc::clone(server)),
5980                        None => return Task::ready(Ok(Default::default())),
5981                    }
5982                }
5983                LanguageServerToQuery::Other(id) => self
5984                    .language_server_for_buffer(buffer, id, cx)
5985                    .map(|(_, server)| Arc::clone(server)),
5986            };
5987            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5988            if let (Some(file), Some(language_server)) = (file, language_server) {
5989                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5990                return cx.spawn(move |this, cx| async move {
5991                    if !request.check_capabilities(language_server.capabilities()) {
5992                        return Ok(Default::default());
5993                    }
5994
5995                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
5996                    let response = match result {
5997                        Ok(response) => response,
5998
5999                        Err(err) => {
6000                            log::warn!(
6001                                "Generic lsp request to {} failed: {}",
6002                                language_server.name(),
6003                                err
6004                            );
6005                            return Err(err);
6006                        }
6007                    };
6008
6009                    request
6010                        .response_from_lsp(
6011                            response,
6012                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6013                            buffer_handle,
6014                            language_server.server_id(),
6015                            cx,
6016                        )
6017                        .await
6018                });
6019            }
6020        } else if let Some(project_id) = self.remote_id() {
6021            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6022        }
6023
6024        Task::ready(Ok(Default::default()))
6025    }
6026
6027    fn send_lsp_proto_request<R: LspCommand>(
6028        &self,
6029        buffer: Model<Buffer>,
6030        project_id: u64,
6031        request: R,
6032        cx: &mut ModelContext<'_, Project>,
6033    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6034        let rpc = self.client.clone();
6035        let message = request.to_proto(project_id, buffer.read(cx));
6036        cx.spawn(move |this, mut cx| async move {
6037            // Ensure the project is still alive by the time the task
6038            // is scheduled.
6039            this.upgrade().context("project dropped")?;
6040            let response = rpc.request(message).await?;
6041            let this = this.upgrade().context("project dropped")?;
6042            if this.update(&mut cx, |this, _| this.is_disconnected())? {
6043                Err(anyhow!("disconnected before completing request"))
6044            } else {
6045                request
6046                    .response_from_proto(response, this, buffer, cx)
6047                    .await
6048            }
6049        })
6050    }
6051
6052    fn sort_candidates_and_open_buffers(
6053        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
6054        cx: &mut ModelContext<Self>,
6055    ) -> (
6056        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
6057        Receiver<(
6058            Option<(Model<Buffer>, BufferSnapshot)>,
6059            SearchMatchCandidateIndex,
6060        )>,
6061    ) {
6062        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
6063        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
6064        cx.spawn(move |this, cx| async move {
6065            let mut buffers = Vec::new();
6066            let mut ignored_buffers = Vec::new();
6067            while let Some(entry) = matching_paths_rx.next().await {
6068                if matches!(
6069                    entry,
6070                    SearchMatchCandidate::Path {
6071                        is_ignored: true,
6072                        ..
6073                    }
6074                ) {
6075                    ignored_buffers.push(entry);
6076                } else {
6077                    buffers.push(entry);
6078                }
6079            }
6080            buffers.sort_by_key(|candidate| candidate.path());
6081            ignored_buffers.sort_by_key(|candidate| candidate.path());
6082            buffers.extend(ignored_buffers);
6083            let matching_paths = buffers.clone();
6084            let _ = sorted_buffers_tx.send(buffers);
6085            for (index, candidate) in matching_paths.into_iter().enumerate() {
6086                if buffers_tx.is_closed() {
6087                    break;
6088                }
6089                let this = this.clone();
6090                let buffers_tx = buffers_tx.clone();
6091                cx.spawn(move |mut cx| async move {
6092                    let buffer = match candidate {
6093                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6094                        SearchMatchCandidate::Path {
6095                            worktree_id, path, ..
6096                        } => this
6097                            .update(&mut cx, |this, cx| {
6098                                this.open_buffer((worktree_id, path), cx)
6099                            })?
6100                            .await
6101                            .log_err(),
6102                    };
6103                    if let Some(buffer) = buffer {
6104                        let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6105                        buffers_tx
6106                            .send((Some((buffer, snapshot)), index))
6107                            .await
6108                            .log_err();
6109                    } else {
6110                        buffers_tx.send((None, index)).await.log_err();
6111                    }
6112
6113                    Ok::<_, anyhow::Error>(())
6114                })
6115                .detach();
6116            }
6117        })
6118        .detach();
6119        (sorted_buffers_rx, buffers_rx)
6120    }
6121
6122    pub fn find_or_create_local_worktree(
6123        &mut self,
6124        abs_path: impl AsRef<Path>,
6125        visible: bool,
6126        cx: &mut ModelContext<Self>,
6127    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6128        let abs_path = abs_path.as_ref();
6129        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6130            Task::ready(Ok((tree, relative_path)))
6131        } else {
6132            let worktree = self.create_local_worktree(abs_path, visible, cx);
6133            cx.background_executor()
6134                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6135        }
6136    }
6137
6138    pub fn find_local_worktree(
6139        &self,
6140        abs_path: &Path,
6141        cx: &AppContext,
6142    ) -> Option<(Model<Worktree>, PathBuf)> {
6143        for tree in &self.worktrees {
6144            if let Some(tree) = tree.upgrade() {
6145                if let Some(relative_path) = tree
6146                    .read(cx)
6147                    .as_local()
6148                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6149                {
6150                    return Some((tree.clone(), relative_path.into()));
6151                }
6152            }
6153        }
6154        None
6155    }
6156
6157    pub fn is_shared(&self) -> bool {
6158        match &self.client_state {
6159            Some(ProjectClientState::Local { .. }) => true,
6160            _ => false,
6161        }
6162    }
6163
6164    fn create_local_worktree(
6165        &mut self,
6166        abs_path: impl AsRef<Path>,
6167        visible: bool,
6168        cx: &mut ModelContext<Self>,
6169    ) -> Task<Result<Model<Worktree>>> {
6170        let fs = self.fs.clone();
6171        let client = self.client.clone();
6172        let next_entry_id = self.next_entry_id.clone();
6173        let path: Arc<Path> = abs_path.as_ref().into();
6174        let task = self
6175            .loading_local_worktrees
6176            .entry(path.clone())
6177            .or_insert_with(|| {
6178                cx.spawn(move |project, mut cx| {
6179                    async move {
6180                        let worktree = Worktree::local(
6181                            client.clone(),
6182                            path.clone(),
6183                            visible,
6184                            fs,
6185                            next_entry_id,
6186                            &mut cx,
6187                        )
6188                        .await;
6189
6190                        project.update(&mut cx, |project, _| {
6191                            project.loading_local_worktrees.remove(&path);
6192                        })?;
6193
6194                        let worktree = worktree?;
6195                        project
6196                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6197                        Ok(worktree)
6198                    }
6199                    .map_err(Arc::new)
6200                })
6201                .shared()
6202            })
6203            .clone();
6204        cx.background_executor().spawn(async move {
6205            match task.await {
6206                Ok(worktree) => Ok(worktree),
6207                Err(err) => Err(anyhow!("{}", err)),
6208            }
6209        })
6210    }
6211
6212    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6213        self.worktrees.retain(|worktree| {
6214            if let Some(worktree) = worktree.upgrade() {
6215                let id = worktree.read(cx).id();
6216                if id == id_to_remove {
6217                    cx.emit(Event::WorktreeRemoved(id));
6218                    false
6219                } else {
6220                    true
6221                }
6222            } else {
6223                false
6224            }
6225        });
6226        self.metadata_changed(cx);
6227    }
6228
6229    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6230        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6231        if worktree.read(cx).is_local() {
6232            cx.subscribe(worktree, |this, worktree, event, cx| match event {
6233                worktree::Event::UpdatedEntries(changes) => {
6234                    this.update_local_worktree_buffers(&worktree, changes, cx);
6235                    this.update_local_worktree_language_servers(&worktree, changes, cx);
6236                    this.update_local_worktree_settings(&worktree, changes, cx);
6237                    this.update_prettier_settings(&worktree, changes, cx);
6238                    cx.emit(Event::WorktreeUpdatedEntries(
6239                        worktree.read(cx).id(),
6240                        changes.clone(),
6241                    ));
6242                }
6243                worktree::Event::UpdatedGitRepositories(updated_repos) => {
6244                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6245                }
6246            })
6247            .detach();
6248        }
6249
6250        let push_strong_handle = {
6251            let worktree = worktree.read(cx);
6252            self.is_shared() || worktree.is_visible() || worktree.is_remote()
6253        };
6254        if push_strong_handle {
6255            self.worktrees
6256                .push(WorktreeHandle::Strong(worktree.clone()));
6257        } else {
6258            self.worktrees
6259                .push(WorktreeHandle::Weak(worktree.downgrade()));
6260        }
6261
6262        let handle_id = worktree.entity_id();
6263        cx.observe_release(worktree, move |this, worktree, cx| {
6264            let _ = this.remove_worktree(worktree.id(), cx);
6265            cx.update_global::<SettingsStore, _>(|store, cx| {
6266                store
6267                    .clear_local_settings(handle_id.as_u64() as usize, cx)
6268                    .log_err()
6269            });
6270        })
6271        .detach();
6272
6273        cx.emit(Event::WorktreeAdded);
6274        self.metadata_changed(cx);
6275    }
6276
6277    fn update_local_worktree_buffers(
6278        &mut self,
6279        worktree_handle: &Model<Worktree>,
6280        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6281        cx: &mut ModelContext<Self>,
6282    ) {
6283        let snapshot = worktree_handle.read(cx).snapshot();
6284
6285        let mut renamed_buffers = Vec::new();
6286        for (path, entry_id, _) in changes {
6287            let worktree_id = worktree_handle.read(cx).id();
6288            let project_path = ProjectPath {
6289                worktree_id,
6290                path: path.clone(),
6291            };
6292
6293            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6294                Some(&buffer_id) => buffer_id,
6295                None => match self.local_buffer_ids_by_path.get(&project_path) {
6296                    Some(&buffer_id) => buffer_id,
6297                    None => {
6298                        continue;
6299                    }
6300                },
6301            };
6302
6303            let open_buffer = self.opened_buffers.get(&buffer_id);
6304            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6305                buffer
6306            } else {
6307                self.opened_buffers.remove(&buffer_id);
6308                self.local_buffer_ids_by_path.remove(&project_path);
6309                self.local_buffer_ids_by_entry_id.remove(entry_id);
6310                continue;
6311            };
6312
6313            buffer.update(cx, |buffer, cx| {
6314                if let Some(old_file) = File::from_dyn(buffer.file()) {
6315                    if old_file.worktree != *worktree_handle {
6316                        return;
6317                    }
6318
6319                    let new_file = if let Some(entry) = old_file
6320                        .entry_id
6321                        .and_then(|entry_id| snapshot.entry_for_id(entry_id))
6322                    {
6323                        File {
6324                            is_local: true,
6325                            entry_id: Some(entry.id),
6326                            mtime: entry.mtime,
6327                            path: entry.path.clone(),
6328                            worktree: worktree_handle.clone(),
6329                            is_deleted: false,
6330                        }
6331                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6332                        File {
6333                            is_local: true,
6334                            entry_id: Some(entry.id),
6335                            mtime: entry.mtime,
6336                            path: entry.path.clone(),
6337                            worktree: worktree_handle.clone(),
6338                            is_deleted: false,
6339                        }
6340                    } else {
6341                        File {
6342                            is_local: true,
6343                            entry_id: old_file.entry_id,
6344                            path: old_file.path().clone(),
6345                            mtime: old_file.mtime(),
6346                            worktree: worktree_handle.clone(),
6347                            is_deleted: true,
6348                        }
6349                    };
6350
6351                    let old_path = old_file.abs_path(cx);
6352                    if new_file.abs_path(cx) != old_path {
6353                        renamed_buffers.push((cx.handle(), old_file.clone()));
6354                        self.local_buffer_ids_by_path.remove(&project_path);
6355                        self.local_buffer_ids_by_path.insert(
6356                            ProjectPath {
6357                                worktree_id,
6358                                path: path.clone(),
6359                            },
6360                            buffer_id,
6361                        );
6362                    }
6363
6364                    if new_file.entry_id != Some(*entry_id) {
6365                        self.local_buffer_ids_by_entry_id.remove(entry_id);
6366                        if let Some(entry_id) = new_file.entry_id {
6367                            self.local_buffer_ids_by_entry_id
6368                                .insert(entry_id, buffer_id);
6369                        }
6370                    }
6371
6372                    if new_file != *old_file {
6373                        if let Some(project_id) = self.remote_id() {
6374                            self.client
6375                                .send(proto::UpdateBufferFile {
6376                                    project_id,
6377                                    buffer_id: buffer_id as u64,
6378                                    file: Some(new_file.to_proto()),
6379                                })
6380                                .log_err();
6381                        }
6382
6383                        buffer.file_updated(Arc::new(new_file), cx);
6384                    }
6385                }
6386            });
6387        }
6388
6389        for (buffer, old_file) in renamed_buffers {
6390            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6391            self.detect_language_for_buffer(&buffer, cx);
6392            self.register_buffer_with_language_servers(&buffer, cx);
6393        }
6394    }
6395
6396    fn update_local_worktree_language_servers(
6397        &mut self,
6398        worktree_handle: &Model<Worktree>,
6399        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6400        cx: &mut ModelContext<Self>,
6401    ) {
6402        if changes.is_empty() {
6403            return;
6404        }
6405
6406        let worktree_id = worktree_handle.read(cx).id();
6407        let mut language_server_ids = self
6408            .language_server_ids
6409            .iter()
6410            .filter_map(|((server_worktree_id, _), server_id)| {
6411                (*server_worktree_id == worktree_id).then_some(*server_id)
6412            })
6413            .collect::<Vec<_>>();
6414        language_server_ids.sort();
6415        language_server_ids.dedup();
6416
6417        let abs_path = worktree_handle.read(cx).abs_path();
6418        for server_id in &language_server_ids {
6419            if let Some(LanguageServerState::Running {
6420                server,
6421                watched_paths,
6422                ..
6423            }) = self.language_servers.get(server_id)
6424            {
6425                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6426                    let params = lsp::DidChangeWatchedFilesParams {
6427                        changes: changes
6428                            .iter()
6429                            .filter_map(|(path, _, change)| {
6430                                if !watched_paths.is_match(&path) {
6431                                    return None;
6432                                }
6433                                let typ = match change {
6434                                    PathChange::Loaded => return None,
6435                                    PathChange::Added => lsp::FileChangeType::CREATED,
6436                                    PathChange::Removed => lsp::FileChangeType::DELETED,
6437                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
6438                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6439                                };
6440                                Some(lsp::FileEvent {
6441                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6442                                    typ,
6443                                })
6444                            })
6445                            .collect(),
6446                    };
6447
6448                    if !params.changes.is_empty() {
6449                        server
6450                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6451                            .log_err();
6452                    }
6453                }
6454            }
6455        }
6456    }
6457
6458    fn update_local_worktree_buffers_git_repos(
6459        &mut self,
6460        worktree_handle: Model<Worktree>,
6461        changed_repos: &UpdatedGitRepositoriesSet,
6462        cx: &mut ModelContext<Self>,
6463    ) {
6464        debug_assert!(worktree_handle.read(cx).is_local());
6465
6466        // Identify the loading buffers whose containing repository that has changed.
6467        let future_buffers = self
6468            .loading_buffers_by_path
6469            .iter()
6470            .filter_map(|(project_path, receiver)| {
6471                if project_path.worktree_id != worktree_handle.read(cx).id() {
6472                    return None;
6473                }
6474                let path = &project_path.path;
6475                changed_repos
6476                    .iter()
6477                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6478                let receiver = receiver.clone();
6479                let path = path.clone();
6480                Some(async move {
6481                    wait_for_loading_buffer(receiver)
6482                        .await
6483                        .ok()
6484                        .map(|buffer| (buffer, path))
6485                })
6486            })
6487            .collect::<FuturesUnordered<_>>();
6488
6489        // Identify the current buffers whose containing repository has changed.
6490        let current_buffers = self
6491            .opened_buffers
6492            .values()
6493            .filter_map(|buffer| {
6494                let buffer = buffer.upgrade()?;
6495                let file = File::from_dyn(buffer.read(cx).file())?;
6496                if file.worktree != worktree_handle {
6497                    return None;
6498                }
6499                let path = file.path();
6500                changed_repos
6501                    .iter()
6502                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6503                Some((buffer, path.clone()))
6504            })
6505            .collect::<Vec<_>>();
6506
6507        if future_buffers.len() + current_buffers.len() == 0 {
6508            return;
6509        }
6510
6511        let remote_id = self.remote_id();
6512        let client = self.client.clone();
6513        cx.spawn(move |_, mut cx| async move {
6514            // Wait for all of the buffers to load.
6515            let future_buffers = future_buffers.collect::<Vec<_>>().await;
6516
6517            // Reload the diff base for every buffer whose containing git repository has changed.
6518            let snapshot =
6519                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
6520            let diff_bases_by_buffer = cx
6521                .background_executor()
6522                .spawn(async move {
6523                    future_buffers
6524                        .into_iter()
6525                        .filter_map(|e| e)
6526                        .chain(current_buffers)
6527                        .filter_map(|(buffer, path)| {
6528                            let (work_directory, repo) =
6529                                snapshot.repository_and_work_directory_for_path(&path)?;
6530                            let repo = snapshot.get_local_repo(&repo)?;
6531                            let relative_path = path.strip_prefix(&work_directory).ok()?;
6532                            let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
6533                            Some((buffer, base_text))
6534                        })
6535                        .collect::<Vec<_>>()
6536                })
6537                .await;
6538
6539            // Assign the new diff bases on all of the buffers.
6540            for (buffer, diff_base) in diff_bases_by_buffer {
6541                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6542                    buffer.set_diff_base(diff_base.clone(), cx);
6543                    buffer.remote_id()
6544                })?;
6545                if let Some(project_id) = remote_id {
6546                    client
6547                        .send(proto::UpdateDiffBase {
6548                            project_id,
6549                            buffer_id,
6550                            diff_base,
6551                        })
6552                        .log_err();
6553                }
6554            }
6555
6556            anyhow::Ok(())
6557        })
6558        .detach();
6559    }
6560
6561    fn update_local_worktree_settings(
6562        &mut self,
6563        worktree: &Model<Worktree>,
6564        changes: &UpdatedEntriesSet,
6565        cx: &mut ModelContext<Self>,
6566    ) {
6567        let project_id = self.remote_id();
6568        let worktree_id = worktree.entity_id();
6569        let worktree = worktree.read(cx).as_local().unwrap();
6570        let remote_worktree_id = worktree.id();
6571
6572        let mut settings_contents = Vec::new();
6573        for (path, _, change) in changes.iter() {
6574            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6575                let settings_dir = Arc::from(
6576                    path.ancestors()
6577                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6578                        .unwrap(),
6579                );
6580                let fs = self.fs.clone();
6581                let removed = *change == PathChange::Removed;
6582                let abs_path = worktree.absolutize(path);
6583                settings_contents.push(async move {
6584                    (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
6585                });
6586            }
6587        }
6588
6589        if settings_contents.is_empty() {
6590            return;
6591        }
6592
6593        let client = self.client.clone();
6594        cx.spawn(move |_, cx| async move {
6595            let settings_contents: Vec<(Arc<Path>, _)> =
6596                futures::future::join_all(settings_contents).await;
6597            cx.update(|cx| {
6598                cx.update_global::<SettingsStore, _>(|store, cx| {
6599                    for (directory, file_content) in settings_contents {
6600                        let file_content = file_content.and_then(|content| content.log_err());
6601                        store
6602                            .set_local_settings(
6603                                worktree_id.as_u64() as usize,
6604                                directory.clone(),
6605                                file_content.as_ref().map(String::as_str),
6606                                cx,
6607                            )
6608                            .log_err();
6609                        if let Some(remote_id) = project_id {
6610                            client
6611                                .send(proto::UpdateWorktreeSettings {
6612                                    project_id: remote_id,
6613                                    worktree_id: remote_worktree_id.to_proto(),
6614                                    path: directory.to_string_lossy().into_owned(),
6615                                    content: file_content,
6616                                })
6617                                .log_err();
6618                        }
6619                    }
6620                });
6621            })
6622            .ok();
6623        })
6624        .detach();
6625    }
6626
6627    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6628        let new_active_entry = entry.and_then(|project_path| {
6629            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6630            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6631            Some(entry.id)
6632        });
6633        if new_active_entry != self.active_entry {
6634            self.active_entry = new_active_entry;
6635            cx.emit(Event::ActiveEntryChanged(new_active_entry));
6636        }
6637    }
6638
6639    pub fn language_servers_running_disk_based_diagnostics(
6640        &self,
6641    ) -> impl Iterator<Item = LanguageServerId> + '_ {
6642        self.language_server_statuses
6643            .iter()
6644            .filter_map(|(id, status)| {
6645                if status.has_pending_diagnostic_updates {
6646                    Some(*id)
6647                } else {
6648                    None
6649                }
6650            })
6651    }
6652
6653    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
6654        let mut summary = DiagnosticSummary::default();
6655        for (_, _, path_summary) in
6656            self.diagnostic_summaries(include_ignored, cx)
6657                .filter(|(path, _, _)| {
6658                    let worktree = self.entry_for_path(&path, cx).map(|entry| entry.is_ignored);
6659                    include_ignored || worktree == Some(false)
6660                })
6661        {
6662            summary.error_count += path_summary.error_count;
6663            summary.warning_count += path_summary.warning_count;
6664        }
6665        summary
6666    }
6667
6668    pub fn diagnostic_summaries<'a>(
6669        &'a self,
6670        include_ignored: bool,
6671        cx: &'a AppContext,
6672    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6673        self.visible_worktrees(cx)
6674            .flat_map(move |worktree| {
6675                let worktree = worktree.read(cx);
6676                let worktree_id = worktree.id();
6677                worktree
6678                    .diagnostic_summaries()
6679                    .map(move |(path, server_id, summary)| {
6680                        (ProjectPath { worktree_id, path }, server_id, summary)
6681                    })
6682            })
6683            .filter(move |(path, _, _)| {
6684                let worktree = self.entry_for_path(&path, cx).map(|entry| entry.is_ignored);
6685                include_ignored || worktree == Some(false)
6686            })
6687    }
6688
6689    pub fn disk_based_diagnostics_started(
6690        &mut self,
6691        language_server_id: LanguageServerId,
6692        cx: &mut ModelContext<Self>,
6693    ) {
6694        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6695    }
6696
6697    pub fn disk_based_diagnostics_finished(
6698        &mut self,
6699        language_server_id: LanguageServerId,
6700        cx: &mut ModelContext<Self>,
6701    ) {
6702        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6703    }
6704
6705    pub fn active_entry(&self) -> Option<ProjectEntryId> {
6706        self.active_entry
6707    }
6708
6709    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6710        self.worktree_for_id(path.worktree_id, cx)?
6711            .read(cx)
6712            .entry_for_path(&path.path)
6713            .cloned()
6714    }
6715
6716    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6717        let worktree = self.worktree_for_entry(entry_id, cx)?;
6718        let worktree = worktree.read(cx);
6719        let worktree_id = worktree.id();
6720        let path = worktree.entry_for_id(entry_id)?.path.clone();
6721        Some(ProjectPath { worktree_id, path })
6722    }
6723
6724    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6725        let workspace_root = self
6726            .worktree_for_id(project_path.worktree_id, cx)?
6727            .read(cx)
6728            .abs_path();
6729        let project_path = project_path.path.as_ref();
6730
6731        Some(if project_path == Path::new("") {
6732            workspace_root.to_path_buf()
6733        } else {
6734            workspace_root.join(project_path)
6735        })
6736    }
6737
6738    // RPC message handlers
6739
6740    async fn handle_unshare_project(
6741        this: Model<Self>,
6742        _: TypedEnvelope<proto::UnshareProject>,
6743        _: Arc<Client>,
6744        mut cx: AsyncAppContext,
6745    ) -> Result<()> {
6746        this.update(&mut cx, |this, cx| {
6747            if this.is_local() {
6748                this.unshare(cx)?;
6749            } else {
6750                this.disconnected_from_host(cx);
6751            }
6752            Ok(())
6753        })?
6754    }
6755
6756    async fn handle_add_collaborator(
6757        this: Model<Self>,
6758        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6759        _: Arc<Client>,
6760        mut cx: AsyncAppContext,
6761    ) -> Result<()> {
6762        let collaborator = envelope
6763            .payload
6764            .collaborator
6765            .take()
6766            .ok_or_else(|| anyhow!("empty collaborator"))?;
6767
6768        let collaborator = Collaborator::from_proto(collaborator)?;
6769        this.update(&mut cx, |this, cx| {
6770            this.shared_buffers.remove(&collaborator.peer_id);
6771            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6772            this.collaborators
6773                .insert(collaborator.peer_id, collaborator);
6774            cx.notify();
6775        })?;
6776
6777        Ok(())
6778    }
6779
6780    async fn handle_update_project_collaborator(
6781        this: Model<Self>,
6782        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6783        _: Arc<Client>,
6784        mut cx: AsyncAppContext,
6785    ) -> Result<()> {
6786        let old_peer_id = envelope
6787            .payload
6788            .old_peer_id
6789            .ok_or_else(|| anyhow!("missing old peer id"))?;
6790        let new_peer_id = envelope
6791            .payload
6792            .new_peer_id
6793            .ok_or_else(|| anyhow!("missing new peer id"))?;
6794        this.update(&mut cx, |this, cx| {
6795            let collaborator = this
6796                .collaborators
6797                .remove(&old_peer_id)
6798                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
6799            let is_host = collaborator.replica_id == 0;
6800            this.collaborators.insert(new_peer_id, collaborator);
6801
6802            let buffers = this.shared_buffers.remove(&old_peer_id);
6803            log::info!(
6804                "peer {} became {}. moving buffers {:?}",
6805                old_peer_id,
6806                new_peer_id,
6807                &buffers
6808            );
6809            if let Some(buffers) = buffers {
6810                this.shared_buffers.insert(new_peer_id, buffers);
6811            }
6812
6813            if is_host {
6814                this.opened_buffers
6815                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
6816                this.buffer_ordered_messages_tx
6817                    .unbounded_send(BufferOrderedMessage::Resync)
6818                    .unwrap();
6819            }
6820
6821            cx.emit(Event::CollaboratorUpdated {
6822                old_peer_id,
6823                new_peer_id,
6824            });
6825            cx.notify();
6826            Ok(())
6827        })?
6828    }
6829
6830    async fn handle_remove_collaborator(
6831        this: Model<Self>,
6832        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
6833        _: Arc<Client>,
6834        mut cx: AsyncAppContext,
6835    ) -> Result<()> {
6836        this.update(&mut cx, |this, cx| {
6837            let peer_id = envelope
6838                .payload
6839                .peer_id
6840                .ok_or_else(|| anyhow!("invalid peer id"))?;
6841            let replica_id = this
6842                .collaborators
6843                .remove(&peer_id)
6844                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
6845                .replica_id;
6846            for buffer in this.opened_buffers.values() {
6847                if let Some(buffer) = buffer.upgrade() {
6848                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
6849                }
6850            }
6851            this.shared_buffers.remove(&peer_id);
6852
6853            cx.emit(Event::CollaboratorLeft(peer_id));
6854            cx.notify();
6855            Ok(())
6856        })?
6857    }
6858
6859    async fn handle_update_project(
6860        this: Model<Self>,
6861        envelope: TypedEnvelope<proto::UpdateProject>,
6862        _: Arc<Client>,
6863        mut cx: AsyncAppContext,
6864    ) -> Result<()> {
6865        this.update(&mut cx, |this, cx| {
6866            // Don't handle messages that were sent before the response to us joining the project
6867            if envelope.message_id > this.join_project_response_message_id {
6868                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
6869            }
6870            Ok(())
6871        })?
6872    }
6873
6874    async fn handle_update_worktree(
6875        this: Model<Self>,
6876        envelope: TypedEnvelope<proto::UpdateWorktree>,
6877        _: Arc<Client>,
6878        mut cx: AsyncAppContext,
6879    ) -> Result<()> {
6880        this.update(&mut cx, |this, cx| {
6881            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6882            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6883                worktree.update(cx, |worktree, _| {
6884                    let worktree = worktree.as_remote_mut().unwrap();
6885                    worktree.update_from_remote(envelope.payload);
6886                });
6887            }
6888            Ok(())
6889        })?
6890    }
6891
6892    async fn handle_update_worktree_settings(
6893        this: Model<Self>,
6894        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6895        _: Arc<Client>,
6896        mut cx: AsyncAppContext,
6897    ) -> Result<()> {
6898        this.update(&mut cx, |this, cx| {
6899            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6900            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6901                cx.update_global::<SettingsStore, _>(|store, cx| {
6902                    store
6903                        .set_local_settings(
6904                            worktree.entity_id().as_u64() as usize,
6905                            PathBuf::from(&envelope.payload.path).into(),
6906                            envelope.payload.content.as_ref().map(String::as_str),
6907                            cx,
6908                        )
6909                        .log_err();
6910                });
6911            }
6912            Ok(())
6913        })?
6914    }
6915
6916    async fn handle_create_project_entry(
6917        this: Model<Self>,
6918        envelope: TypedEnvelope<proto::CreateProjectEntry>,
6919        _: Arc<Client>,
6920        mut cx: AsyncAppContext,
6921    ) -> Result<proto::ProjectEntryResponse> {
6922        let worktree = this.update(&mut cx, |this, cx| {
6923            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6924            this.worktree_for_id(worktree_id, cx)
6925                .ok_or_else(|| anyhow!("worktree not found"))
6926        })??;
6927        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6928        let entry = worktree
6929            .update(&mut cx, |worktree, cx| {
6930                let worktree = worktree.as_local_mut().unwrap();
6931                let path = PathBuf::from(envelope.payload.path);
6932                worktree.create_entry(path, envelope.payload.is_directory, cx)
6933            })?
6934            .await?;
6935        Ok(proto::ProjectEntryResponse {
6936            entry: entry.as_ref().map(|e| e.into()),
6937            worktree_scan_id: worktree_scan_id as u64,
6938        })
6939    }
6940
6941    async fn handle_rename_project_entry(
6942        this: Model<Self>,
6943        envelope: TypedEnvelope<proto::RenameProjectEntry>,
6944        _: Arc<Client>,
6945        mut cx: AsyncAppContext,
6946    ) -> Result<proto::ProjectEntryResponse> {
6947        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6948        let worktree = this.update(&mut cx, |this, cx| {
6949            this.worktree_for_entry(entry_id, cx)
6950                .ok_or_else(|| anyhow!("worktree not found"))
6951        })??;
6952        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6953        let entry = worktree
6954            .update(&mut cx, |worktree, cx| {
6955                let new_path = PathBuf::from(envelope.payload.new_path);
6956                worktree
6957                    .as_local_mut()
6958                    .unwrap()
6959                    .rename_entry(entry_id, new_path, cx)
6960            })?
6961            .await?;
6962        Ok(proto::ProjectEntryResponse {
6963            entry: entry.as_ref().map(|e| e.into()),
6964            worktree_scan_id: worktree_scan_id as u64,
6965        })
6966    }
6967
6968    async fn handle_copy_project_entry(
6969        this: Model<Self>,
6970        envelope: TypedEnvelope<proto::CopyProjectEntry>,
6971        _: Arc<Client>,
6972        mut cx: AsyncAppContext,
6973    ) -> Result<proto::ProjectEntryResponse> {
6974        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6975        let worktree = this.update(&mut cx, |this, cx| {
6976            this.worktree_for_entry(entry_id, cx)
6977                .ok_or_else(|| anyhow!("worktree not found"))
6978        })??;
6979        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6980        let entry = worktree
6981            .update(&mut cx, |worktree, cx| {
6982                let new_path = PathBuf::from(envelope.payload.new_path);
6983                worktree
6984                    .as_local_mut()
6985                    .unwrap()
6986                    .copy_entry(entry_id, new_path, cx)
6987            })?
6988            .await?;
6989        Ok(proto::ProjectEntryResponse {
6990            entry: entry.as_ref().map(|e| e.into()),
6991            worktree_scan_id: worktree_scan_id as u64,
6992        })
6993    }
6994
6995    async fn handle_delete_project_entry(
6996        this: Model<Self>,
6997        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6998        _: Arc<Client>,
6999        mut cx: AsyncAppContext,
7000    ) -> Result<proto::ProjectEntryResponse> {
7001        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7002
7003        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
7004
7005        let worktree = this.update(&mut cx, |this, cx| {
7006            this.worktree_for_entry(entry_id, cx)
7007                .ok_or_else(|| anyhow!("worktree not found"))
7008        })??;
7009        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7010        worktree
7011            .update(&mut cx, |worktree, cx| {
7012                worktree
7013                    .as_local_mut()
7014                    .unwrap()
7015                    .delete_entry(entry_id, cx)
7016                    .ok_or_else(|| anyhow!("invalid entry"))
7017            })??
7018            .await?;
7019        Ok(proto::ProjectEntryResponse {
7020            entry: None,
7021            worktree_scan_id: worktree_scan_id as u64,
7022        })
7023    }
7024
7025    async fn handle_expand_project_entry(
7026        this: Model<Self>,
7027        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7028        _: Arc<Client>,
7029        mut cx: AsyncAppContext,
7030    ) -> Result<proto::ExpandProjectEntryResponse> {
7031        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7032        let worktree = this
7033            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7034            .ok_or_else(|| anyhow!("invalid request"))?;
7035        worktree
7036            .update(&mut cx, |worktree, cx| {
7037                worktree
7038                    .as_local_mut()
7039                    .unwrap()
7040                    .expand_entry(entry_id, cx)
7041                    .ok_or_else(|| anyhow!("invalid entry"))
7042            })??
7043            .await?;
7044        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7045        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7046    }
7047
7048    async fn handle_update_diagnostic_summary(
7049        this: Model<Self>,
7050        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7051        _: Arc<Client>,
7052        mut cx: AsyncAppContext,
7053    ) -> Result<()> {
7054        this.update(&mut cx, |this, cx| {
7055            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7056            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7057                if let Some(summary) = envelope.payload.summary {
7058                    let project_path = ProjectPath {
7059                        worktree_id,
7060                        path: Path::new(&summary.path).into(),
7061                    };
7062                    worktree.update(cx, |worktree, _| {
7063                        worktree
7064                            .as_remote_mut()
7065                            .unwrap()
7066                            .update_diagnostic_summary(project_path.path.clone(), &summary);
7067                    });
7068                    cx.emit(Event::DiagnosticsUpdated {
7069                        language_server_id: LanguageServerId(summary.language_server_id as usize),
7070                        path: project_path,
7071                    });
7072                }
7073            }
7074            Ok(())
7075        })?
7076    }
7077
7078    async fn handle_start_language_server(
7079        this: Model<Self>,
7080        envelope: TypedEnvelope<proto::StartLanguageServer>,
7081        _: Arc<Client>,
7082        mut cx: AsyncAppContext,
7083    ) -> Result<()> {
7084        let server = envelope
7085            .payload
7086            .server
7087            .ok_or_else(|| anyhow!("invalid server"))?;
7088        this.update(&mut cx, |this, cx| {
7089            this.language_server_statuses.insert(
7090                LanguageServerId(server.id as usize),
7091                LanguageServerStatus {
7092                    name: server.name,
7093                    pending_work: Default::default(),
7094                    has_pending_diagnostic_updates: false,
7095                    progress_tokens: Default::default(),
7096                },
7097            );
7098            cx.notify();
7099        })?;
7100        Ok(())
7101    }
7102
7103    async fn handle_update_language_server(
7104        this: Model<Self>,
7105        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7106        _: Arc<Client>,
7107        mut cx: AsyncAppContext,
7108    ) -> Result<()> {
7109        this.update(&mut cx, |this, cx| {
7110            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7111
7112            match envelope
7113                .payload
7114                .variant
7115                .ok_or_else(|| anyhow!("invalid variant"))?
7116            {
7117                proto::update_language_server::Variant::WorkStart(payload) => {
7118                    this.on_lsp_work_start(
7119                        language_server_id,
7120                        payload.token,
7121                        LanguageServerProgress {
7122                            message: payload.message,
7123                            percentage: payload.percentage.map(|p| p as usize),
7124                            last_update_at: Instant::now(),
7125                        },
7126                        cx,
7127                    );
7128                }
7129
7130                proto::update_language_server::Variant::WorkProgress(payload) => {
7131                    this.on_lsp_work_progress(
7132                        language_server_id,
7133                        payload.token,
7134                        LanguageServerProgress {
7135                            message: payload.message,
7136                            percentage: payload.percentage.map(|p| p as usize),
7137                            last_update_at: Instant::now(),
7138                        },
7139                        cx,
7140                    );
7141                }
7142
7143                proto::update_language_server::Variant::WorkEnd(payload) => {
7144                    this.on_lsp_work_end(language_server_id, payload.token, cx);
7145                }
7146
7147                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7148                    this.disk_based_diagnostics_started(language_server_id, cx);
7149                }
7150
7151                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7152                    this.disk_based_diagnostics_finished(language_server_id, cx)
7153                }
7154            }
7155
7156            Ok(())
7157        })?
7158    }
7159
7160    async fn handle_update_buffer(
7161        this: Model<Self>,
7162        envelope: TypedEnvelope<proto::UpdateBuffer>,
7163        _: Arc<Client>,
7164        mut cx: AsyncAppContext,
7165    ) -> Result<proto::Ack> {
7166        this.update(&mut cx, |this, cx| {
7167            let payload = envelope.payload.clone();
7168            let buffer_id = payload.buffer_id;
7169            let ops = payload
7170                .operations
7171                .into_iter()
7172                .map(language::proto::deserialize_operation)
7173                .collect::<Result<Vec<_>, _>>()?;
7174            let is_remote = this.is_remote();
7175            match this.opened_buffers.entry(buffer_id) {
7176                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7177                    OpenBuffer::Strong(buffer) => {
7178                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7179                    }
7180                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7181                    OpenBuffer::Weak(_) => {}
7182                },
7183                hash_map::Entry::Vacant(e) => {
7184                    assert!(
7185                        is_remote,
7186                        "received buffer update from {:?}",
7187                        envelope.original_sender_id
7188                    );
7189                    e.insert(OpenBuffer::Operations(ops));
7190                }
7191            }
7192            Ok(proto::Ack {})
7193        })?
7194    }
7195
7196    async fn handle_create_buffer_for_peer(
7197        this: Model<Self>,
7198        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7199        _: Arc<Client>,
7200        mut cx: AsyncAppContext,
7201    ) -> Result<()> {
7202        this.update(&mut cx, |this, cx| {
7203            match envelope
7204                .payload
7205                .variant
7206                .ok_or_else(|| anyhow!("missing variant"))?
7207            {
7208                proto::create_buffer_for_peer::Variant::State(mut state) => {
7209                    let mut buffer_file = None;
7210                    if let Some(file) = state.file.take() {
7211                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
7212                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7213                            anyhow!("no worktree found for id {}", file.worktree_id)
7214                        })?;
7215                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7216                            as Arc<dyn language::File>);
7217                    }
7218
7219                    let buffer_id = state.id;
7220                    let buffer = cx.new_model(|_| {
7221                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
7222                            .unwrap()
7223                    });
7224                    this.incomplete_remote_buffers
7225                        .insert(buffer_id, Some(buffer));
7226                }
7227                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7228                    let buffer = this
7229                        .incomplete_remote_buffers
7230                        .get(&chunk.buffer_id)
7231                        .cloned()
7232                        .flatten()
7233                        .ok_or_else(|| {
7234                            anyhow!(
7235                                "received chunk for buffer {} without initial state",
7236                                chunk.buffer_id
7237                            )
7238                        })?;
7239                    let operations = chunk
7240                        .operations
7241                        .into_iter()
7242                        .map(language::proto::deserialize_operation)
7243                        .collect::<Result<Vec<_>>>()?;
7244                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7245
7246                    if chunk.is_last {
7247                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
7248                        this.register_buffer(&buffer, cx)?;
7249                    }
7250                }
7251            }
7252
7253            Ok(())
7254        })?
7255    }
7256
7257    async fn handle_update_diff_base(
7258        this: Model<Self>,
7259        envelope: TypedEnvelope<proto::UpdateDiffBase>,
7260        _: Arc<Client>,
7261        mut cx: AsyncAppContext,
7262    ) -> Result<()> {
7263        this.update(&mut cx, |this, cx| {
7264            let buffer_id = envelope.payload.buffer_id;
7265            let diff_base = envelope.payload.diff_base;
7266            if let Some(buffer) = this
7267                .opened_buffers
7268                .get_mut(&buffer_id)
7269                .and_then(|b| b.upgrade())
7270                .or_else(|| {
7271                    this.incomplete_remote_buffers
7272                        .get(&buffer_id)
7273                        .cloned()
7274                        .flatten()
7275                })
7276            {
7277                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7278            }
7279            Ok(())
7280        })?
7281    }
7282
7283    async fn handle_update_buffer_file(
7284        this: Model<Self>,
7285        envelope: TypedEnvelope<proto::UpdateBufferFile>,
7286        _: Arc<Client>,
7287        mut cx: AsyncAppContext,
7288    ) -> Result<()> {
7289        let buffer_id = envelope.payload.buffer_id;
7290
7291        this.update(&mut cx, |this, cx| {
7292            let payload = envelope.payload.clone();
7293            if let Some(buffer) = this
7294                .opened_buffers
7295                .get(&buffer_id)
7296                .and_then(|b| b.upgrade())
7297                .or_else(|| {
7298                    this.incomplete_remote_buffers
7299                        .get(&buffer_id)
7300                        .cloned()
7301                        .flatten()
7302                })
7303            {
7304                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7305                let worktree = this
7306                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7307                    .ok_or_else(|| anyhow!("no such worktree"))?;
7308                let file = File::from_proto(file, worktree, cx)?;
7309                buffer.update(cx, |buffer, cx| {
7310                    buffer.file_updated(Arc::new(file), cx);
7311                });
7312                this.detect_language_for_buffer(&buffer, cx);
7313            }
7314            Ok(())
7315        })?
7316    }
7317
7318    async fn handle_save_buffer(
7319        this: Model<Self>,
7320        envelope: TypedEnvelope<proto::SaveBuffer>,
7321        _: Arc<Client>,
7322        mut cx: AsyncAppContext,
7323    ) -> Result<proto::BufferSaved> {
7324        let buffer_id = envelope.payload.buffer_id;
7325        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7326            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7327            let buffer = this
7328                .opened_buffers
7329                .get(&buffer_id)
7330                .and_then(|buffer| buffer.upgrade())
7331                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7332            anyhow::Ok((project_id, buffer))
7333        })??;
7334        buffer
7335            .update(&mut cx, |buffer, _| {
7336                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7337            })?
7338            .await?;
7339        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7340
7341        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7342            .await?;
7343        Ok(buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7344            project_id,
7345            buffer_id,
7346            version: serialize_version(buffer.saved_version()),
7347            mtime: Some(buffer.saved_mtime().into()),
7348            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7349        })?)
7350    }
7351
7352    async fn handle_reload_buffers(
7353        this: Model<Self>,
7354        envelope: TypedEnvelope<proto::ReloadBuffers>,
7355        _: Arc<Client>,
7356        mut cx: AsyncAppContext,
7357    ) -> Result<proto::ReloadBuffersResponse> {
7358        let sender_id = envelope.original_sender_id()?;
7359        let reload = this.update(&mut cx, |this, cx| {
7360            let mut buffers = HashSet::default();
7361            for buffer_id in &envelope.payload.buffer_ids {
7362                buffers.insert(
7363                    this.opened_buffers
7364                        .get(buffer_id)
7365                        .and_then(|buffer| buffer.upgrade())
7366                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7367                );
7368            }
7369            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7370        })??;
7371
7372        let project_transaction = reload.await?;
7373        let project_transaction = this.update(&mut cx, |this, cx| {
7374            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7375        })?;
7376        Ok(proto::ReloadBuffersResponse {
7377            transaction: Some(project_transaction),
7378        })
7379    }
7380
7381    async fn handle_synchronize_buffers(
7382        this: Model<Self>,
7383        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7384        _: Arc<Client>,
7385        mut cx: AsyncAppContext,
7386    ) -> Result<proto::SynchronizeBuffersResponse> {
7387        let project_id = envelope.payload.project_id;
7388        let mut response = proto::SynchronizeBuffersResponse {
7389            buffers: Default::default(),
7390        };
7391
7392        this.update(&mut cx, |this, cx| {
7393            let Some(guest_id) = envelope.original_sender_id else {
7394                error!("missing original_sender_id on SynchronizeBuffers request");
7395                return;
7396            };
7397
7398            this.shared_buffers.entry(guest_id).or_default().clear();
7399            for buffer in envelope.payload.buffers {
7400                let buffer_id = buffer.id;
7401                let remote_version = language::proto::deserialize_version(&buffer.version);
7402                if let Some(buffer) = this.buffer_for_id(buffer_id) {
7403                    this.shared_buffers
7404                        .entry(guest_id)
7405                        .or_default()
7406                        .insert(buffer_id);
7407
7408                    let buffer = buffer.read(cx);
7409                    response.buffers.push(proto::BufferVersion {
7410                        id: buffer_id,
7411                        version: language::proto::serialize_version(&buffer.version),
7412                    });
7413
7414                    let operations = buffer.serialize_ops(Some(remote_version), cx);
7415                    let client = this.client.clone();
7416                    if let Some(file) = buffer.file() {
7417                        client
7418                            .send(proto::UpdateBufferFile {
7419                                project_id,
7420                                buffer_id: buffer_id as u64,
7421                                file: Some(file.to_proto()),
7422                            })
7423                            .log_err();
7424                    }
7425
7426                    client
7427                        .send(proto::UpdateDiffBase {
7428                            project_id,
7429                            buffer_id: buffer_id as u64,
7430                            diff_base: buffer.diff_base().map(Into::into),
7431                        })
7432                        .log_err();
7433
7434                    client
7435                        .send(proto::BufferReloaded {
7436                            project_id,
7437                            buffer_id,
7438                            version: language::proto::serialize_version(buffer.saved_version()),
7439                            mtime: Some(buffer.saved_mtime().into()),
7440                            fingerprint: language::proto::serialize_fingerprint(
7441                                buffer.saved_version_fingerprint(),
7442                            ),
7443                            line_ending: language::proto::serialize_line_ending(
7444                                buffer.line_ending(),
7445                            ) as i32,
7446                        })
7447                        .log_err();
7448
7449                    cx.background_executor()
7450                        .spawn(
7451                            async move {
7452                                let operations = operations.await;
7453                                for chunk in split_operations(operations) {
7454                                    client
7455                                        .request(proto::UpdateBuffer {
7456                                            project_id,
7457                                            buffer_id,
7458                                            operations: chunk,
7459                                        })
7460                                        .await?;
7461                                }
7462                                anyhow::Ok(())
7463                            }
7464                            .log_err(),
7465                        )
7466                        .detach();
7467                }
7468            }
7469        })?;
7470
7471        Ok(response)
7472    }
7473
7474    async fn handle_format_buffers(
7475        this: Model<Self>,
7476        envelope: TypedEnvelope<proto::FormatBuffers>,
7477        _: Arc<Client>,
7478        mut cx: AsyncAppContext,
7479    ) -> Result<proto::FormatBuffersResponse> {
7480        let sender_id = envelope.original_sender_id()?;
7481        let format = this.update(&mut cx, |this, cx| {
7482            let mut buffers = HashSet::default();
7483            for buffer_id in &envelope.payload.buffer_ids {
7484                buffers.insert(
7485                    this.opened_buffers
7486                        .get(buffer_id)
7487                        .and_then(|buffer| buffer.upgrade())
7488                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7489                );
7490            }
7491            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7492            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7493        })??;
7494
7495        let project_transaction = format.await?;
7496        let project_transaction = this.update(&mut cx, |this, cx| {
7497            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7498        })?;
7499        Ok(proto::FormatBuffersResponse {
7500            transaction: Some(project_transaction),
7501        })
7502    }
7503
7504    async fn handle_apply_additional_edits_for_completion(
7505        this: Model<Self>,
7506        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7507        _: Arc<Client>,
7508        mut cx: AsyncAppContext,
7509    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7510        let (buffer, completion) = this.update(&mut cx, |this, cx| {
7511            let buffer = this
7512                .opened_buffers
7513                .get(&envelope.payload.buffer_id)
7514                .and_then(|buffer| buffer.upgrade())
7515                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7516            let language = buffer.read(cx).language();
7517            let completion = language::proto::deserialize_completion(
7518                envelope
7519                    .payload
7520                    .completion
7521                    .ok_or_else(|| anyhow!("invalid completion"))?,
7522                language.cloned(),
7523            );
7524            Ok::<_, anyhow::Error>((buffer, completion))
7525        })??;
7526
7527        let completion = completion.await?;
7528
7529        let apply_additional_edits = this.update(&mut cx, |this, cx| {
7530            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7531        })?;
7532
7533        Ok(proto::ApplyCompletionAdditionalEditsResponse {
7534            transaction: apply_additional_edits
7535                .await?
7536                .as_ref()
7537                .map(language::proto::serialize_transaction),
7538        })
7539    }
7540
7541    async fn handle_apply_code_action(
7542        this: Model<Self>,
7543        envelope: TypedEnvelope<proto::ApplyCodeAction>,
7544        _: Arc<Client>,
7545        mut cx: AsyncAppContext,
7546    ) -> Result<proto::ApplyCodeActionResponse> {
7547        let sender_id = envelope.original_sender_id()?;
7548        let action = language::proto::deserialize_code_action(
7549            envelope
7550                .payload
7551                .action
7552                .ok_or_else(|| anyhow!("invalid action"))?,
7553        )?;
7554        let apply_code_action = this.update(&mut cx, |this, cx| {
7555            let buffer = this
7556                .opened_buffers
7557                .get(&envelope.payload.buffer_id)
7558                .and_then(|buffer| buffer.upgrade())
7559                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7560            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7561        })??;
7562
7563        let project_transaction = apply_code_action.await?;
7564        let project_transaction = this.update(&mut cx, |this, cx| {
7565            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7566        })?;
7567        Ok(proto::ApplyCodeActionResponse {
7568            transaction: Some(project_transaction),
7569        })
7570    }
7571
7572    async fn handle_on_type_formatting(
7573        this: Model<Self>,
7574        envelope: TypedEnvelope<proto::OnTypeFormatting>,
7575        _: Arc<Client>,
7576        mut cx: AsyncAppContext,
7577    ) -> Result<proto::OnTypeFormattingResponse> {
7578        let on_type_formatting = this.update(&mut cx, |this, cx| {
7579            let buffer = this
7580                .opened_buffers
7581                .get(&envelope.payload.buffer_id)
7582                .and_then(|buffer| buffer.upgrade())
7583                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7584            let position = envelope
7585                .payload
7586                .position
7587                .and_then(deserialize_anchor)
7588                .ok_or_else(|| anyhow!("invalid position"))?;
7589            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7590                buffer,
7591                position,
7592                envelope.payload.trigger.clone(),
7593                cx,
7594            ))
7595        })??;
7596
7597        let transaction = on_type_formatting
7598            .await?
7599            .as_ref()
7600            .map(language::proto::serialize_transaction);
7601        Ok(proto::OnTypeFormattingResponse { transaction })
7602    }
7603
7604    async fn handle_inlay_hints(
7605        this: Model<Self>,
7606        envelope: TypedEnvelope<proto::InlayHints>,
7607        _: Arc<Client>,
7608        mut cx: AsyncAppContext,
7609    ) -> Result<proto::InlayHintsResponse> {
7610        let sender_id = envelope.original_sender_id()?;
7611        let buffer = this.update(&mut cx, |this, _| {
7612            this.opened_buffers
7613                .get(&envelope.payload.buffer_id)
7614                .and_then(|buffer| buffer.upgrade())
7615                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7616        })??;
7617        let buffer_version = deserialize_version(&envelope.payload.version);
7618
7619        buffer
7620            .update(&mut cx, |buffer, _| {
7621                buffer.wait_for_version(buffer_version.clone())
7622            })?
7623            .await
7624            .with_context(|| {
7625                format!(
7626                    "waiting for version {:?} for buffer {}",
7627                    buffer_version,
7628                    buffer.entity_id()
7629                )
7630            })?;
7631
7632        let start = envelope
7633            .payload
7634            .start
7635            .and_then(deserialize_anchor)
7636            .context("missing range start")?;
7637        let end = envelope
7638            .payload
7639            .end
7640            .and_then(deserialize_anchor)
7641            .context("missing range end")?;
7642        let buffer_hints = this
7643            .update(&mut cx, |project, cx| {
7644                project.inlay_hints(buffer, start..end, cx)
7645            })?
7646            .await
7647            .context("inlay hints fetch")?;
7648
7649        Ok(this.update(&mut cx, |project, cx| {
7650            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7651        })?)
7652    }
7653
7654    async fn handle_resolve_inlay_hint(
7655        this: Model<Self>,
7656        envelope: TypedEnvelope<proto::ResolveInlayHint>,
7657        _: Arc<Client>,
7658        mut cx: AsyncAppContext,
7659    ) -> Result<proto::ResolveInlayHintResponse> {
7660        let proto_hint = envelope
7661            .payload
7662            .hint
7663            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7664        let hint = InlayHints::proto_to_project_hint(proto_hint)
7665            .context("resolved proto inlay hint conversion")?;
7666        let buffer = this.update(&mut cx, |this, _cx| {
7667            this.opened_buffers
7668                .get(&envelope.payload.buffer_id)
7669                .and_then(|buffer| buffer.upgrade())
7670                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7671        })??;
7672        let response_hint = this
7673            .update(&mut cx, |project, cx| {
7674                project.resolve_inlay_hint(
7675                    hint,
7676                    buffer,
7677                    LanguageServerId(envelope.payload.language_server_id as usize),
7678                    cx,
7679                )
7680            })?
7681            .await
7682            .context("inlay hints fetch")?;
7683        Ok(proto::ResolveInlayHintResponse {
7684            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7685        })
7686    }
7687
7688    async fn handle_refresh_inlay_hints(
7689        this: Model<Self>,
7690        _: TypedEnvelope<proto::RefreshInlayHints>,
7691        _: Arc<Client>,
7692        mut cx: AsyncAppContext,
7693    ) -> Result<proto::Ack> {
7694        this.update(&mut cx, |_, cx| {
7695            cx.emit(Event::RefreshInlayHints);
7696        })?;
7697        Ok(proto::Ack {})
7698    }
7699
7700    async fn handle_lsp_command<T: LspCommand>(
7701        this: Model<Self>,
7702        envelope: TypedEnvelope<T::ProtoRequest>,
7703        _: Arc<Client>,
7704        mut cx: AsyncAppContext,
7705    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7706    where
7707        <T::LspRequest as lsp::request::Request>::Params: Send,
7708        <T::LspRequest as lsp::request::Request>::Result: Send,
7709    {
7710        let sender_id = envelope.original_sender_id()?;
7711        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
7712        let buffer_handle = this.update(&mut cx, |this, _cx| {
7713            this.opened_buffers
7714                .get(&buffer_id)
7715                .and_then(|buffer| buffer.upgrade())
7716                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7717        })??;
7718        let request = T::from_proto(
7719            envelope.payload,
7720            this.clone(),
7721            buffer_handle.clone(),
7722            cx.clone(),
7723        )
7724        .await?;
7725        let buffer_version = buffer_handle.update(&mut cx, |buffer, _| buffer.version())?;
7726        let response = this
7727            .update(&mut cx, |this, cx| {
7728                this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
7729            })?
7730            .await?;
7731        this.update(&mut cx, |this, cx| {
7732            Ok(T::response_to_proto(
7733                response,
7734                this,
7735                sender_id,
7736                &buffer_version,
7737                cx,
7738            ))
7739        })?
7740    }
7741
7742    async fn handle_get_project_symbols(
7743        this: Model<Self>,
7744        envelope: TypedEnvelope<proto::GetProjectSymbols>,
7745        _: Arc<Client>,
7746        mut cx: AsyncAppContext,
7747    ) -> Result<proto::GetProjectSymbolsResponse> {
7748        let symbols = this
7749            .update(&mut cx, |this, cx| {
7750                this.symbols(&envelope.payload.query, cx)
7751            })?
7752            .await?;
7753
7754        Ok(proto::GetProjectSymbolsResponse {
7755            symbols: symbols.iter().map(serialize_symbol).collect(),
7756        })
7757    }
7758
7759    async fn handle_search_project(
7760        this: Model<Self>,
7761        envelope: TypedEnvelope<proto::SearchProject>,
7762        _: Arc<Client>,
7763        mut cx: AsyncAppContext,
7764    ) -> Result<proto::SearchProjectResponse> {
7765        let peer_id = envelope.original_sender_id()?;
7766        let query = SearchQuery::from_proto(envelope.payload)?;
7767        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
7768
7769        cx.spawn(move |mut cx| async move {
7770            let mut locations = Vec::new();
7771            while let Some((buffer, ranges)) = result.next().await {
7772                for range in ranges {
7773                    let start = serialize_anchor(&range.start);
7774                    let end = serialize_anchor(&range.end);
7775                    let buffer_id = this.update(&mut cx, |this, cx| {
7776                        this.create_buffer_for_peer(&buffer, peer_id, cx)
7777                    })?;
7778                    locations.push(proto::Location {
7779                        buffer_id,
7780                        start: Some(start),
7781                        end: Some(end),
7782                    });
7783                }
7784            }
7785            Ok(proto::SearchProjectResponse { locations })
7786        })
7787        .await
7788    }
7789
7790    async fn handle_open_buffer_for_symbol(
7791        this: Model<Self>,
7792        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7793        _: Arc<Client>,
7794        mut cx: AsyncAppContext,
7795    ) -> Result<proto::OpenBufferForSymbolResponse> {
7796        let peer_id = envelope.original_sender_id()?;
7797        let symbol = envelope
7798            .payload
7799            .symbol
7800            .ok_or_else(|| anyhow!("invalid symbol"))?;
7801        let symbol = this
7802            .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
7803            .await?;
7804        let symbol = this.update(&mut cx, |this, _| {
7805            let signature = this.symbol_signature(&symbol.path);
7806            if signature == symbol.signature {
7807                Ok(symbol)
7808            } else {
7809                Err(anyhow!("invalid symbol signature"))
7810            }
7811        })??;
7812        let buffer = this
7813            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
7814            .await?;
7815
7816        Ok(proto::OpenBufferForSymbolResponse {
7817            buffer_id: this.update(&mut cx, |this, cx| {
7818                this.create_buffer_for_peer(&buffer, peer_id, cx)
7819            })?,
7820        })
7821    }
7822
7823    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7824        let mut hasher = Sha256::new();
7825        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7826        hasher.update(project_path.path.to_string_lossy().as_bytes());
7827        hasher.update(self.nonce.to_be_bytes());
7828        hasher.finalize().as_slice().try_into().unwrap()
7829    }
7830
7831    async fn handle_open_buffer_by_id(
7832        this: Model<Self>,
7833        envelope: TypedEnvelope<proto::OpenBufferById>,
7834        _: Arc<Client>,
7835        mut cx: AsyncAppContext,
7836    ) -> Result<proto::OpenBufferResponse> {
7837        let peer_id = envelope.original_sender_id()?;
7838        let buffer = this
7839            .update(&mut cx, |this, cx| {
7840                this.open_buffer_by_id(envelope.payload.id, cx)
7841            })?
7842            .await?;
7843        this.update(&mut cx, |this, cx| {
7844            Ok(proto::OpenBufferResponse {
7845                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7846            })
7847        })?
7848    }
7849
7850    async fn handle_open_buffer_by_path(
7851        this: Model<Self>,
7852        envelope: TypedEnvelope<proto::OpenBufferByPath>,
7853        _: Arc<Client>,
7854        mut cx: AsyncAppContext,
7855    ) -> Result<proto::OpenBufferResponse> {
7856        let peer_id = envelope.original_sender_id()?;
7857        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7858        let open_buffer = this.update(&mut cx, |this, cx| {
7859            this.open_buffer(
7860                ProjectPath {
7861                    worktree_id,
7862                    path: PathBuf::from(envelope.payload.path).into(),
7863                },
7864                cx,
7865            )
7866        })?;
7867
7868        let buffer = open_buffer.await?;
7869        this.update(&mut cx, |this, cx| {
7870            Ok(proto::OpenBufferResponse {
7871                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7872            })
7873        })?
7874    }
7875
7876    fn serialize_project_transaction_for_peer(
7877        &mut self,
7878        project_transaction: ProjectTransaction,
7879        peer_id: proto::PeerId,
7880        cx: &mut AppContext,
7881    ) -> proto::ProjectTransaction {
7882        let mut serialized_transaction = proto::ProjectTransaction {
7883            buffer_ids: Default::default(),
7884            transactions: Default::default(),
7885        };
7886        for (buffer, transaction) in project_transaction.0 {
7887            serialized_transaction
7888                .buffer_ids
7889                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
7890            serialized_transaction
7891                .transactions
7892                .push(language::proto::serialize_transaction(&transaction));
7893        }
7894        serialized_transaction
7895    }
7896
7897    fn deserialize_project_transaction(
7898        &mut self,
7899        message: proto::ProjectTransaction,
7900        push_to_history: bool,
7901        cx: &mut ModelContext<Self>,
7902    ) -> Task<Result<ProjectTransaction>> {
7903        cx.spawn(move |this, mut cx| async move {
7904            let mut project_transaction = ProjectTransaction::default();
7905            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
7906            {
7907                let buffer = this
7908                    .update(&mut cx, |this, cx| {
7909                        this.wait_for_remote_buffer(buffer_id, cx)
7910                    })?
7911                    .await?;
7912                let transaction = language::proto::deserialize_transaction(transaction)?;
7913                project_transaction.0.insert(buffer, transaction);
7914            }
7915
7916            for (buffer, transaction) in &project_transaction.0 {
7917                buffer
7918                    .update(&mut cx, |buffer, _| {
7919                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7920                    })?
7921                    .await?;
7922
7923                if push_to_history {
7924                    buffer.update(&mut cx, |buffer, _| {
7925                        buffer.push_transaction(transaction.clone(), Instant::now());
7926                    })?;
7927                }
7928            }
7929
7930            Ok(project_transaction)
7931        })
7932    }
7933
7934    fn create_buffer_for_peer(
7935        &mut self,
7936        buffer: &Model<Buffer>,
7937        peer_id: proto::PeerId,
7938        cx: &mut AppContext,
7939    ) -> u64 {
7940        let buffer_id = buffer.read(cx).remote_id();
7941        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7942            updates_tx
7943                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7944                .ok();
7945        }
7946        buffer_id
7947    }
7948
7949    fn wait_for_remote_buffer(
7950        &mut self,
7951        id: u64,
7952        cx: &mut ModelContext<Self>,
7953    ) -> Task<Result<Model<Buffer>>> {
7954        let mut opened_buffer_rx = self.opened_buffer.1.clone();
7955
7956        cx.spawn(move |this, mut cx| async move {
7957            let buffer = loop {
7958                let Some(this) = this.upgrade() else {
7959                    return Err(anyhow!("project dropped"));
7960                };
7961
7962                let buffer = this.update(&mut cx, |this, _cx| {
7963                    this.opened_buffers
7964                        .get(&id)
7965                        .and_then(|buffer| buffer.upgrade())
7966                })?;
7967
7968                if let Some(buffer) = buffer {
7969                    break buffer;
7970                } else if this.update(&mut cx, |this, _| this.is_disconnected())? {
7971                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
7972                }
7973
7974                this.update(&mut cx, |this, _| {
7975                    this.incomplete_remote_buffers.entry(id).or_default();
7976                })?;
7977                drop(this);
7978
7979                opened_buffer_rx
7980                    .next()
7981                    .await
7982                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7983            };
7984
7985            Ok(buffer)
7986        })
7987    }
7988
7989    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7990        let project_id = match self.client_state.as_ref() {
7991            Some(ProjectClientState::Remote {
7992                sharing_has_stopped,
7993                remote_id,
7994                ..
7995            }) => {
7996                if *sharing_has_stopped {
7997                    return Task::ready(Err(anyhow!(
7998                        "can't synchronize remote buffers on a readonly project"
7999                    )));
8000                } else {
8001                    *remote_id
8002                }
8003            }
8004            Some(ProjectClientState::Local { .. }) | None => {
8005                return Task::ready(Err(anyhow!(
8006                    "can't synchronize remote buffers on a local project"
8007                )))
8008            }
8009        };
8010
8011        let client = self.client.clone();
8012        cx.spawn(move |this, mut cx| async move {
8013            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
8014                let buffers = this
8015                    .opened_buffers
8016                    .iter()
8017                    .filter_map(|(id, buffer)| {
8018                        let buffer = buffer.upgrade()?;
8019                        Some(proto::BufferVersion {
8020                            id: *id,
8021                            version: language::proto::serialize_version(&buffer.read(cx).version),
8022                        })
8023                    })
8024                    .collect();
8025                let incomplete_buffer_ids = this
8026                    .incomplete_remote_buffers
8027                    .keys()
8028                    .copied()
8029                    .collect::<Vec<_>>();
8030
8031                (buffers, incomplete_buffer_ids)
8032            })?;
8033            let response = client
8034                .request(proto::SynchronizeBuffers {
8035                    project_id,
8036                    buffers,
8037                })
8038                .await?;
8039
8040            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8041                response
8042                    .buffers
8043                    .into_iter()
8044                    .map(|buffer| {
8045                        let client = client.clone();
8046                        let buffer_id = buffer.id;
8047                        let remote_version = language::proto::deserialize_version(&buffer.version);
8048                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
8049                            let operations =
8050                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
8051                            cx.background_executor().spawn(async move {
8052                                let operations = operations.await;
8053                                for chunk in split_operations(operations) {
8054                                    client
8055                                        .request(proto::UpdateBuffer {
8056                                            project_id,
8057                                            buffer_id,
8058                                            operations: chunk,
8059                                        })
8060                                        .await?;
8061                                }
8062                                anyhow::Ok(())
8063                            })
8064                        } else {
8065                            Task::ready(Ok(()))
8066                        }
8067                    })
8068                    .collect::<Vec<_>>()
8069            })?;
8070
8071            // Any incomplete buffers have open requests waiting. Request that the host sends
8072            // creates these buffers for us again to unblock any waiting futures.
8073            for id in incomplete_buffer_ids {
8074                cx.background_executor()
8075                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
8076                    .detach();
8077            }
8078
8079            futures::future::join_all(send_updates_for_buffers)
8080                .await
8081                .into_iter()
8082                .collect()
8083        })
8084    }
8085
8086    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8087        self.worktrees()
8088            .map(|worktree| {
8089                let worktree = worktree.read(cx);
8090                proto::WorktreeMetadata {
8091                    id: worktree.id().to_proto(),
8092                    root_name: worktree.root_name().into(),
8093                    visible: worktree.is_visible(),
8094                    abs_path: worktree.abs_path().to_string_lossy().into(),
8095                }
8096            })
8097            .collect()
8098    }
8099
8100    fn set_worktrees_from_proto(
8101        &mut self,
8102        worktrees: Vec<proto::WorktreeMetadata>,
8103        cx: &mut ModelContext<Project>,
8104    ) -> Result<()> {
8105        let replica_id = self.replica_id();
8106        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8107
8108        let mut old_worktrees_by_id = self
8109            .worktrees
8110            .drain(..)
8111            .filter_map(|worktree| {
8112                let worktree = worktree.upgrade()?;
8113                Some((worktree.read(cx).id(), worktree))
8114            })
8115            .collect::<HashMap<_, _>>();
8116
8117        for worktree in worktrees {
8118            if let Some(old_worktree) =
8119                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8120            {
8121                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8122            } else {
8123                let worktree =
8124                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8125                let _ = self.add_worktree(&worktree, cx);
8126            }
8127        }
8128
8129        self.metadata_changed(cx);
8130        for id in old_worktrees_by_id.keys() {
8131            cx.emit(Event::WorktreeRemoved(*id));
8132        }
8133
8134        Ok(())
8135    }
8136
8137    fn set_collaborators_from_proto(
8138        &mut self,
8139        messages: Vec<proto::Collaborator>,
8140        cx: &mut ModelContext<Self>,
8141    ) -> Result<()> {
8142        let mut collaborators = HashMap::default();
8143        for message in messages {
8144            let collaborator = Collaborator::from_proto(message)?;
8145            collaborators.insert(collaborator.peer_id, collaborator);
8146        }
8147        for old_peer_id in self.collaborators.keys() {
8148            if !collaborators.contains_key(old_peer_id) {
8149                cx.emit(Event::CollaboratorLeft(*old_peer_id));
8150            }
8151        }
8152        self.collaborators = collaborators;
8153        Ok(())
8154    }
8155
8156    fn deserialize_symbol(
8157        &self,
8158        serialized_symbol: proto::Symbol,
8159    ) -> impl Future<Output = Result<Symbol>> {
8160        let languages = self.languages.clone();
8161        async move {
8162            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8163            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8164            let start = serialized_symbol
8165                .start
8166                .ok_or_else(|| anyhow!("invalid start"))?;
8167            let end = serialized_symbol
8168                .end
8169                .ok_or_else(|| anyhow!("invalid end"))?;
8170            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8171            let path = ProjectPath {
8172                worktree_id,
8173                path: PathBuf::from(serialized_symbol.path).into(),
8174            };
8175            let language = languages
8176                .language_for_file(&path.path, None)
8177                .await
8178                .log_err();
8179            Ok(Symbol {
8180                language_server_name: LanguageServerName(
8181                    serialized_symbol.language_server_name.into(),
8182                ),
8183                source_worktree_id,
8184                path,
8185                label: {
8186                    match language {
8187                        Some(language) => {
8188                            language
8189                                .label_for_symbol(&serialized_symbol.name, kind)
8190                                .await
8191                        }
8192                        None => None,
8193                    }
8194                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8195                },
8196
8197                name: serialized_symbol.name,
8198                range: Unclipped(PointUtf16::new(start.row, start.column))
8199                    ..Unclipped(PointUtf16::new(end.row, end.column)),
8200                kind,
8201                signature: serialized_symbol
8202                    .signature
8203                    .try_into()
8204                    .map_err(|_| anyhow!("invalid signature"))?,
8205            })
8206        }
8207    }
8208
8209    async fn handle_buffer_saved(
8210        this: Model<Self>,
8211        envelope: TypedEnvelope<proto::BufferSaved>,
8212        _: Arc<Client>,
8213        mut cx: AsyncAppContext,
8214    ) -> Result<()> {
8215        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8216        let version = deserialize_version(&envelope.payload.version);
8217        let mtime = envelope
8218            .payload
8219            .mtime
8220            .ok_or_else(|| anyhow!("missing mtime"))?
8221            .into();
8222
8223        this.update(&mut cx, |this, cx| {
8224            let buffer = this
8225                .opened_buffers
8226                .get(&envelope.payload.buffer_id)
8227                .and_then(|buffer| buffer.upgrade())
8228                .or_else(|| {
8229                    this.incomplete_remote_buffers
8230                        .get(&envelope.payload.buffer_id)
8231                        .and_then(|b| b.clone())
8232                });
8233            if let Some(buffer) = buffer {
8234                buffer.update(cx, |buffer, cx| {
8235                    buffer.did_save(version, fingerprint, mtime, cx);
8236                });
8237            }
8238            Ok(())
8239        })?
8240    }
8241
8242    async fn handle_buffer_reloaded(
8243        this: Model<Self>,
8244        envelope: TypedEnvelope<proto::BufferReloaded>,
8245        _: Arc<Client>,
8246        mut cx: AsyncAppContext,
8247    ) -> Result<()> {
8248        let payload = envelope.payload;
8249        let version = deserialize_version(&payload.version);
8250        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8251        let line_ending = deserialize_line_ending(
8252            proto::LineEnding::from_i32(payload.line_ending)
8253                .ok_or_else(|| anyhow!("missing line ending"))?,
8254        );
8255        let mtime = payload
8256            .mtime
8257            .ok_or_else(|| anyhow!("missing mtime"))?
8258            .into();
8259        this.update(&mut cx, |this, cx| {
8260            let buffer = this
8261                .opened_buffers
8262                .get(&payload.buffer_id)
8263                .and_then(|buffer| buffer.upgrade())
8264                .or_else(|| {
8265                    this.incomplete_remote_buffers
8266                        .get(&payload.buffer_id)
8267                        .cloned()
8268                        .flatten()
8269                });
8270            if let Some(buffer) = buffer {
8271                buffer.update(cx, |buffer, cx| {
8272                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8273                });
8274            }
8275            Ok(())
8276        })?
8277    }
8278
8279    #[allow(clippy::type_complexity)]
8280    fn edits_from_lsp(
8281        &mut self,
8282        buffer: &Model<Buffer>,
8283        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8284        server_id: LanguageServerId,
8285        version: Option<i32>,
8286        cx: &mut ModelContext<Self>,
8287    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8288        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8289        cx.background_executor().spawn(async move {
8290            let snapshot = snapshot?;
8291            let mut lsp_edits = lsp_edits
8292                .into_iter()
8293                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8294                .collect::<Vec<_>>();
8295            lsp_edits.sort_by_key(|(range, _)| range.start);
8296
8297            let mut lsp_edits = lsp_edits.into_iter().peekable();
8298            let mut edits = Vec::new();
8299            while let Some((range, mut new_text)) = lsp_edits.next() {
8300                // Clip invalid ranges provided by the language server.
8301                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8302                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
8303
8304                // Combine any LSP edits that are adjacent.
8305                //
8306                // Also, combine LSP edits that are separated from each other by only
8307                // a newline. This is important because for some code actions,
8308                // Rust-analyzer rewrites the entire buffer via a series of edits that
8309                // are separated by unchanged newline characters.
8310                //
8311                // In order for the diffing logic below to work properly, any edits that
8312                // cancel each other out must be combined into one.
8313                while let Some((next_range, next_text)) = lsp_edits.peek() {
8314                    if next_range.start.0 > range.end {
8315                        if next_range.start.0.row > range.end.row + 1
8316                            || next_range.start.0.column > 0
8317                            || snapshot.clip_point_utf16(
8318                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8319                                Bias::Left,
8320                            ) > range.end
8321                        {
8322                            break;
8323                        }
8324                        new_text.push('\n');
8325                    }
8326                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8327                    new_text.push_str(next_text);
8328                    lsp_edits.next();
8329                }
8330
8331                // For multiline edits, perform a diff of the old and new text so that
8332                // we can identify the changes more precisely, preserving the locations
8333                // of any anchors positioned in the unchanged regions.
8334                if range.end.row > range.start.row {
8335                    let mut offset = range.start.to_offset(&snapshot);
8336                    let old_text = snapshot.text_for_range(range).collect::<String>();
8337
8338                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8339                    let mut moved_since_edit = true;
8340                    for change in diff.iter_all_changes() {
8341                        let tag = change.tag();
8342                        let value = change.value();
8343                        match tag {
8344                            ChangeTag::Equal => {
8345                                offset += value.len();
8346                                moved_since_edit = true;
8347                            }
8348                            ChangeTag::Delete => {
8349                                let start = snapshot.anchor_after(offset);
8350                                let end = snapshot.anchor_before(offset + value.len());
8351                                if moved_since_edit {
8352                                    edits.push((start..end, String::new()));
8353                                } else {
8354                                    edits.last_mut().unwrap().0.end = end;
8355                                }
8356                                offset += value.len();
8357                                moved_since_edit = false;
8358                            }
8359                            ChangeTag::Insert => {
8360                                if moved_since_edit {
8361                                    let anchor = snapshot.anchor_after(offset);
8362                                    edits.push((anchor..anchor, value.to_string()));
8363                                } else {
8364                                    edits.last_mut().unwrap().1.push_str(value);
8365                                }
8366                                moved_since_edit = false;
8367                            }
8368                        }
8369                    }
8370                } else if range.end == range.start {
8371                    let anchor = snapshot.anchor_after(range.start);
8372                    edits.push((anchor..anchor, new_text));
8373                } else {
8374                    let edit_start = snapshot.anchor_after(range.start);
8375                    let edit_end = snapshot.anchor_before(range.end);
8376                    edits.push((edit_start..edit_end, new_text));
8377                }
8378            }
8379
8380            Ok(edits)
8381        })
8382    }
8383
8384    fn buffer_snapshot_for_lsp_version(
8385        &mut self,
8386        buffer: &Model<Buffer>,
8387        server_id: LanguageServerId,
8388        version: Option<i32>,
8389        cx: &AppContext,
8390    ) -> Result<TextBufferSnapshot> {
8391        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8392
8393        if let Some(version) = version {
8394            let buffer_id = buffer.read(cx).remote_id();
8395            let snapshots = self
8396                .buffer_snapshots
8397                .get_mut(&buffer_id)
8398                .and_then(|m| m.get_mut(&server_id))
8399                .ok_or_else(|| {
8400                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
8401                })?;
8402
8403            let found_snapshot = snapshots
8404                .binary_search_by_key(&version, |e| e.version)
8405                .map(|ix| snapshots[ix].snapshot.clone())
8406                .map_err(|_| {
8407                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
8408                })?;
8409
8410            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
8411            Ok(found_snapshot)
8412        } else {
8413            Ok((buffer.read(cx)).text_snapshot())
8414        }
8415    }
8416
8417    pub fn language_servers(
8418        &self,
8419    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
8420        self.language_server_ids
8421            .iter()
8422            .map(|((worktree_id, server_name), server_id)| {
8423                (*server_id, server_name.clone(), *worktree_id)
8424            })
8425    }
8426
8427    pub fn supplementary_language_servers(
8428        &self,
8429    ) -> impl '_
8430           + Iterator<
8431        Item = (
8432            &LanguageServerId,
8433            &(LanguageServerName, Arc<LanguageServer>),
8434        ),
8435    > {
8436        self.supplementary_language_servers.iter()
8437    }
8438
8439    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8440        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
8441            Some(server.clone())
8442        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
8443            Some(Arc::clone(server))
8444        } else {
8445            None
8446        }
8447    }
8448
8449    pub fn language_servers_for_buffer(
8450        &self,
8451        buffer: &Buffer,
8452        cx: &AppContext,
8453    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8454        self.language_server_ids_for_buffer(buffer, cx)
8455            .into_iter()
8456            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
8457                LanguageServerState::Running {
8458                    adapter, server, ..
8459                } => Some((adapter, server)),
8460                _ => None,
8461            })
8462    }
8463
8464    fn primary_language_server_for_buffer(
8465        &self,
8466        buffer: &Buffer,
8467        cx: &AppContext,
8468    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8469        self.language_servers_for_buffer(buffer, cx).next()
8470    }
8471
8472    pub fn language_server_for_buffer(
8473        &self,
8474        buffer: &Buffer,
8475        server_id: LanguageServerId,
8476        cx: &AppContext,
8477    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8478        self.language_servers_for_buffer(buffer, cx)
8479            .find(|(_, s)| s.server_id() == server_id)
8480    }
8481
8482    fn language_server_ids_for_buffer(
8483        &self,
8484        buffer: &Buffer,
8485        cx: &AppContext,
8486    ) -> Vec<LanguageServerId> {
8487        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8488            let worktree_id = file.worktree_id(cx);
8489            language
8490                .lsp_adapters()
8491                .iter()
8492                .flat_map(|adapter| {
8493                    let key = (worktree_id, adapter.name.clone());
8494                    self.language_server_ids.get(&key).copied()
8495                })
8496                .collect()
8497        } else {
8498            Vec::new()
8499        }
8500    }
8501}
8502
8503fn subscribe_for_copilot_events(
8504    copilot: &Model<Copilot>,
8505    cx: &mut ModelContext<'_, Project>,
8506) -> gpui::Subscription {
8507    cx.subscribe(
8508        copilot,
8509        |project, copilot, copilot_event, cx| match copilot_event {
8510            copilot::Event::CopilotLanguageServerStarted => {
8511                match copilot.read(cx).language_server() {
8512                    Some((name, copilot_server)) => {
8513                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
8514                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
8515                            let new_server_id = copilot_server.server_id();
8516                            let weak_project = cx.weak_model();
8517                            let copilot_log_subscription = copilot_server
8518                                .on_notification::<copilot::request::LogMessage, _>(
8519                                    move |params, mut cx| {
8520                                        weak_project.update(&mut cx, |_, cx| {
8521                                            cx.emit(Event::LanguageServerLog(
8522                                                new_server_id,
8523                                                params.message,
8524                                            ));
8525                                        }).ok();
8526                                    },
8527                                );
8528                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
8529                            project.copilot_log_subscription = Some(copilot_log_subscription);
8530                            cx.emit(Event::LanguageServerAdded(new_server_id));
8531                        }
8532                    }
8533                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
8534                }
8535            }
8536        },
8537    )
8538}
8539
8540fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8541    let mut literal_end = 0;
8542    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8543        if part.contains(&['*', '?', '{', '}']) {
8544            break;
8545        } else {
8546            if i > 0 {
8547                // Acount for separator prior to this part
8548                literal_end += path::MAIN_SEPARATOR.len_utf8();
8549            }
8550            literal_end += part.len();
8551        }
8552    }
8553    &glob[..literal_end]
8554}
8555
8556impl WorktreeHandle {
8557    pub fn upgrade(&self) -> Option<Model<Worktree>> {
8558        match self {
8559            WorktreeHandle::Strong(handle) => Some(handle.clone()),
8560            WorktreeHandle::Weak(handle) => handle.upgrade(),
8561        }
8562    }
8563
8564    pub fn handle_id(&self) -> usize {
8565        match self {
8566            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
8567            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
8568        }
8569    }
8570}
8571
8572impl OpenBuffer {
8573    pub fn upgrade(&self) -> Option<Model<Buffer>> {
8574        match self {
8575            OpenBuffer::Strong(handle) => Some(handle.clone()),
8576            OpenBuffer::Weak(handle) => handle.upgrade(),
8577            OpenBuffer::Operations(_) => None,
8578        }
8579    }
8580}
8581
8582pub struct PathMatchCandidateSet {
8583    pub snapshot: Snapshot,
8584    pub include_ignored: bool,
8585    pub include_root_name: bool,
8586}
8587
8588impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
8589    type Candidates = PathMatchCandidateSetIter<'a>;
8590
8591    fn id(&self) -> usize {
8592        self.snapshot.id().to_usize()
8593    }
8594
8595    fn len(&self) -> usize {
8596        if self.include_ignored {
8597            self.snapshot.file_count()
8598        } else {
8599            self.snapshot.visible_file_count()
8600        }
8601    }
8602
8603    fn prefix(&self) -> Arc<str> {
8604        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
8605            self.snapshot.root_name().into()
8606        } else if self.include_root_name {
8607            format!("{}/", self.snapshot.root_name()).into()
8608        } else {
8609            "".into()
8610        }
8611    }
8612
8613    fn candidates(&'a self, start: usize) -> Self::Candidates {
8614        PathMatchCandidateSetIter {
8615            traversal: self.snapshot.files(self.include_ignored, start),
8616        }
8617    }
8618}
8619
8620pub struct PathMatchCandidateSetIter<'a> {
8621    traversal: Traversal<'a>,
8622}
8623
8624impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8625    type Item = fuzzy::PathMatchCandidate<'a>;
8626
8627    fn next(&mut self) -> Option<Self::Item> {
8628        self.traversal.next().map(|entry| {
8629            if let EntryKind::File(char_bag) = entry.kind {
8630                fuzzy::PathMatchCandidate {
8631                    path: &entry.path,
8632                    char_bag,
8633                }
8634            } else {
8635                unreachable!()
8636            }
8637        })
8638    }
8639}
8640
8641impl EventEmitter<Event> for Project {}
8642
8643impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8644    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8645        Self {
8646            worktree_id,
8647            path: path.as_ref().into(),
8648        }
8649    }
8650}
8651
8652impl ProjectLspAdapterDelegate {
8653    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8654        Arc::new(Self {
8655            project: cx.handle(),
8656            http_client: project.client.http_client(),
8657        })
8658    }
8659}
8660
8661impl LspAdapterDelegate for ProjectLspAdapterDelegate {
8662    fn show_notification(&self, message: &str, cx: &mut AppContext) {
8663        self.project
8664            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
8665    }
8666
8667    fn http_client(&self) -> Arc<dyn HttpClient> {
8668        self.http_client.clone()
8669    }
8670}
8671
8672fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
8673    proto::Symbol {
8674        language_server_name: symbol.language_server_name.0.to_string(),
8675        source_worktree_id: symbol.source_worktree_id.to_proto(),
8676        worktree_id: symbol.path.worktree_id.to_proto(),
8677        path: symbol.path.path.to_string_lossy().to_string(),
8678        name: symbol.name.clone(),
8679        kind: unsafe { mem::transmute(symbol.kind) },
8680        start: Some(proto::PointUtf16 {
8681            row: symbol.range.start.0.row,
8682            column: symbol.range.start.0.column,
8683        }),
8684        end: Some(proto::PointUtf16 {
8685            row: symbol.range.end.0.row,
8686            column: symbol.range.end.0.column,
8687        }),
8688        signature: symbol.signature.to_vec(),
8689    }
8690}
8691
8692fn relativize_path(base: &Path, path: &Path) -> PathBuf {
8693    let mut path_components = path.components();
8694    let mut base_components = base.components();
8695    let mut components: Vec<Component> = Vec::new();
8696    loop {
8697        match (path_components.next(), base_components.next()) {
8698            (None, None) => break,
8699            (Some(a), None) => {
8700                components.push(a);
8701                components.extend(path_components.by_ref());
8702                break;
8703            }
8704            (None, _) => components.push(Component::ParentDir),
8705            (Some(a), Some(b)) if components.is_empty() && a == b => (),
8706            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
8707            (Some(a), Some(_)) => {
8708                components.push(Component::ParentDir);
8709                for _ in base_components {
8710                    components.push(Component::ParentDir);
8711                }
8712                components.push(a);
8713                components.extend(path_components.by_ref());
8714                break;
8715            }
8716        }
8717    }
8718    components.iter().map(|c| c.as_os_str()).collect()
8719}
8720
8721impl Item for Buffer {
8722    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
8723        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
8724    }
8725
8726    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
8727        File::from_dyn(self.file()).map(|file| ProjectPath {
8728            worktree_id: file.worktree_id(cx),
8729            path: file.path().clone(),
8730        })
8731    }
8732}
8733
8734async fn wait_for_loading_buffer(
8735    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
8736) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
8737    loop {
8738        if let Some(result) = receiver.borrow().as_ref() {
8739            match result {
8740                Ok(buffer) => return Ok(buffer.to_owned()),
8741                Err(e) => return Err(e.to_owned()),
8742            }
8743        }
8744        receiver.next().await;
8745    }
8746}
8747
8748fn include_text(server: &lsp::LanguageServer) -> bool {
8749    server
8750        .capabilities()
8751        .text_document_sync
8752        .as_ref()
8753        .and_then(|sync| match sync {
8754            lsp::TextDocumentSyncCapability::Kind(_) => None,
8755            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
8756        })
8757        .and_then(|save_options| match save_options {
8758            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
8759            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
8760        })
8761        .unwrap_or(false)
8762}