project.rs

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