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