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,
  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::<lsp::notification::Progress, _>(move |params, mut cx| {
3146                if let Some(this) = this.upgrade() {
3147                    this.update(&mut cx, |this, cx| {
3148                        this.on_lsp_progress(
3149                            params,
3150                            server_id,
3151                            disk_based_diagnostics_progress_token.clone(),
3152                            cx,
3153                        );
3154                    })
3155                    .ok();
3156                }
3157            })
3158            .detach();
3159
3160        let mut initialization_options = adapter.adapter.initialization_options();
3161        match (&mut initialization_options, override_options) {
3162            (Some(initialization_options), Some(override_options)) => {
3163                merge_json_value_into(override_options, initialization_options);
3164            }
3165            (None, override_options) => initialization_options = override_options,
3166            _ => {}
3167        }
3168        let language_server = cx
3169            .update(|cx| language_server.initialize(initialization_options, cx))?
3170            .await?;
3171
3172        language_server
3173            .notify::<lsp::notification::DidChangeConfiguration>(
3174                lsp::DidChangeConfigurationParams {
3175                    settings: workspace_config,
3176                },
3177            )
3178            .ok();
3179
3180        Ok(language_server)
3181    }
3182
3183    fn insert_newly_running_language_server(
3184        &mut self,
3185        language: Arc<Language>,
3186        adapter: Arc<CachedLspAdapter>,
3187        language_server: Arc<LanguageServer>,
3188        server_id: LanguageServerId,
3189        key: (WorktreeId, LanguageServerName),
3190        cx: &mut ModelContext<Self>,
3191    ) -> Result<()> {
3192        // If the language server for this key doesn't match the server id, don't store the
3193        // server. Which will cause it to be dropped, killing the process
3194        if self
3195            .language_server_ids
3196            .get(&key)
3197            .map(|id| id != &server_id)
3198            .unwrap_or(false)
3199        {
3200            return Ok(());
3201        }
3202
3203        // Update language_servers collection with Running variant of LanguageServerState
3204        // indicating that the server is up and running and ready
3205        self.language_servers.insert(
3206            server_id,
3207            LanguageServerState::Running {
3208                adapter: adapter.clone(),
3209                language: language.clone(),
3210                watched_paths: Default::default(),
3211                server: language_server.clone(),
3212                simulate_disk_based_diagnostics_completion: None,
3213            },
3214        );
3215
3216        self.language_server_statuses.insert(
3217            server_id,
3218            LanguageServerStatus {
3219                name: language_server.name().to_string(),
3220                pending_work: Default::default(),
3221                has_pending_diagnostic_updates: false,
3222                progress_tokens: Default::default(),
3223            },
3224        );
3225
3226        cx.emit(Event::LanguageServerAdded(server_id));
3227
3228        if let Some(project_id) = self.remote_id() {
3229            self.client.send(proto::StartLanguageServer {
3230                project_id,
3231                server: Some(proto::LanguageServer {
3232                    id: server_id.0 as u64,
3233                    name: language_server.name().to_string(),
3234                }),
3235            })?;
3236        }
3237
3238        // Tell the language server about every open buffer in the worktree that matches the language.
3239        for buffer in self.opened_buffers.values() {
3240            if let Some(buffer_handle) = buffer.upgrade() {
3241                let buffer = buffer_handle.read(cx);
3242                let file = match File::from_dyn(buffer.file()) {
3243                    Some(file) => file,
3244                    None => continue,
3245                };
3246                let language = match buffer.language() {
3247                    Some(language) => language,
3248                    None => continue,
3249                };
3250
3251                if file.worktree.read(cx).id() != key.0
3252                    || !self
3253                        .languages
3254                        .lsp_adapters(&language)
3255                        .iter()
3256                        .any(|a| a.name == key.1)
3257                {
3258                    continue;
3259                }
3260
3261                let file = match file.as_local() {
3262                    Some(file) => file,
3263                    None => continue,
3264                };
3265
3266                let versions = self
3267                    .buffer_snapshots
3268                    .entry(buffer.remote_id())
3269                    .or_default()
3270                    .entry(server_id)
3271                    .or_insert_with(|| {
3272                        vec![LspBufferSnapshot {
3273                            version: 0,
3274                            snapshot: buffer.text_snapshot(),
3275                        }]
3276                    });
3277
3278                let snapshot = versions.last().unwrap();
3279                let version = snapshot.version;
3280                let initial_snapshot = &snapshot.snapshot;
3281                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3282                language_server.notify::<lsp::notification::DidOpenTextDocument>(
3283                    lsp::DidOpenTextDocumentParams {
3284                        text_document: lsp::TextDocumentItem::new(
3285                            uri,
3286                            adapter
3287                                .language_ids
3288                                .get(language.name().as_ref())
3289                                .cloned()
3290                                .unwrap_or_default(),
3291                            version,
3292                            initial_snapshot.text(),
3293                        ),
3294                    },
3295                )?;
3296
3297                buffer_handle.update(cx, |buffer, cx| {
3298                    buffer.set_completion_triggers(
3299                        language_server
3300                            .capabilities()
3301                            .completion_provider
3302                            .as_ref()
3303                            .and_then(|provider| provider.trigger_characters.clone())
3304                            .unwrap_or_default(),
3305                        cx,
3306                    )
3307                });
3308            }
3309        }
3310
3311        cx.notify();
3312        Ok(())
3313    }
3314
3315    // Returns a list of all of the worktrees which no longer have a language server and the root path
3316    // for the stopped server
3317    fn stop_language_server(
3318        &mut self,
3319        worktree_id: WorktreeId,
3320        adapter_name: LanguageServerName,
3321        cx: &mut ModelContext<Self>,
3322    ) -> Task<Vec<WorktreeId>> {
3323        let key = (worktree_id, adapter_name);
3324        if let Some(server_id) = self.language_server_ids.remove(&key) {
3325            let name = key.1 .0;
3326            log::info!("stopping language server {name}");
3327
3328            // Remove other entries for this language server as well
3329            let mut orphaned_worktrees = vec![worktree_id];
3330            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3331            for other_key in other_keys {
3332                if self.language_server_ids.get(&other_key) == Some(&server_id) {
3333                    self.language_server_ids.remove(&other_key);
3334                    orphaned_worktrees.push(other_key.0);
3335                }
3336            }
3337
3338            for buffer in self.opened_buffers.values() {
3339                if let Some(buffer) = buffer.upgrade() {
3340                    buffer.update(cx, |buffer, cx| {
3341                        buffer.update_diagnostics(server_id, Default::default(), cx);
3342                    });
3343                }
3344            }
3345            for worktree in &self.worktrees {
3346                if let Some(worktree) = worktree.upgrade() {
3347                    worktree.update(cx, |worktree, cx| {
3348                        if let Some(worktree) = worktree.as_local_mut() {
3349                            worktree.clear_diagnostics_for_language_server(server_id, cx);
3350                        }
3351                    });
3352                }
3353            }
3354
3355            self.language_server_statuses.remove(&server_id);
3356            cx.notify();
3357
3358            let server_state = self.language_servers.remove(&server_id);
3359            cx.emit(Event::LanguageServerRemoved(server_id));
3360            cx.spawn(move |this, cx| async move {
3361                Self::shutdown_language_server(this, server_state, name, server_id, cx).await;
3362                orphaned_worktrees
3363            })
3364        } else {
3365            Task::ready(Vec::new())
3366        }
3367    }
3368
3369    async fn shutdown_language_server(
3370        this: WeakModel<Project>,
3371        server_state: Option<LanguageServerState>,
3372        name: Arc<str>,
3373        server_id: LanguageServerId,
3374        mut cx: AsyncAppContext,
3375    ) {
3376        let server = match server_state {
3377            Some(LanguageServerState::Starting(task)) => {
3378                let mut timer = cx
3379                    .background_executor()
3380                    .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
3381                    .fuse();
3382
3383                select! {
3384                    server = task.fuse() => server,
3385                    _ = timer => {
3386                        log::info!(
3387                            "timeout waiting for language server {} to finish launching before stopping",
3388                            name
3389                        );
3390                        None
3391                    },
3392                }
3393            }
3394
3395            Some(LanguageServerState::Running { server, .. }) => Some(server),
3396
3397            None => None,
3398        };
3399
3400        if let Some(server) = server {
3401            if let Some(shutdown) = server.shutdown() {
3402                shutdown.await;
3403            }
3404        }
3405
3406        if let Some(this) = this.upgrade() {
3407            this.update(&mut cx, |this, cx| {
3408                this.language_server_statuses.remove(&server_id);
3409                cx.notify();
3410            })
3411            .ok();
3412        }
3413    }
3414
3415    pub fn restart_language_servers_for_buffers(
3416        &mut self,
3417        buffers: impl IntoIterator<Item = Model<Buffer>>,
3418        cx: &mut ModelContext<Self>,
3419    ) -> Option<()> {
3420        let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
3421            .into_iter()
3422            .filter_map(|buffer| {
3423                let buffer = buffer.read(cx);
3424                let file = File::from_dyn(buffer.file())?;
3425                let full_path = file.full_path(cx);
3426                let language = self
3427                    .languages
3428                    .language_for_file(&full_path, Some(buffer.as_rope()))
3429                    .now_or_never()?
3430                    .ok()?;
3431                Some((file.worktree.clone(), language))
3432            })
3433            .collect();
3434        for (worktree, language) in language_server_lookup_info {
3435            self.restart_language_servers(worktree, language, cx);
3436        }
3437
3438        None
3439    }
3440
3441    fn restart_language_servers(
3442        &mut self,
3443        worktree: Model<Worktree>,
3444        language: Arc<Language>,
3445        cx: &mut ModelContext<Self>,
3446    ) {
3447        let worktree_id = worktree.read(cx).id();
3448
3449        let stop_tasks = self
3450            .languages
3451            .clone()
3452            .lsp_adapters(&language)
3453            .iter()
3454            .map(|adapter| {
3455                let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
3456                (stop_task, adapter.name.clone())
3457            })
3458            .collect::<Vec<_>>();
3459        if stop_tasks.is_empty() {
3460            return;
3461        }
3462
3463        cx.spawn(move |this, mut cx| async move {
3464            // For each stopped language server, record all of the worktrees with which
3465            // it was associated.
3466            let mut affected_worktrees = Vec::new();
3467            for (stop_task, language_server_name) in stop_tasks {
3468                for affected_worktree_id in stop_task.await {
3469                    affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
3470                }
3471            }
3472
3473            this.update(&mut cx, |this, cx| {
3474                // Restart the language server for the given worktree.
3475                this.start_language_servers(&worktree, language.clone(), cx);
3476
3477                // Lookup new server ids and set them for each of the orphaned worktrees
3478                for (affected_worktree_id, language_server_name) in affected_worktrees {
3479                    if let Some(new_server_id) = this
3480                        .language_server_ids
3481                        .get(&(worktree_id, language_server_name.clone()))
3482                        .cloned()
3483                    {
3484                        this.language_server_ids
3485                            .insert((affected_worktree_id, language_server_name), new_server_id);
3486                    }
3487                }
3488            })
3489            .ok();
3490        })
3491        .detach();
3492    }
3493
3494    fn check_errored_server(
3495        language: Arc<Language>,
3496        adapter: Arc<CachedLspAdapter>,
3497        server_id: LanguageServerId,
3498        installation_test_binary: Option<LanguageServerBinary>,
3499        cx: &mut ModelContext<Self>,
3500    ) {
3501        if !adapter.can_be_reinstalled() {
3502            log::info!(
3503                "Validation check requested for {:?} but it cannot be reinstalled",
3504                adapter.name.0
3505            );
3506            return;
3507        }
3508
3509        cx.spawn(move |this, mut cx| async move {
3510            log::info!("About to spawn test binary");
3511
3512            // A lack of test binary counts as a failure
3513            let process = installation_test_binary.and_then(|binary| {
3514                smol::process::Command::new(&binary.path)
3515                    .current_dir(&binary.path)
3516                    .args(binary.arguments)
3517                    .stdin(Stdio::piped())
3518                    .stdout(Stdio::piped())
3519                    .stderr(Stdio::inherit())
3520                    .kill_on_drop(true)
3521                    .spawn()
3522                    .ok()
3523            });
3524
3525            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3526            let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
3527
3528            let mut errored = false;
3529            if let Some(mut process) = process {
3530                futures::select! {
3531                    status = process.status().fuse() => match status {
3532                        Ok(status) => errored = !status.success(),
3533                        Err(_) => errored = true,
3534                    },
3535
3536                    _ = timeout => {
3537                        log::info!("test binary time-ed out, this counts as a success");
3538                        _ = process.kill();
3539                    }
3540                }
3541            } else {
3542                log::warn!("test binary failed to launch");
3543                errored = true;
3544            }
3545
3546            if errored {
3547                log::warn!("test binary check failed");
3548                let task = this
3549                    .update(&mut cx, move |this, cx| {
3550                        this.reinstall_language_server(language, adapter, server_id, cx)
3551                    })
3552                    .ok()
3553                    .flatten();
3554
3555                if let Some(task) = task {
3556                    task.await;
3557                }
3558            }
3559        })
3560        .detach();
3561    }
3562
3563    fn on_lsp_progress(
3564        &mut self,
3565        progress: lsp::ProgressParams,
3566        language_server_id: LanguageServerId,
3567        disk_based_diagnostics_progress_token: Option<String>,
3568        cx: &mut ModelContext<Self>,
3569    ) {
3570        let token = match progress.token {
3571            lsp::NumberOrString::String(token) => token,
3572            lsp::NumberOrString::Number(token) => {
3573                log::info!("skipping numeric progress token {}", token);
3574                return;
3575            }
3576        };
3577        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3578        let language_server_status =
3579            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3580                status
3581            } else {
3582                return;
3583            };
3584
3585        if !language_server_status.progress_tokens.contains(&token) {
3586            return;
3587        }
3588
3589        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3590            .as_ref()
3591            .map_or(false, |disk_based_token| {
3592                token.starts_with(disk_based_token)
3593            });
3594
3595        match progress {
3596            lsp::WorkDoneProgress::Begin(report) => {
3597                if is_disk_based_diagnostics_progress {
3598                    language_server_status.has_pending_diagnostic_updates = true;
3599                    self.disk_based_diagnostics_started(language_server_id, cx);
3600                    self.buffer_ordered_messages_tx
3601                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3602                            language_server_id,
3603                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3604                        })
3605                        .ok();
3606                } else {
3607                    self.on_lsp_work_start(
3608                        language_server_id,
3609                        token.clone(),
3610                        LanguageServerProgress {
3611                            message: report.message.clone(),
3612                            percentage: report.percentage.map(|p| p as usize),
3613                            last_update_at: Instant::now(),
3614                        },
3615                        cx,
3616                    );
3617                    self.buffer_ordered_messages_tx
3618                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3619                            language_server_id,
3620                            message: proto::update_language_server::Variant::WorkStart(
3621                                proto::LspWorkStart {
3622                                    token,
3623                                    message: report.message,
3624                                    percentage: report.percentage.map(|p| p as u32),
3625                                },
3626                            ),
3627                        })
3628                        .ok();
3629                }
3630            }
3631            lsp::WorkDoneProgress::Report(report) => {
3632                if !is_disk_based_diagnostics_progress {
3633                    self.on_lsp_work_progress(
3634                        language_server_id,
3635                        token.clone(),
3636                        LanguageServerProgress {
3637                            message: report.message.clone(),
3638                            percentage: report.percentage.map(|p| p as usize),
3639                            last_update_at: Instant::now(),
3640                        },
3641                        cx,
3642                    );
3643                    self.buffer_ordered_messages_tx
3644                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3645                            language_server_id,
3646                            message: proto::update_language_server::Variant::WorkProgress(
3647                                proto::LspWorkProgress {
3648                                    token,
3649                                    message: report.message,
3650                                    percentage: report.percentage.map(|p| p as u32),
3651                                },
3652                            ),
3653                        })
3654                        .ok();
3655                }
3656            }
3657            lsp::WorkDoneProgress::End(_) => {
3658                language_server_status.progress_tokens.remove(&token);
3659
3660                if is_disk_based_diagnostics_progress {
3661                    language_server_status.has_pending_diagnostic_updates = false;
3662                    self.disk_based_diagnostics_finished(language_server_id, cx);
3663                    self.buffer_ordered_messages_tx
3664                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3665                            language_server_id,
3666                            message:
3667                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3668                                    Default::default(),
3669                                ),
3670                        })
3671                        .ok();
3672                } else {
3673                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
3674                    self.buffer_ordered_messages_tx
3675                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3676                            language_server_id,
3677                            message: proto::update_language_server::Variant::WorkEnd(
3678                                proto::LspWorkEnd { token },
3679                            ),
3680                        })
3681                        .ok();
3682                }
3683            }
3684        }
3685    }
3686
3687    fn on_lsp_work_start(
3688        &mut self,
3689        language_server_id: LanguageServerId,
3690        token: String,
3691        progress: LanguageServerProgress,
3692        cx: &mut ModelContext<Self>,
3693    ) {
3694        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3695            status.pending_work.insert(token, progress);
3696            cx.notify();
3697        }
3698    }
3699
3700    fn on_lsp_work_progress(
3701        &mut self,
3702        language_server_id: LanguageServerId,
3703        token: String,
3704        progress: LanguageServerProgress,
3705        cx: &mut ModelContext<Self>,
3706    ) {
3707        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3708            let entry = status
3709                .pending_work
3710                .entry(token)
3711                .or_insert(LanguageServerProgress {
3712                    message: Default::default(),
3713                    percentage: Default::default(),
3714                    last_update_at: progress.last_update_at,
3715                });
3716            if progress.message.is_some() {
3717                entry.message = progress.message;
3718            }
3719            if progress.percentage.is_some() {
3720                entry.percentage = progress.percentage;
3721            }
3722            entry.last_update_at = progress.last_update_at;
3723            cx.notify();
3724        }
3725    }
3726
3727    fn on_lsp_work_end(
3728        &mut self,
3729        language_server_id: LanguageServerId,
3730        token: String,
3731        cx: &mut ModelContext<Self>,
3732    ) {
3733        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3734            cx.emit(Event::RefreshInlayHints);
3735            status.pending_work.remove(&token);
3736            cx.notify();
3737        }
3738    }
3739
3740    fn on_lsp_did_change_watched_files(
3741        &mut self,
3742        language_server_id: LanguageServerId,
3743        params: DidChangeWatchedFilesRegistrationOptions,
3744        cx: &mut ModelContext<Self>,
3745    ) {
3746        if let Some(LanguageServerState::Running { watched_paths, .. }) =
3747            self.language_servers.get_mut(&language_server_id)
3748        {
3749            let mut builders = HashMap::default();
3750            for watcher in params.watchers {
3751                for worktree in &self.worktrees {
3752                    if let Some(worktree) = worktree.upgrade() {
3753                        let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3754                            if let Some(abs_path) = tree.abs_path().to_str() {
3755                                let relative_glob_pattern = match &watcher.glob_pattern {
3756                                    lsp::GlobPattern::String(s) => s
3757                                        .strip_prefix(abs_path)
3758                                        .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3759                                    lsp::GlobPattern::Relative(rp) => {
3760                                        let base_uri = match &rp.base_uri {
3761                                            lsp::OneOf::Left(workspace_folder) => {
3762                                                &workspace_folder.uri
3763                                            }
3764                                            lsp::OneOf::Right(base_uri) => base_uri,
3765                                        };
3766                                        base_uri.to_file_path().ok().and_then(|file_path| {
3767                                            (file_path.to_str() == Some(abs_path))
3768                                                .then_some(rp.pattern.as_str())
3769                                        })
3770                                    }
3771                                };
3772                                if let Some(relative_glob_pattern) = relative_glob_pattern {
3773                                    let literal_prefix = glob_literal_prefix(relative_glob_pattern);
3774                                    tree.as_local_mut()
3775                                        .unwrap()
3776                                        .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3777                                    if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3778                                        builders
3779                                            .entry(tree.id())
3780                                            .or_insert_with(|| GlobSetBuilder::new())
3781                                            .add(glob);
3782                                    }
3783                                    return true;
3784                                }
3785                            }
3786                            false
3787                        });
3788                        if glob_is_inside_worktree {
3789                            break;
3790                        }
3791                    }
3792                }
3793            }
3794
3795            watched_paths.clear();
3796            for (worktree_id, builder) in builders {
3797                if let Ok(globset) = builder.build() {
3798                    watched_paths.insert(worktree_id, globset);
3799                }
3800            }
3801
3802            cx.notify();
3803        }
3804    }
3805
3806    async fn on_lsp_workspace_edit(
3807        this: WeakModel<Self>,
3808        params: lsp::ApplyWorkspaceEditParams,
3809        server_id: LanguageServerId,
3810        adapter: Arc<CachedLspAdapter>,
3811        mut cx: AsyncAppContext,
3812    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3813        let this = this
3814            .upgrade()
3815            .ok_or_else(|| anyhow!("project project closed"))?;
3816        let language_server = this
3817            .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
3818            .ok_or_else(|| anyhow!("language server not found"))?;
3819        let transaction = Self::deserialize_workspace_edit(
3820            this.clone(),
3821            params.edit,
3822            true,
3823            adapter.clone(),
3824            language_server.clone(),
3825            &mut cx,
3826        )
3827        .await
3828        .log_err();
3829        this.update(&mut cx, |this, _| {
3830            if let Some(transaction) = transaction {
3831                this.last_workspace_edits_by_language_server
3832                    .insert(server_id, transaction);
3833            }
3834        })?;
3835        Ok(lsp::ApplyWorkspaceEditResponse {
3836            applied: true,
3837            failed_change: None,
3838            failure_reason: None,
3839        })
3840    }
3841
3842    pub fn language_server_statuses(
3843        &self,
3844    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3845        self.language_server_statuses.values()
3846    }
3847
3848    pub fn update_diagnostics(
3849        &mut self,
3850        language_server_id: LanguageServerId,
3851        mut params: lsp::PublishDiagnosticsParams,
3852        disk_based_sources: &[String],
3853        cx: &mut ModelContext<Self>,
3854    ) -> Result<()> {
3855        let abs_path = params
3856            .uri
3857            .to_file_path()
3858            .map_err(|_| anyhow!("URI is not a file"))?;
3859        let mut diagnostics = Vec::default();
3860        let mut primary_diagnostic_group_ids = HashMap::default();
3861        let mut sources_by_group_id = HashMap::default();
3862        let mut supporting_diagnostics = HashMap::default();
3863
3864        // Ensure that primary diagnostics are always the most severe
3865        params.diagnostics.sort_by_key(|item| item.severity);
3866
3867        for diagnostic in &params.diagnostics {
3868            let source = diagnostic.source.as_ref();
3869            let code = diagnostic.code.as_ref().map(|code| match code {
3870                lsp::NumberOrString::Number(code) => code.to_string(),
3871                lsp::NumberOrString::String(code) => code.clone(),
3872            });
3873            let range = range_from_lsp(diagnostic.range);
3874            let is_supporting = diagnostic
3875                .related_information
3876                .as_ref()
3877                .map_or(false, |infos| {
3878                    infos.iter().any(|info| {
3879                        primary_diagnostic_group_ids.contains_key(&(
3880                            source,
3881                            code.clone(),
3882                            range_from_lsp(info.location.range),
3883                        ))
3884                    })
3885                });
3886
3887            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3888                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3889            });
3890
3891            if is_supporting {
3892                supporting_diagnostics.insert(
3893                    (source, code.clone(), range),
3894                    (diagnostic.severity, is_unnecessary),
3895                );
3896            } else {
3897                let group_id = post_inc(&mut self.next_diagnostic_group_id);
3898                let is_disk_based =
3899                    source.map_or(false, |source| disk_based_sources.contains(source));
3900
3901                sources_by_group_id.insert(group_id, source);
3902                primary_diagnostic_group_ids
3903                    .insert((source, code.clone(), range.clone()), group_id);
3904
3905                diagnostics.push(DiagnosticEntry {
3906                    range,
3907                    diagnostic: Diagnostic {
3908                        source: diagnostic.source.clone(),
3909                        code: code.clone(),
3910                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3911                        message: diagnostic.message.trim().to_string(),
3912                        group_id,
3913                        is_primary: true,
3914                        is_disk_based,
3915                        is_unnecessary,
3916                    },
3917                });
3918                if let Some(infos) = &diagnostic.related_information {
3919                    for info in infos {
3920                        if info.location.uri == params.uri && !info.message.is_empty() {
3921                            let range = range_from_lsp(info.location.range);
3922                            diagnostics.push(DiagnosticEntry {
3923                                range,
3924                                diagnostic: Diagnostic {
3925                                    source: diagnostic.source.clone(),
3926                                    code: code.clone(),
3927                                    severity: DiagnosticSeverity::INFORMATION,
3928                                    message: info.message.trim().to_string(),
3929                                    group_id,
3930                                    is_primary: false,
3931                                    is_disk_based,
3932                                    is_unnecessary: false,
3933                                },
3934                            });
3935                        }
3936                    }
3937                }
3938            }
3939        }
3940
3941        for entry in &mut diagnostics {
3942            let diagnostic = &mut entry.diagnostic;
3943            if !diagnostic.is_primary {
3944                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3945                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3946                    source,
3947                    diagnostic.code.clone(),
3948                    entry.range.clone(),
3949                )) {
3950                    if let Some(severity) = severity {
3951                        diagnostic.severity = severity;
3952                    }
3953                    diagnostic.is_unnecessary = is_unnecessary;
3954                }
3955            }
3956        }
3957
3958        self.update_diagnostic_entries(
3959            language_server_id,
3960            abs_path,
3961            params.version,
3962            diagnostics,
3963            cx,
3964        )?;
3965        Ok(())
3966    }
3967
3968    pub fn update_diagnostic_entries(
3969        &mut self,
3970        server_id: LanguageServerId,
3971        abs_path: PathBuf,
3972        version: Option<i32>,
3973        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3974        cx: &mut ModelContext<Project>,
3975    ) -> Result<(), anyhow::Error> {
3976        let (worktree, relative_path) = self
3977            .find_local_worktree(&abs_path, cx)
3978            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3979
3980        let project_path = ProjectPath {
3981            worktree_id: worktree.read(cx).id(),
3982            path: relative_path.into(),
3983        };
3984
3985        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3986            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3987        }
3988
3989        let updated = worktree.update(cx, |worktree, cx| {
3990            worktree
3991                .as_local_mut()
3992                .ok_or_else(|| anyhow!("not a local worktree"))?
3993                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3994        })?;
3995        if updated {
3996            cx.emit(Event::DiagnosticsUpdated {
3997                language_server_id: server_id,
3998                path: project_path,
3999            });
4000        }
4001        Ok(())
4002    }
4003
4004    fn update_buffer_diagnostics(
4005        &mut self,
4006        buffer: &Model<Buffer>,
4007        server_id: LanguageServerId,
4008        version: Option<i32>,
4009        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4010        cx: &mut ModelContext<Self>,
4011    ) -> Result<()> {
4012        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
4013            Ordering::Equal
4014                .then_with(|| b.is_primary.cmp(&a.is_primary))
4015                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
4016                .then_with(|| a.severity.cmp(&b.severity))
4017                .then_with(|| a.message.cmp(&b.message))
4018        }
4019
4020        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
4021
4022        diagnostics.sort_unstable_by(|a, b| {
4023            Ordering::Equal
4024                .then_with(|| a.range.start.cmp(&b.range.start))
4025                .then_with(|| b.range.end.cmp(&a.range.end))
4026                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
4027        });
4028
4029        let mut sanitized_diagnostics = Vec::new();
4030        let edits_since_save = Patch::new(
4031            snapshot
4032                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
4033                .collect(),
4034        );
4035        for entry in diagnostics {
4036            let start;
4037            let end;
4038            if entry.diagnostic.is_disk_based {
4039                // Some diagnostics are based on files on disk instead of buffers'
4040                // current contents. Adjust these diagnostics' ranges to reflect
4041                // any unsaved edits.
4042                start = edits_since_save.old_to_new(entry.range.start);
4043                end = edits_since_save.old_to_new(entry.range.end);
4044            } else {
4045                start = entry.range.start;
4046                end = entry.range.end;
4047            }
4048
4049            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
4050                ..snapshot.clip_point_utf16(end, Bias::Right);
4051
4052            // Expand empty ranges by one codepoint
4053            if range.start == range.end {
4054                // This will be go to the next boundary when being clipped
4055                range.end.column += 1;
4056                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
4057                if range.start == range.end && range.end.column > 0 {
4058                    range.start.column -= 1;
4059                    range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
4060                }
4061            }
4062
4063            sanitized_diagnostics.push(DiagnosticEntry {
4064                range,
4065                diagnostic: entry.diagnostic,
4066            });
4067        }
4068        drop(edits_since_save);
4069
4070        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
4071        buffer.update(cx, |buffer, cx| {
4072            buffer.update_diagnostics(server_id, set, cx)
4073        });
4074        Ok(())
4075    }
4076
4077    pub fn reload_buffers(
4078        &self,
4079        buffers: HashSet<Model<Buffer>>,
4080        push_to_history: bool,
4081        cx: &mut ModelContext<Self>,
4082    ) -> Task<Result<ProjectTransaction>> {
4083        let mut local_buffers = Vec::new();
4084        let mut remote_buffers = None;
4085        for buffer_handle in buffers {
4086            let buffer = buffer_handle.read(cx);
4087            if buffer.is_dirty() {
4088                if let Some(file) = File::from_dyn(buffer.file()) {
4089                    if file.is_local() {
4090                        local_buffers.push(buffer_handle);
4091                    } else {
4092                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
4093                    }
4094                }
4095            }
4096        }
4097
4098        let remote_buffers = self.remote_id().zip(remote_buffers);
4099        let client = self.client.clone();
4100
4101        cx.spawn(move |this, mut cx| async move {
4102            let mut project_transaction = ProjectTransaction::default();
4103
4104            if let Some((project_id, remote_buffers)) = remote_buffers {
4105                let response = client
4106                    .request(proto::ReloadBuffers {
4107                        project_id,
4108                        buffer_ids: remote_buffers
4109                            .iter()
4110                            .filter_map(|buffer| {
4111                                buffer
4112                                    .update(&mut cx, |buffer, _| buffer.remote_id().into())
4113                                    .ok()
4114                            })
4115                            .collect(),
4116                    })
4117                    .await?
4118                    .transaction
4119                    .ok_or_else(|| anyhow!("missing transaction"))?;
4120                project_transaction = this
4121                    .update(&mut cx, |this, cx| {
4122                        this.deserialize_project_transaction(response, push_to_history, cx)
4123                    })?
4124                    .await?;
4125            }
4126
4127            for buffer in local_buffers {
4128                let transaction = buffer
4129                    .update(&mut cx, |buffer, cx| buffer.reload(cx))?
4130                    .await?;
4131                buffer.update(&mut cx, |buffer, cx| {
4132                    if let Some(transaction) = transaction {
4133                        if !push_to_history {
4134                            buffer.forget_transaction(transaction.id);
4135                        }
4136                        project_transaction.0.insert(cx.handle(), transaction);
4137                    }
4138                })?;
4139            }
4140
4141            Ok(project_transaction)
4142        })
4143    }
4144
4145    pub fn format(
4146        &mut self,
4147        buffers: HashSet<Model<Buffer>>,
4148        push_to_history: bool,
4149        trigger: FormatTrigger,
4150        cx: &mut ModelContext<Project>,
4151    ) -> Task<anyhow::Result<ProjectTransaction>> {
4152        if self.is_local() {
4153            let mut buffers_with_paths = buffers
4154                .into_iter()
4155                .filter_map(|buffer_handle| {
4156                    let buffer = buffer_handle.read(cx);
4157                    let file = File::from_dyn(buffer.file())?;
4158                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
4159                    Some((buffer_handle, buffer_abs_path))
4160                })
4161                .collect::<Vec<_>>();
4162
4163            cx.spawn(move |project, mut cx| async move {
4164                // Do not allow multiple concurrent formatting requests for the
4165                // same buffer.
4166                project.update(&mut cx, |this, cx| {
4167                    buffers_with_paths.retain(|(buffer, _)| {
4168                        this.buffers_being_formatted
4169                            .insert(buffer.read(cx).remote_id())
4170                    });
4171                })?;
4172
4173                let _cleanup = defer({
4174                    let this = project.clone();
4175                    let mut cx = cx.clone();
4176                    let buffers = &buffers_with_paths;
4177                    move || {
4178                        this.update(&mut cx, |this, cx| {
4179                            for (buffer, _) in buffers {
4180                                this.buffers_being_formatted
4181                                    .remove(&buffer.read(cx).remote_id());
4182                            }
4183                        })
4184                        .ok();
4185                    }
4186                });
4187
4188                let mut project_transaction = ProjectTransaction::default();
4189                for (buffer, buffer_abs_path) in &buffers_with_paths {
4190                    let adapters_and_servers: Vec<_> = project.update(&mut cx, |project, cx| {
4191                        project
4192                            .language_servers_for_buffer(&buffer.read(cx), cx)
4193                            .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
4194                            .collect()
4195                    })?;
4196
4197                    let settings = buffer.update(&mut cx, |buffer, cx| {
4198                        language_settings(buffer.language(), buffer.file(), cx).clone()
4199                    })?;
4200
4201                    let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
4202                    let ensure_final_newline = settings.ensure_final_newline_on_save;
4203                    let tab_size = settings.tab_size;
4204
4205                    // First, format buffer's whitespace according to the settings.
4206                    let trailing_whitespace_diff = if remove_trailing_whitespace {
4207                        Some(
4208                            buffer
4209                                .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
4210                                .await,
4211                        )
4212                    } else {
4213                        None
4214                    };
4215                    let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
4216                        buffer.finalize_last_transaction();
4217                        buffer.start_transaction();
4218                        if let Some(diff) = trailing_whitespace_diff {
4219                            buffer.apply_diff(diff, cx);
4220                        }
4221                        if ensure_final_newline {
4222                            buffer.ensure_final_newline(cx);
4223                        }
4224                        buffer.end_transaction(cx)
4225                    })?;
4226
4227                    for (lsp_adapter, language_server) in adapters_and_servers.iter() {
4228                        // Apply the code actions on
4229                        let code_actions: Vec<lsp::CodeActionKind> = settings
4230                            .code_actions_on_format
4231                            .iter()
4232                            .flat_map(|(kind, enabled)| {
4233                                if *enabled {
4234                                    Some(kind.clone().into())
4235                                } else {
4236                                    None
4237                                }
4238                            })
4239                            .collect();
4240
4241                        if !code_actions.is_empty()
4242                            && !(trigger == FormatTrigger::Save
4243                                && settings.format_on_save == FormatOnSave::Off)
4244                        {
4245                            let actions = project
4246                                .update(&mut cx, |this, cx| {
4247                                    this.request_lsp(
4248                                        buffer.clone(),
4249                                        LanguageServerToQuery::Other(language_server.server_id()),
4250                                        GetCodeActions {
4251                                            range: text::Anchor::MIN..text::Anchor::MAX,
4252                                            kinds: Some(code_actions),
4253                                        },
4254                                        cx,
4255                                    )
4256                                })?
4257                                .await?;
4258
4259                            for action in actions {
4260                                if let Some(edit) = action.lsp_action.edit {
4261                                    if edit.changes.is_none() && edit.document_changes.is_none() {
4262                                        continue;
4263                                    }
4264
4265                                    let new = Self::deserialize_workspace_edit(
4266                                        project
4267                                            .upgrade()
4268                                            .ok_or_else(|| anyhow!("project dropped"))?,
4269                                        edit,
4270                                        push_to_history,
4271                                        lsp_adapter.clone(),
4272                                        language_server.clone(),
4273                                        &mut cx,
4274                                    )
4275                                    .await?;
4276                                    project_transaction.0.extend(new.0);
4277                                }
4278
4279                                if let Some(command) = action.lsp_action.command {
4280                                    project.update(&mut cx, |this, _| {
4281                                        this.last_workspace_edits_by_language_server
4282                                            .remove(&language_server.server_id());
4283                                    })?;
4284
4285                                    language_server
4286                                        .request::<lsp::request::ExecuteCommand>(
4287                                            lsp::ExecuteCommandParams {
4288                                                command: command.command,
4289                                                arguments: command.arguments.unwrap_or_default(),
4290                                                ..Default::default()
4291                                            },
4292                                        )
4293                                        .await?;
4294
4295                                    project.update(&mut cx, |this, _| {
4296                                        project_transaction.0.extend(
4297                                            this.last_workspace_edits_by_language_server
4298                                                .remove(&language_server.server_id())
4299                                                .unwrap_or_default()
4300                                                .0,
4301                                        )
4302                                    })?;
4303                                }
4304                            }
4305                        }
4306                    }
4307
4308                    // Apply language-specific formatting using either the primary language server
4309                    // or external command.
4310                    let primary_language_server = adapters_and_servers
4311                        .first()
4312                        .cloned()
4313                        .map(|(_, lsp)| lsp.clone());
4314                    let server_and_buffer = primary_language_server
4315                        .as_ref()
4316                        .zip(buffer_abs_path.as_ref());
4317
4318                    let mut format_operation = None;
4319                    match (&settings.formatter, &settings.format_on_save) {
4320                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4321
4322                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4323                        | (_, FormatOnSave::LanguageServer) => {
4324                            if let Some((language_server, buffer_abs_path)) = server_and_buffer {
4325                                format_operation = Some(FormatOperation::Lsp(
4326                                    Self::format_via_lsp(
4327                                        &project,
4328                                        buffer,
4329                                        buffer_abs_path,
4330                                        language_server,
4331                                        tab_size,
4332                                        &mut cx,
4333                                    )
4334                                    .await
4335                                    .context("failed to format via language server")?,
4336                                ));
4337                            }
4338                        }
4339
4340                        (
4341                            Formatter::External { command, arguments },
4342                            FormatOnSave::On | FormatOnSave::Off,
4343                        )
4344                        | (_, FormatOnSave::External { command, arguments }) => {
4345                            if let Some(buffer_abs_path) = buffer_abs_path {
4346                                format_operation = Self::format_via_external_command(
4347                                    buffer,
4348                                    buffer_abs_path,
4349                                    command,
4350                                    arguments,
4351                                    &mut cx,
4352                                )
4353                                .await
4354                                .context(format!(
4355                                    "failed to format via external command {:?}",
4356                                    command
4357                                ))?
4358                                .map(FormatOperation::External);
4359                            }
4360                        }
4361                        (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4362                            if let Some(new_operation) =
4363                                prettier_support::format_with_prettier(&project, buffer, &mut cx)
4364                                    .await
4365                            {
4366                                format_operation = Some(new_operation);
4367                            } else if let Some((language_server, buffer_abs_path)) =
4368                                server_and_buffer
4369                            {
4370                                format_operation = Some(FormatOperation::Lsp(
4371                                    Self::format_via_lsp(
4372                                        &project,
4373                                        buffer,
4374                                        buffer_abs_path,
4375                                        language_server,
4376                                        tab_size,
4377                                        &mut cx,
4378                                    )
4379                                    .await
4380                                    .context("failed to format via language server")?,
4381                                ));
4382                            }
4383                        }
4384                        (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
4385                            if let Some(new_operation) =
4386                                prettier_support::format_with_prettier(&project, buffer, &mut cx)
4387                                    .await
4388                            {
4389                                format_operation = Some(new_operation);
4390                            }
4391                        }
4392                    };
4393
4394                    buffer.update(&mut cx, |b, cx| {
4395                        // If the buffer had its whitespace formatted and was edited while the language-specific
4396                        // formatting was being computed, avoid applying the language-specific formatting, because
4397                        // it can't be grouped with the whitespace formatting in the undo history.
4398                        if let Some(transaction_id) = whitespace_transaction_id {
4399                            if b.peek_undo_stack()
4400                                .map_or(true, |e| e.transaction_id() != transaction_id)
4401                            {
4402                                format_operation.take();
4403                            }
4404                        }
4405
4406                        // Apply any language-specific formatting, and group the two formatting operations
4407                        // in the buffer's undo history.
4408                        if let Some(operation) = format_operation {
4409                            match operation {
4410                                FormatOperation::Lsp(edits) => {
4411                                    b.edit(edits, None, cx);
4412                                }
4413                                FormatOperation::External(diff) => {
4414                                    b.apply_diff(diff, cx);
4415                                }
4416                                FormatOperation::Prettier(diff) => {
4417                                    b.apply_diff(diff, cx);
4418                                }
4419                            }
4420
4421                            if let Some(transaction_id) = whitespace_transaction_id {
4422                                b.group_until_transaction(transaction_id);
4423                            } else if let Some(transaction) = project_transaction.0.get(buffer) {
4424                                b.group_until_transaction(transaction.id)
4425                            }
4426                        }
4427
4428                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
4429                            if !push_to_history {
4430                                b.forget_transaction(transaction.id);
4431                            }
4432                            project_transaction.0.insert(buffer.clone(), transaction);
4433                        }
4434                    })?;
4435                }
4436
4437                Ok(project_transaction)
4438            })
4439        } else {
4440            let remote_id = self.remote_id();
4441            let client = self.client.clone();
4442            cx.spawn(move |this, mut cx| async move {
4443                let mut project_transaction = ProjectTransaction::default();
4444                if let Some(project_id) = remote_id {
4445                    let response = client
4446                        .request(proto::FormatBuffers {
4447                            project_id,
4448                            trigger: trigger as i32,
4449                            buffer_ids: buffers
4450                                .iter()
4451                                .map(|buffer| {
4452                                    buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
4453                                })
4454                                .collect::<Result<_>>()?,
4455                        })
4456                        .await?
4457                        .transaction
4458                        .ok_or_else(|| anyhow!("missing transaction"))?;
4459                    project_transaction = this
4460                        .update(&mut cx, |this, cx| {
4461                            this.deserialize_project_transaction(response, push_to_history, cx)
4462                        })?
4463                        .await?;
4464                }
4465                Ok(project_transaction)
4466            })
4467        }
4468    }
4469
4470    async fn format_via_lsp(
4471        this: &WeakModel<Self>,
4472        buffer: &Model<Buffer>,
4473        abs_path: &Path,
4474        language_server: &Arc<LanguageServer>,
4475        tab_size: NonZeroU32,
4476        cx: &mut AsyncAppContext,
4477    ) -> Result<Vec<(Range<Anchor>, String)>> {
4478        let uri = lsp::Url::from_file_path(abs_path)
4479            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4480        let text_document = lsp::TextDocumentIdentifier::new(uri);
4481        let capabilities = &language_server.capabilities();
4482
4483        let formatting_provider = capabilities.document_formatting_provider.as_ref();
4484        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4485
4486        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4487            language_server
4488                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4489                    text_document,
4490                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4491                    work_done_progress_params: Default::default(),
4492                })
4493                .await?
4494        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4495            let buffer_start = lsp::Position::new(0, 0);
4496            let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
4497
4498            language_server
4499                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4500                    text_document,
4501                    range: lsp::Range::new(buffer_start, buffer_end),
4502                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4503                    work_done_progress_params: Default::default(),
4504                })
4505                .await?
4506        } else {
4507            None
4508        };
4509
4510        if let Some(lsp_edits) = lsp_edits {
4511            this.update(cx, |this, cx| {
4512                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4513            })?
4514            .await
4515        } else {
4516            Ok(Vec::new())
4517        }
4518    }
4519
4520    async fn format_via_external_command(
4521        buffer: &Model<Buffer>,
4522        buffer_abs_path: &Path,
4523        command: &str,
4524        arguments: &[String],
4525        cx: &mut AsyncAppContext,
4526    ) -> Result<Option<Diff>> {
4527        let working_dir_path = buffer.update(cx, |buffer, cx| {
4528            let file = File::from_dyn(buffer.file())?;
4529            let worktree = file.worktree.read(cx).as_local()?;
4530            let mut worktree_path = worktree.abs_path().to_path_buf();
4531            if worktree.root_entry()?.is_file() {
4532                worktree_path.pop();
4533            }
4534            Some(worktree_path)
4535        })?;
4536
4537        if let Some(working_dir_path) = working_dir_path {
4538            let mut child =
4539                smol::process::Command::new(command)
4540                    .args(arguments.iter().map(|arg| {
4541                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4542                    }))
4543                    .current_dir(&working_dir_path)
4544                    .stdin(smol::process::Stdio::piped())
4545                    .stdout(smol::process::Stdio::piped())
4546                    .stderr(smol::process::Stdio::piped())
4547                    .spawn()?;
4548            let stdin = child
4549                .stdin
4550                .as_mut()
4551                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4552            let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
4553            for chunk in text.chunks() {
4554                stdin.write_all(chunk.as_bytes()).await?;
4555            }
4556            stdin.flush().await?;
4557
4558            let output = child.output().await?;
4559            if !output.status.success() {
4560                return Err(anyhow!(
4561                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4562                    output.status.code(),
4563                    String::from_utf8_lossy(&output.stdout),
4564                    String::from_utf8_lossy(&output.stderr),
4565                ));
4566            }
4567
4568            let stdout = String::from_utf8(output.stdout)?;
4569            Ok(Some(
4570                buffer
4571                    .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
4572                    .await,
4573            ))
4574        } else {
4575            Ok(None)
4576        }
4577    }
4578
4579    #[inline(never)]
4580    fn definition_impl(
4581        &self,
4582        buffer: &Model<Buffer>,
4583        position: PointUtf16,
4584        cx: &mut ModelContext<Self>,
4585    ) -> Task<Result<Vec<LocationLink>>> {
4586        self.request_lsp(
4587            buffer.clone(),
4588            LanguageServerToQuery::Primary,
4589            GetDefinition { position },
4590            cx,
4591        )
4592    }
4593    pub fn definition<T: ToPointUtf16>(
4594        &self,
4595        buffer: &Model<Buffer>,
4596        position: T,
4597        cx: &mut ModelContext<Self>,
4598    ) -> Task<Result<Vec<LocationLink>>> {
4599        let position = position.to_point_utf16(buffer.read(cx));
4600        self.definition_impl(buffer, position, cx)
4601    }
4602
4603    fn type_definition_impl(
4604        &self,
4605        buffer: &Model<Buffer>,
4606        position: PointUtf16,
4607        cx: &mut ModelContext<Self>,
4608    ) -> Task<Result<Vec<LocationLink>>> {
4609        self.request_lsp(
4610            buffer.clone(),
4611            LanguageServerToQuery::Primary,
4612            GetTypeDefinition { position },
4613            cx,
4614        )
4615    }
4616
4617    pub fn type_definition<T: ToPointUtf16>(
4618        &self,
4619        buffer: &Model<Buffer>,
4620        position: T,
4621        cx: &mut ModelContext<Self>,
4622    ) -> Task<Result<Vec<LocationLink>>> {
4623        let position = position.to_point_utf16(buffer.read(cx));
4624        self.type_definition_impl(buffer, position, cx)
4625    }
4626
4627    fn implementation_impl(
4628        &self,
4629        buffer: &Model<Buffer>,
4630        position: PointUtf16,
4631        cx: &mut ModelContext<Self>,
4632    ) -> Task<Result<Vec<LocationLink>>> {
4633        self.request_lsp(
4634            buffer.clone(),
4635            LanguageServerToQuery::Primary,
4636            GetImplementation { position },
4637            cx,
4638        )
4639    }
4640
4641    pub fn implementation<T: ToPointUtf16>(
4642        &self,
4643        buffer: &Model<Buffer>,
4644        position: T,
4645        cx: &mut ModelContext<Self>,
4646    ) -> Task<Result<Vec<LocationLink>>> {
4647        let position = position.to_point_utf16(buffer.read(cx));
4648        self.implementation_impl(buffer, position, cx)
4649    }
4650
4651    fn references_impl(
4652        &self,
4653        buffer: &Model<Buffer>,
4654        position: PointUtf16,
4655        cx: &mut ModelContext<Self>,
4656    ) -> Task<Result<Vec<Location>>> {
4657        self.request_lsp(
4658            buffer.clone(),
4659            LanguageServerToQuery::Primary,
4660            GetReferences { position },
4661            cx,
4662        )
4663    }
4664    pub fn references<T: ToPointUtf16>(
4665        &self,
4666        buffer: &Model<Buffer>,
4667        position: T,
4668        cx: &mut ModelContext<Self>,
4669    ) -> Task<Result<Vec<Location>>> {
4670        let position = position.to_point_utf16(buffer.read(cx));
4671        self.references_impl(buffer, position, cx)
4672    }
4673
4674    fn document_highlights_impl(
4675        &self,
4676        buffer: &Model<Buffer>,
4677        position: PointUtf16,
4678        cx: &mut ModelContext<Self>,
4679    ) -> Task<Result<Vec<DocumentHighlight>>> {
4680        self.request_lsp(
4681            buffer.clone(),
4682            LanguageServerToQuery::Primary,
4683            GetDocumentHighlights { position },
4684            cx,
4685        )
4686    }
4687
4688    pub fn document_highlights<T: ToPointUtf16>(
4689        &self,
4690        buffer: &Model<Buffer>,
4691        position: T,
4692        cx: &mut ModelContext<Self>,
4693    ) -> Task<Result<Vec<DocumentHighlight>>> {
4694        let position = position.to_point_utf16(buffer.read(cx));
4695        self.document_highlights_impl(buffer, position, cx)
4696    }
4697
4698    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4699        if self.is_local() {
4700            let mut requests = Vec::new();
4701            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4702                let worktree_id = *worktree_id;
4703                let worktree_handle = self.worktree_for_id(worktree_id, cx);
4704                let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4705                    Some(worktree) => worktree,
4706                    None => continue,
4707                };
4708                let worktree_abs_path = worktree.abs_path().clone();
4709
4710                let (adapter, language, server) = match self.language_servers.get(server_id) {
4711                    Some(LanguageServerState::Running {
4712                        adapter,
4713                        language,
4714                        server,
4715                        ..
4716                    }) => (adapter.clone(), language.clone(), server),
4717
4718                    _ => continue,
4719                };
4720
4721                requests.push(
4722                    server
4723                        .request::<lsp::request::WorkspaceSymbolRequest>(
4724                            lsp::WorkspaceSymbolParams {
4725                                query: query.to_string(),
4726                                ..Default::default()
4727                            },
4728                        )
4729                        .log_err()
4730                        .map(move |response| {
4731                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4732                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4733                                    flat_responses.into_iter().map(|lsp_symbol| {
4734                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4735                                    }).collect::<Vec<_>>()
4736                                }
4737                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4738                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
4739                                        let location = match lsp_symbol.location {
4740                                            OneOf::Left(location) => location,
4741                                            OneOf::Right(_) => {
4742                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4743                                                return None
4744                                            }
4745                                        };
4746                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
4747                                    }).collect::<Vec<_>>()
4748                                }
4749                            }).unwrap_or_default();
4750
4751                            (
4752                                adapter,
4753                                language,
4754                                worktree_id,
4755                                worktree_abs_path,
4756                                lsp_symbols,
4757                            )
4758                        }),
4759                );
4760            }
4761
4762            cx.spawn(move |this, mut cx| async move {
4763                let responses = futures::future::join_all(requests).await;
4764                let this = match this.upgrade() {
4765                    Some(this) => this,
4766                    None => return Ok(Vec::new()),
4767                };
4768
4769                let symbols = this.update(&mut cx, |this, cx| {
4770                    let mut symbols = Vec::new();
4771                    for (
4772                        adapter,
4773                        adapter_language,
4774                        source_worktree_id,
4775                        worktree_abs_path,
4776                        lsp_symbols,
4777                    ) in responses
4778                    {
4779                        symbols.extend(lsp_symbols.into_iter().filter_map(
4780                            |(symbol_name, symbol_kind, symbol_location)| {
4781                                let abs_path = symbol_location.uri.to_file_path().ok()?;
4782                                let mut worktree_id = source_worktree_id;
4783                                let path;
4784                                if let Some((worktree, rel_path)) =
4785                                    this.find_local_worktree(&abs_path, cx)
4786                                {
4787                                    worktree_id = worktree.read(cx).id();
4788                                    path = rel_path;
4789                                } else {
4790                                    path = relativize_path(&worktree_abs_path, &abs_path);
4791                                }
4792
4793                                let project_path = ProjectPath {
4794                                    worktree_id,
4795                                    path: path.into(),
4796                                };
4797                                let signature = this.symbol_signature(&project_path);
4798                                let adapter_language = adapter_language.clone();
4799                                let language = this
4800                                    .languages
4801                                    .language_for_file(&project_path.path, None)
4802                                    .unwrap_or_else(move |_| adapter_language);
4803                                let adapter = adapter.clone();
4804                                Some(async move {
4805                                    let language = language.await;
4806                                    let label = adapter
4807                                        .label_for_symbol(&symbol_name, symbol_kind, &language)
4808                                        .await;
4809
4810                                    Symbol {
4811                                        language_server_name: adapter.name.clone(),
4812                                        source_worktree_id,
4813                                        path: project_path,
4814                                        label: label.unwrap_or_else(|| {
4815                                            CodeLabel::plain(symbol_name.clone(), None)
4816                                        }),
4817                                        kind: symbol_kind,
4818                                        name: symbol_name,
4819                                        range: range_from_lsp(symbol_location.range),
4820                                        signature,
4821                                    }
4822                                })
4823                            },
4824                        ));
4825                    }
4826
4827                    symbols
4828                })?;
4829
4830                Ok(futures::future::join_all(symbols).await)
4831            })
4832        } else if let Some(project_id) = self.remote_id() {
4833            let request = self.client.request(proto::GetProjectSymbols {
4834                project_id,
4835                query: query.to_string(),
4836            });
4837            cx.spawn(move |this, mut cx| async move {
4838                let response = request.await?;
4839                let mut symbols = Vec::new();
4840                if let Some(this) = this.upgrade() {
4841                    let new_symbols = this.update(&mut cx, |this, _| {
4842                        response
4843                            .symbols
4844                            .into_iter()
4845                            .map(|symbol| this.deserialize_symbol(symbol))
4846                            .collect::<Vec<_>>()
4847                    })?;
4848                    symbols = futures::future::join_all(new_symbols)
4849                        .await
4850                        .into_iter()
4851                        .filter_map(|symbol| symbol.log_err())
4852                        .collect::<Vec<_>>();
4853                }
4854                Ok(symbols)
4855            })
4856        } else {
4857            Task::ready(Ok(Default::default()))
4858        }
4859    }
4860
4861    pub fn open_buffer_for_symbol(
4862        &mut self,
4863        symbol: &Symbol,
4864        cx: &mut ModelContext<Self>,
4865    ) -> Task<Result<Model<Buffer>>> {
4866        if self.is_local() {
4867            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4868                symbol.source_worktree_id,
4869                symbol.language_server_name.clone(),
4870            )) {
4871                *id
4872            } else {
4873                return Task::ready(Err(anyhow!(
4874                    "language server for worktree and language not found"
4875                )));
4876            };
4877
4878            let worktree_abs_path = if let Some(worktree_abs_path) = self
4879                .worktree_for_id(symbol.path.worktree_id, cx)
4880                .and_then(|worktree| worktree.read(cx).as_local())
4881                .map(|local_worktree| local_worktree.abs_path())
4882            {
4883                worktree_abs_path
4884            } else {
4885                return Task::ready(Err(anyhow!("worktree not found for symbol")));
4886            };
4887
4888            let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
4889            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4890                uri
4891            } else {
4892                return Task::ready(Err(anyhow!("invalid symbol path")));
4893            };
4894
4895            self.open_local_buffer_via_lsp(
4896                symbol_uri,
4897                language_server_id,
4898                symbol.language_server_name.clone(),
4899                cx,
4900            )
4901        } else if let Some(project_id) = self.remote_id() {
4902            let request = self.client.request(proto::OpenBufferForSymbol {
4903                project_id,
4904                symbol: Some(serialize_symbol(symbol)),
4905            });
4906            cx.spawn(move |this, mut cx| async move {
4907                let response = request.await?;
4908                let buffer_id = BufferId::new(response.buffer_id)?;
4909                this.update(&mut cx, |this, cx| {
4910                    this.wait_for_remote_buffer(buffer_id, cx)
4911                })?
4912                .await
4913            })
4914        } else {
4915            Task::ready(Err(anyhow!("project does not have a remote id")))
4916        }
4917    }
4918
4919    fn hover_impl(
4920        &self,
4921        buffer: &Model<Buffer>,
4922        position: PointUtf16,
4923        cx: &mut ModelContext<Self>,
4924    ) -> Task<Result<Option<Hover>>> {
4925        self.request_lsp(
4926            buffer.clone(),
4927            LanguageServerToQuery::Primary,
4928            GetHover { position },
4929            cx,
4930        )
4931    }
4932    pub fn hover<T: ToPointUtf16>(
4933        &self,
4934        buffer: &Model<Buffer>,
4935        position: T,
4936        cx: &mut ModelContext<Self>,
4937    ) -> Task<Result<Option<Hover>>> {
4938        let position = position.to_point_utf16(buffer.read(cx));
4939        self.hover_impl(buffer, position, cx)
4940    }
4941
4942    #[inline(never)]
4943    fn completions_impl(
4944        &self,
4945        buffer: &Model<Buffer>,
4946        position: PointUtf16,
4947        cx: &mut ModelContext<Self>,
4948    ) -> Task<Result<Vec<Completion>>> {
4949        if self.is_local() {
4950            let snapshot = buffer.read(cx).snapshot();
4951            let offset = position.to_offset(&snapshot);
4952            let scope = snapshot.language_scope_at(offset);
4953
4954            let server_ids: Vec<_> = self
4955                .language_servers_for_buffer(buffer.read(cx), cx)
4956                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4957                .filter(|(adapter, _)| {
4958                    scope
4959                        .as_ref()
4960                        .map(|scope| scope.language_allowed(&adapter.name))
4961                        .unwrap_or(true)
4962                })
4963                .map(|(_, server)| server.server_id())
4964                .collect();
4965
4966            let buffer = buffer.clone();
4967            cx.spawn(move |this, mut cx| async move {
4968                let mut tasks = Vec::with_capacity(server_ids.len());
4969                this.update(&mut cx, |this, cx| {
4970                    for server_id in server_ids {
4971                        tasks.push(this.request_lsp(
4972                            buffer.clone(),
4973                            LanguageServerToQuery::Other(server_id),
4974                            GetCompletions { position },
4975                            cx,
4976                        ));
4977                    }
4978                })?;
4979
4980                let mut completions = Vec::new();
4981                for task in tasks {
4982                    if let Ok(new_completions) = task.await {
4983                        completions.extend_from_slice(&new_completions);
4984                    }
4985                }
4986
4987                Ok(completions)
4988            })
4989        } else if let Some(project_id) = self.remote_id() {
4990            self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4991        } else {
4992            Task::ready(Ok(Default::default()))
4993        }
4994    }
4995    pub fn completions<T: ToOffset + ToPointUtf16>(
4996        &self,
4997        buffer: &Model<Buffer>,
4998        position: T,
4999        cx: &mut ModelContext<Self>,
5000    ) -> Task<Result<Vec<Completion>>> {
5001        let position = position.to_point_utf16(buffer.read(cx));
5002        self.completions_impl(buffer, position, cx)
5003    }
5004
5005    pub fn resolve_completions(
5006        &self,
5007        completion_indices: Vec<usize>,
5008        completions: Arc<RwLock<Box<[Completion]>>>,
5009        cx: &mut ModelContext<Self>,
5010    ) -> Task<Result<bool>> {
5011        let client = self.client();
5012        let language_registry = self.languages().clone();
5013
5014        let is_remote = self.is_remote();
5015        let project_id = self.remote_id();
5016
5017        cx.spawn(move |this, mut cx| async move {
5018            let mut did_resolve = false;
5019            if is_remote {
5020                let project_id =
5021                    project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
5022
5023                for completion_index in completion_indices {
5024                    let completions_guard = completions.read();
5025                    let completion = &completions_guard[completion_index];
5026                    if completion.documentation.is_some() {
5027                        continue;
5028                    }
5029
5030                    did_resolve = true;
5031                    let server_id = completion.server_id;
5032                    let completion = completion.lsp_completion.clone();
5033                    drop(completions_guard);
5034
5035                    Self::resolve_completion_documentation_remote(
5036                        project_id,
5037                        server_id,
5038                        completions.clone(),
5039                        completion_index,
5040                        completion,
5041                        client.clone(),
5042                        language_registry.clone(),
5043                    )
5044                    .await;
5045                }
5046            } else {
5047                for completion_index in completion_indices {
5048                    let completions_guard = completions.read();
5049                    let completion = &completions_guard[completion_index];
5050                    if completion.documentation.is_some() {
5051                        continue;
5052                    }
5053
5054                    let server_id = completion.server_id;
5055                    let completion = completion.lsp_completion.clone();
5056                    drop(completions_guard);
5057
5058                    let server = this
5059                        .read_with(&mut cx, |project, _| {
5060                            project.language_server_for_id(server_id)
5061                        })
5062                        .ok()
5063                        .flatten();
5064                    let Some(server) = server else {
5065                        continue;
5066                    };
5067
5068                    did_resolve = true;
5069                    Self::resolve_completion_documentation_local(
5070                        server,
5071                        completions.clone(),
5072                        completion_index,
5073                        completion,
5074                        language_registry.clone(),
5075                    )
5076                    .await;
5077                }
5078            }
5079
5080            Ok(did_resolve)
5081        })
5082    }
5083
5084    async fn resolve_completion_documentation_local(
5085        server: Arc<lsp::LanguageServer>,
5086        completions: Arc<RwLock<Box<[Completion]>>>,
5087        completion_index: usize,
5088        completion: lsp::CompletionItem,
5089        language_registry: Arc<LanguageRegistry>,
5090    ) {
5091        let can_resolve = server
5092            .capabilities()
5093            .completion_provider
5094            .as_ref()
5095            .and_then(|options| options.resolve_provider)
5096            .unwrap_or(false);
5097        if !can_resolve {
5098            return;
5099        }
5100
5101        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
5102        let Some(completion_item) = request.await.log_err() else {
5103            return;
5104        };
5105
5106        if let Some(lsp_documentation) = completion_item.documentation {
5107            let documentation = language::prepare_completion_documentation(
5108                &lsp_documentation,
5109                &language_registry,
5110                None, // TODO: Try to reasonably work out which language the completion is for
5111            )
5112            .await;
5113
5114            let mut completions = completions.write();
5115            let completion = &mut completions[completion_index];
5116            completion.documentation = Some(documentation);
5117        } else {
5118            let mut completions = completions.write();
5119            let completion = &mut completions[completion_index];
5120            completion.documentation = Some(Documentation::Undocumented);
5121        }
5122    }
5123
5124    async fn resolve_completion_documentation_remote(
5125        project_id: u64,
5126        server_id: LanguageServerId,
5127        completions: Arc<RwLock<Box<[Completion]>>>,
5128        completion_index: usize,
5129        completion: lsp::CompletionItem,
5130        client: Arc<Client>,
5131        language_registry: Arc<LanguageRegistry>,
5132    ) {
5133        let request = proto::ResolveCompletionDocumentation {
5134            project_id,
5135            language_server_id: server_id.0 as u64,
5136            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
5137        };
5138
5139        let Some(response) = client
5140            .request(request)
5141            .await
5142            .context("completion documentation resolve proto request")
5143            .log_err()
5144        else {
5145            return;
5146        };
5147
5148        if response.text.is_empty() {
5149            let mut completions = completions.write();
5150            let completion = &mut completions[completion_index];
5151            completion.documentation = Some(Documentation::Undocumented);
5152        }
5153
5154        let documentation = if response.is_markdown {
5155            Documentation::MultiLineMarkdown(
5156                markdown::parse_markdown(&response.text, &language_registry, None).await,
5157            )
5158        } else if response.text.lines().count() <= 1 {
5159            Documentation::SingleLine(response.text)
5160        } else {
5161            Documentation::MultiLinePlainText(response.text)
5162        };
5163
5164        let mut completions = completions.write();
5165        let completion = &mut completions[completion_index];
5166        completion.documentation = Some(documentation);
5167    }
5168
5169    pub fn apply_additional_edits_for_completion(
5170        &self,
5171        buffer_handle: Model<Buffer>,
5172        completion: Completion,
5173        push_to_history: bool,
5174        cx: &mut ModelContext<Self>,
5175    ) -> Task<Result<Option<Transaction>>> {
5176        let buffer = buffer_handle.read(cx);
5177        let buffer_id = buffer.remote_id();
5178
5179        if self.is_local() {
5180            let server_id = completion.server_id;
5181            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
5182                Some((_, server)) => server.clone(),
5183                _ => return Task::ready(Ok(Default::default())),
5184            };
5185
5186            cx.spawn(move |this, mut cx| async move {
5187                let can_resolve = lang_server
5188                    .capabilities()
5189                    .completion_provider
5190                    .as_ref()
5191                    .and_then(|options| options.resolve_provider)
5192                    .unwrap_or(false);
5193                let additional_text_edits = if can_resolve {
5194                    lang_server
5195                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
5196                        .await?
5197                        .additional_text_edits
5198                } else {
5199                    completion.lsp_completion.additional_text_edits
5200                };
5201                if let Some(edits) = additional_text_edits {
5202                    let edits = this
5203                        .update(&mut cx, |this, cx| {
5204                            this.edits_from_lsp(
5205                                &buffer_handle,
5206                                edits,
5207                                lang_server.server_id(),
5208                                None,
5209                                cx,
5210                            )
5211                        })?
5212                        .await?;
5213
5214                    buffer_handle.update(&mut cx, |buffer, cx| {
5215                        buffer.finalize_last_transaction();
5216                        buffer.start_transaction();
5217
5218                        for (range, text) in edits {
5219                            let primary = &completion.old_range;
5220                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
5221                                && primary.end.cmp(&range.start, buffer).is_ge();
5222                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
5223                                && range.end.cmp(&primary.end, buffer).is_ge();
5224
5225                            //Skip additional edits which overlap with the primary completion edit
5226                            //https://github.com/zed-industries/zed/pull/1871
5227                            if !start_within && !end_within {
5228                                buffer.edit([(range, text)], None, cx);
5229                            }
5230                        }
5231
5232                        let transaction = if buffer.end_transaction(cx).is_some() {
5233                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5234                            if !push_to_history {
5235                                buffer.forget_transaction(transaction.id);
5236                            }
5237                            Some(transaction)
5238                        } else {
5239                            None
5240                        };
5241                        Ok(transaction)
5242                    })?
5243                } else {
5244                    Ok(None)
5245                }
5246            })
5247        } else if let Some(project_id) = self.remote_id() {
5248            let client = self.client.clone();
5249            cx.spawn(move |_, mut cx| async move {
5250                let response = client
5251                    .request(proto::ApplyCompletionAdditionalEdits {
5252                        project_id,
5253                        buffer_id: buffer_id.into(),
5254                        completion: Some(language::proto::serialize_completion(&completion)),
5255                    })
5256                    .await?;
5257
5258                if let Some(transaction) = response.transaction {
5259                    let transaction = language::proto::deserialize_transaction(transaction)?;
5260                    buffer_handle
5261                        .update(&mut cx, |buffer, _| {
5262                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5263                        })?
5264                        .await?;
5265                    if push_to_history {
5266                        buffer_handle.update(&mut cx, |buffer, _| {
5267                            buffer.push_transaction(transaction.clone(), Instant::now());
5268                        })?;
5269                    }
5270                    Ok(Some(transaction))
5271                } else {
5272                    Ok(None)
5273                }
5274            })
5275        } else {
5276            Task::ready(Err(anyhow!("project does not have a remote id")))
5277        }
5278    }
5279
5280    fn code_actions_impl(
5281        &self,
5282        buffer_handle: &Model<Buffer>,
5283        range: Range<Anchor>,
5284        cx: &mut ModelContext<Self>,
5285    ) -> Task<Result<Vec<CodeAction>>> {
5286        self.request_lsp(
5287            buffer_handle.clone(),
5288            LanguageServerToQuery::Primary,
5289            GetCodeActions { range, kinds: None },
5290            cx,
5291        )
5292    }
5293
5294    pub fn code_actions<T: Clone + ToOffset>(
5295        &self,
5296        buffer_handle: &Model<Buffer>,
5297        range: Range<T>,
5298        cx: &mut ModelContext<Self>,
5299    ) -> Task<Result<Vec<CodeAction>>> {
5300        let buffer = buffer_handle.read(cx);
5301        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5302        self.code_actions_impl(buffer_handle, range, cx)
5303    }
5304
5305    pub fn apply_code_action(
5306        &self,
5307        buffer_handle: Model<Buffer>,
5308        mut action: CodeAction,
5309        push_to_history: bool,
5310        cx: &mut ModelContext<Self>,
5311    ) -> Task<Result<ProjectTransaction>> {
5312        if self.is_local() {
5313            let buffer = buffer_handle.read(cx);
5314            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
5315                self.language_server_for_buffer(buffer, action.server_id, cx)
5316            {
5317                (adapter.clone(), server.clone())
5318            } else {
5319                return Task::ready(Ok(Default::default()));
5320            };
5321            let range = action.range.to_point_utf16(buffer);
5322
5323            cx.spawn(move |this, mut cx| async move {
5324                if let Some(lsp_range) = action
5325                    .lsp_action
5326                    .data
5327                    .as_mut()
5328                    .and_then(|d| d.get_mut("codeActionParams"))
5329                    .and_then(|d| d.get_mut("range"))
5330                {
5331                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
5332                    action.lsp_action = lang_server
5333                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
5334                        .await?;
5335                } else {
5336                    let actions = this
5337                        .update(&mut cx, |this, cx| {
5338                            this.code_actions(&buffer_handle, action.range, cx)
5339                        })?
5340                        .await?;
5341                    action.lsp_action = actions
5342                        .into_iter()
5343                        .find(|a| a.lsp_action.title == action.lsp_action.title)
5344                        .ok_or_else(|| anyhow!("code action is outdated"))?
5345                        .lsp_action;
5346                }
5347
5348                if let Some(edit) = action.lsp_action.edit {
5349                    if edit.changes.is_some() || edit.document_changes.is_some() {
5350                        return Self::deserialize_workspace_edit(
5351                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5352                            edit,
5353                            push_to_history,
5354                            lsp_adapter.clone(),
5355                            lang_server.clone(),
5356                            &mut cx,
5357                        )
5358                        .await;
5359                    }
5360                }
5361
5362                if let Some(command) = action.lsp_action.command {
5363                    this.update(&mut cx, |this, _| {
5364                        this.last_workspace_edits_by_language_server
5365                            .remove(&lang_server.server_id());
5366                    })?;
5367
5368                    let result = lang_server
5369                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5370                            command: command.command,
5371                            arguments: command.arguments.unwrap_or_default(),
5372                            ..Default::default()
5373                        })
5374                        .await;
5375
5376                    if let Err(err) = result {
5377                        // TODO: LSP ERROR
5378                        return Err(err);
5379                    }
5380
5381                    return Ok(this.update(&mut cx, |this, _| {
5382                        this.last_workspace_edits_by_language_server
5383                            .remove(&lang_server.server_id())
5384                            .unwrap_or_default()
5385                    })?);
5386                }
5387
5388                Ok(ProjectTransaction::default())
5389            })
5390        } else if let Some(project_id) = self.remote_id() {
5391            let client = self.client.clone();
5392            let request = proto::ApplyCodeAction {
5393                project_id,
5394                buffer_id: buffer_handle.read(cx).remote_id().into(),
5395                action: Some(language::proto::serialize_code_action(&action)),
5396            };
5397            cx.spawn(move |this, mut cx| async move {
5398                let response = client
5399                    .request(request)
5400                    .await?
5401                    .transaction
5402                    .ok_or_else(|| anyhow!("missing transaction"))?;
5403                this.update(&mut cx, |this, cx| {
5404                    this.deserialize_project_transaction(response, push_to_history, cx)
5405                })?
5406                .await
5407            })
5408        } else {
5409            Task::ready(Err(anyhow!("project does not have a remote id")))
5410        }
5411    }
5412
5413    fn apply_on_type_formatting(
5414        &self,
5415        buffer: Model<Buffer>,
5416        position: Anchor,
5417        trigger: String,
5418        cx: &mut ModelContext<Self>,
5419    ) -> Task<Result<Option<Transaction>>> {
5420        if self.is_local() {
5421            cx.spawn(move |this, mut cx| async move {
5422                // Do not allow multiple concurrent formatting requests for the
5423                // same buffer.
5424                this.update(&mut cx, |this, cx| {
5425                    this.buffers_being_formatted
5426                        .insert(buffer.read(cx).remote_id())
5427                })?;
5428
5429                let _cleanup = defer({
5430                    let this = this.clone();
5431                    let mut cx = cx.clone();
5432                    let closure_buffer = buffer.clone();
5433                    move || {
5434                        this.update(&mut cx, |this, cx| {
5435                            this.buffers_being_formatted
5436                                .remove(&closure_buffer.read(cx).remote_id());
5437                        })
5438                        .ok();
5439                    }
5440                });
5441
5442                buffer
5443                    .update(&mut cx, |buffer, _| {
5444                        buffer.wait_for_edits(Some(position.timestamp))
5445                    })?
5446                    .await?;
5447                this.update(&mut cx, |this, cx| {
5448                    let position = position.to_point_utf16(buffer.read(cx));
5449                    this.on_type_format(buffer, position, trigger, false, cx)
5450                })?
5451                .await
5452            })
5453        } else if let Some(project_id) = self.remote_id() {
5454            let client = self.client.clone();
5455            let request = proto::OnTypeFormatting {
5456                project_id,
5457                buffer_id: buffer.read(cx).remote_id().into(),
5458                position: Some(serialize_anchor(&position)),
5459                trigger,
5460                version: serialize_version(&buffer.read(cx).version()),
5461            };
5462            cx.spawn(move |_, _| async move {
5463                client
5464                    .request(request)
5465                    .await?
5466                    .transaction
5467                    .map(language::proto::deserialize_transaction)
5468                    .transpose()
5469            })
5470        } else {
5471            Task::ready(Err(anyhow!("project does not have a remote id")))
5472        }
5473    }
5474
5475    async fn deserialize_edits(
5476        this: Model<Self>,
5477        buffer_to_edit: Model<Buffer>,
5478        edits: Vec<lsp::TextEdit>,
5479        push_to_history: bool,
5480        _: Arc<CachedLspAdapter>,
5481        language_server: Arc<LanguageServer>,
5482        cx: &mut AsyncAppContext,
5483    ) -> Result<Option<Transaction>> {
5484        let edits = this
5485            .update(cx, |this, cx| {
5486                this.edits_from_lsp(
5487                    &buffer_to_edit,
5488                    edits,
5489                    language_server.server_id(),
5490                    None,
5491                    cx,
5492                )
5493            })?
5494            .await?;
5495
5496        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5497            buffer.finalize_last_transaction();
5498            buffer.start_transaction();
5499            for (range, text) in edits {
5500                buffer.edit([(range, text)], None, cx);
5501            }
5502
5503            if buffer.end_transaction(cx).is_some() {
5504                let transaction = buffer.finalize_last_transaction().unwrap().clone();
5505                if !push_to_history {
5506                    buffer.forget_transaction(transaction.id);
5507                }
5508                Some(transaction)
5509            } else {
5510                None
5511            }
5512        })?;
5513
5514        Ok(transaction)
5515    }
5516
5517    async fn deserialize_workspace_edit(
5518        this: Model<Self>,
5519        edit: lsp::WorkspaceEdit,
5520        push_to_history: bool,
5521        lsp_adapter: Arc<CachedLspAdapter>,
5522        language_server: Arc<LanguageServer>,
5523        cx: &mut AsyncAppContext,
5524    ) -> Result<ProjectTransaction> {
5525        let fs = this.update(cx, |this, _| this.fs.clone())?;
5526        let mut operations = Vec::new();
5527        if let Some(document_changes) = edit.document_changes {
5528            match document_changes {
5529                lsp::DocumentChanges::Edits(edits) => {
5530                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5531                }
5532                lsp::DocumentChanges::Operations(ops) => operations = ops,
5533            }
5534        } else if let Some(changes) = edit.changes {
5535            operations.extend(changes.into_iter().map(|(uri, edits)| {
5536                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5537                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5538                        uri,
5539                        version: None,
5540                    },
5541                    edits: edits.into_iter().map(OneOf::Left).collect(),
5542                })
5543            }));
5544        }
5545
5546        let mut project_transaction = ProjectTransaction::default();
5547        for operation in operations {
5548            match operation {
5549                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5550                    let abs_path = op
5551                        .uri
5552                        .to_file_path()
5553                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5554
5555                    if let Some(parent_path) = abs_path.parent() {
5556                        fs.create_dir(parent_path).await?;
5557                    }
5558                    if abs_path.ends_with("/") {
5559                        fs.create_dir(&abs_path).await?;
5560                    } else {
5561                        fs.create_file(
5562                            &abs_path,
5563                            op.options
5564                                .map(|options| fs::CreateOptions {
5565                                    overwrite: options.overwrite.unwrap_or(false),
5566                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5567                                })
5568                                .unwrap_or_default(),
5569                        )
5570                        .await?;
5571                    }
5572                }
5573
5574                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5575                    let source_abs_path = op
5576                        .old_uri
5577                        .to_file_path()
5578                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5579                    let target_abs_path = op
5580                        .new_uri
5581                        .to_file_path()
5582                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5583                    fs.rename(
5584                        &source_abs_path,
5585                        &target_abs_path,
5586                        op.options
5587                            .map(|options| fs::RenameOptions {
5588                                overwrite: options.overwrite.unwrap_or(false),
5589                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5590                            })
5591                            .unwrap_or_default(),
5592                    )
5593                    .await?;
5594                }
5595
5596                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5597                    let abs_path = op
5598                        .uri
5599                        .to_file_path()
5600                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5601                    let options = op
5602                        .options
5603                        .map(|options| fs::RemoveOptions {
5604                            recursive: options.recursive.unwrap_or(false),
5605                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5606                        })
5607                        .unwrap_or_default();
5608                    if abs_path.ends_with("/") {
5609                        fs.remove_dir(&abs_path, options).await?;
5610                    } else {
5611                        fs.remove_file(&abs_path, options).await?;
5612                    }
5613                }
5614
5615                lsp::DocumentChangeOperation::Edit(op) => {
5616                    let buffer_to_edit = this
5617                        .update(cx, |this, cx| {
5618                            this.open_local_buffer_via_lsp(
5619                                op.text_document.uri,
5620                                language_server.server_id(),
5621                                lsp_adapter.name.clone(),
5622                                cx,
5623                            )
5624                        })?
5625                        .await?;
5626
5627                    let edits = this
5628                        .update(cx, |this, cx| {
5629                            let edits = op.edits.into_iter().map(|edit| match edit {
5630                                OneOf::Left(edit) => edit,
5631                                OneOf::Right(edit) => edit.text_edit,
5632                            });
5633                            this.edits_from_lsp(
5634                                &buffer_to_edit,
5635                                edits,
5636                                language_server.server_id(),
5637                                op.text_document.version,
5638                                cx,
5639                            )
5640                        })?
5641                        .await?;
5642
5643                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5644                        buffer.finalize_last_transaction();
5645                        buffer.start_transaction();
5646                        for (range, text) in edits {
5647                            buffer.edit([(range, text)], None, cx);
5648                        }
5649                        let transaction = if buffer.end_transaction(cx).is_some() {
5650                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5651                            if !push_to_history {
5652                                buffer.forget_transaction(transaction.id);
5653                            }
5654                            Some(transaction)
5655                        } else {
5656                            None
5657                        };
5658
5659                        transaction
5660                    })?;
5661                    if let Some(transaction) = transaction {
5662                        project_transaction.0.insert(buffer_to_edit, transaction);
5663                    }
5664                }
5665            }
5666        }
5667
5668        Ok(project_transaction)
5669    }
5670
5671    fn prepare_rename_impl(
5672        &self,
5673        buffer: Model<Buffer>,
5674        position: PointUtf16,
5675        cx: &mut ModelContext<Self>,
5676    ) -> Task<Result<Option<Range<Anchor>>>> {
5677        self.request_lsp(
5678            buffer,
5679            LanguageServerToQuery::Primary,
5680            PrepareRename { position },
5681            cx,
5682        )
5683    }
5684    pub fn prepare_rename<T: ToPointUtf16>(
5685        &self,
5686        buffer: Model<Buffer>,
5687        position: T,
5688        cx: &mut ModelContext<Self>,
5689    ) -> Task<Result<Option<Range<Anchor>>>> {
5690        let position = position.to_point_utf16(buffer.read(cx));
5691        self.prepare_rename_impl(buffer, position, cx)
5692    }
5693
5694    fn perform_rename_impl(
5695        &self,
5696        buffer: Model<Buffer>,
5697        position: PointUtf16,
5698        new_name: String,
5699        push_to_history: bool,
5700        cx: &mut ModelContext<Self>,
5701    ) -> Task<Result<ProjectTransaction>> {
5702        let position = position.to_point_utf16(buffer.read(cx));
5703        self.request_lsp(
5704            buffer,
5705            LanguageServerToQuery::Primary,
5706            PerformRename {
5707                position,
5708                new_name,
5709                push_to_history,
5710            },
5711            cx,
5712        )
5713    }
5714    pub fn perform_rename<T: ToPointUtf16>(
5715        &self,
5716        buffer: Model<Buffer>,
5717        position: T,
5718        new_name: String,
5719        push_to_history: bool,
5720        cx: &mut ModelContext<Self>,
5721    ) -> Task<Result<ProjectTransaction>> {
5722        let position = position.to_point_utf16(buffer.read(cx));
5723        self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
5724    }
5725
5726    pub fn on_type_format_impl(
5727        &self,
5728        buffer: Model<Buffer>,
5729        position: PointUtf16,
5730        trigger: String,
5731        push_to_history: bool,
5732        cx: &mut ModelContext<Self>,
5733    ) -> Task<Result<Option<Transaction>>> {
5734        let tab_size = buffer.update(cx, |buffer, cx| {
5735            language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
5736        });
5737        self.request_lsp(
5738            buffer.clone(),
5739            LanguageServerToQuery::Primary,
5740            OnTypeFormatting {
5741                position,
5742                trigger,
5743                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5744                push_to_history,
5745            },
5746            cx,
5747        )
5748    }
5749
5750    pub fn on_type_format<T: ToPointUtf16>(
5751        &self,
5752        buffer: Model<Buffer>,
5753        position: T,
5754        trigger: String,
5755        push_to_history: bool,
5756        cx: &mut ModelContext<Self>,
5757    ) -> Task<Result<Option<Transaction>>> {
5758        let position = position.to_point_utf16(buffer.read(cx));
5759        self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
5760    }
5761
5762    pub fn inlay_hints<T: ToOffset>(
5763        &self,
5764        buffer_handle: Model<Buffer>,
5765        range: Range<T>,
5766        cx: &mut ModelContext<Self>,
5767    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5768        let buffer = buffer_handle.read(cx);
5769        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5770        self.inlay_hints_impl(buffer_handle, range, cx)
5771    }
5772    fn inlay_hints_impl(
5773        &self,
5774        buffer_handle: Model<Buffer>,
5775        range: Range<Anchor>,
5776        cx: &mut ModelContext<Self>,
5777    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5778        let buffer = buffer_handle.read(cx);
5779        let range_start = range.start;
5780        let range_end = range.end;
5781        let buffer_id = buffer.remote_id().into();
5782        let lsp_request = InlayHints { range };
5783
5784        if self.is_local() {
5785            let lsp_request_task = self.request_lsp(
5786                buffer_handle.clone(),
5787                LanguageServerToQuery::Primary,
5788                lsp_request,
5789                cx,
5790            );
5791            cx.spawn(move |_, mut cx| async move {
5792                buffer_handle
5793                    .update(&mut cx, |buffer, _| {
5794                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5795                    })?
5796                    .await
5797                    .context("waiting for inlay hint request range edits")?;
5798                lsp_request_task.await.context("inlay hints LSP request")
5799            })
5800        } else if let Some(project_id) = self.remote_id() {
5801            let client = self.client.clone();
5802            let request = proto::InlayHints {
5803                project_id,
5804                buffer_id,
5805                start: Some(serialize_anchor(&range_start)),
5806                end: Some(serialize_anchor(&range_end)),
5807                version: serialize_version(&buffer_handle.read(cx).version()),
5808            };
5809            cx.spawn(move |project, cx| async move {
5810                let response = client
5811                    .request(request)
5812                    .await
5813                    .context("inlay hints proto request")?;
5814                LspCommand::response_from_proto(
5815                    lsp_request,
5816                    response,
5817                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5818                    buffer_handle.clone(),
5819                    cx.clone(),
5820                )
5821                .await
5822                .context("inlay hints proto response conversion")
5823            })
5824        } else {
5825            Task::ready(Err(anyhow!("project does not have a remote id")))
5826        }
5827    }
5828
5829    pub fn resolve_inlay_hint(
5830        &self,
5831        hint: InlayHint,
5832        buffer_handle: Model<Buffer>,
5833        server_id: LanguageServerId,
5834        cx: &mut ModelContext<Self>,
5835    ) -> Task<anyhow::Result<InlayHint>> {
5836        if self.is_local() {
5837            let buffer = buffer_handle.read(cx);
5838            let (_, lang_server) = if let Some((adapter, server)) =
5839                self.language_server_for_buffer(buffer, server_id, cx)
5840            {
5841                (adapter.clone(), server.clone())
5842            } else {
5843                return Task::ready(Ok(hint));
5844            };
5845            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5846                return Task::ready(Ok(hint));
5847            }
5848
5849            let buffer_snapshot = buffer.snapshot();
5850            cx.spawn(move |_, mut cx| async move {
5851                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5852                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5853                );
5854                let resolved_hint = resolve_task
5855                    .await
5856                    .context("inlay hint resolve LSP request")?;
5857                let resolved_hint = InlayHints::lsp_to_project_hint(
5858                    resolved_hint,
5859                    &buffer_handle,
5860                    server_id,
5861                    ResolveState::Resolved,
5862                    false,
5863                    &mut cx,
5864                )
5865                .await?;
5866                Ok(resolved_hint)
5867            })
5868        } else if let Some(project_id) = self.remote_id() {
5869            let client = self.client.clone();
5870            let request = proto::ResolveInlayHint {
5871                project_id,
5872                buffer_id: buffer_handle.read(cx).remote_id().into(),
5873                language_server_id: server_id.0 as u64,
5874                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5875            };
5876            cx.spawn(move |_, _| async move {
5877                let response = client
5878                    .request(request)
5879                    .await
5880                    .context("inlay hints proto request")?;
5881                match response.hint {
5882                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5883                        .context("inlay hints proto resolve response conversion"),
5884                    None => Ok(hint),
5885                }
5886            })
5887        } else {
5888            Task::ready(Err(anyhow!("project does not have a remote id")))
5889        }
5890    }
5891
5892    #[allow(clippy::type_complexity)]
5893    pub fn search(
5894        &self,
5895        query: SearchQuery,
5896        cx: &mut ModelContext<Self>,
5897    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5898        if self.is_local() {
5899            self.search_local(query, cx)
5900        } else if let Some(project_id) = self.remote_id() {
5901            let (tx, rx) = smol::channel::unbounded();
5902            let request = self.client.request(query.to_proto(project_id));
5903            cx.spawn(move |this, mut cx| async move {
5904                let response = request.await?;
5905                let mut result = HashMap::default();
5906                for location in response.locations {
5907                    let buffer_id = BufferId::new(location.buffer_id)?;
5908                    let target_buffer = this
5909                        .update(&mut cx, |this, cx| {
5910                            this.wait_for_remote_buffer(buffer_id, cx)
5911                        })?
5912                        .await?;
5913                    let start = location
5914                        .start
5915                        .and_then(deserialize_anchor)
5916                        .ok_or_else(|| anyhow!("missing target start"))?;
5917                    let end = location
5918                        .end
5919                        .and_then(deserialize_anchor)
5920                        .ok_or_else(|| anyhow!("missing target end"))?;
5921                    result
5922                        .entry(target_buffer)
5923                        .or_insert(Vec::new())
5924                        .push(start..end)
5925                }
5926                for (buffer, ranges) in result {
5927                    let _ = tx.send((buffer, ranges)).await;
5928                }
5929                Result::<(), anyhow::Error>::Ok(())
5930            })
5931            .detach_and_log_err(cx);
5932            rx
5933        } else {
5934            unimplemented!();
5935        }
5936    }
5937
5938    pub fn search_local(
5939        &self,
5940        query: SearchQuery,
5941        cx: &mut ModelContext<Self>,
5942    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5943        // Local search is split into several phases.
5944        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5945        // and the second phase that finds positions of all the matches found in the candidate files.
5946        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5947        //
5948        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5949        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5950        //
5951        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5952        //    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
5953        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5954        // 2. At this point, we have a list of all potentially matching buffers/files.
5955        //    We sort that list by buffer path - this list is retained for later use.
5956        //    We ensure that all buffers are now opened and available in project.
5957        // 3. We run a scan over all the candidate buffers on multiple background threads.
5958        //    We cannot assume that there will even be a match - while at least one match
5959        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5960        //    There is also an auxiliary background thread responsible for result gathering.
5961        //    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),
5962        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5963        //    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
5964        //    entry - which might already be available thanks to out-of-order processing.
5965        //
5966        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5967        // 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.
5968        // 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
5969        // in face of constantly updating list of sorted matches.
5970        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5971        let snapshots = self
5972            .visible_worktrees(cx)
5973            .filter_map(|tree| {
5974                let tree = tree.read(cx).as_local()?;
5975                Some(tree.snapshot())
5976            })
5977            .collect::<Vec<_>>();
5978
5979        let background = cx.background_executor().clone();
5980        let path_count: usize = snapshots
5981            .iter()
5982            .map(|s| {
5983                if query.include_ignored() {
5984                    s.file_count()
5985                } else {
5986                    s.visible_file_count()
5987                }
5988            })
5989            .sum();
5990        if path_count == 0 {
5991            let (_, rx) = smol::channel::bounded(1024);
5992            return rx;
5993        }
5994        let workers = background.num_cpus().min(path_count);
5995        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5996        let mut unnamed_files = vec![];
5997        let opened_buffers = self
5998            .opened_buffers
5999            .iter()
6000            .filter_map(|(_, b)| {
6001                let buffer = b.upgrade()?;
6002                let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
6003                    let is_ignored = buffer
6004                        .project_path(cx)
6005                        .and_then(|path| self.entry_for_path(&path, cx))
6006                        .map_or(false, |entry| entry.is_ignored);
6007                    (is_ignored, buffer.snapshot())
6008                });
6009                if is_ignored && !query.include_ignored() {
6010                    return None;
6011                } else if let Some(path) = snapshot.file().map(|file| file.path()) {
6012                    Some((path.clone(), (buffer, snapshot)))
6013                } else {
6014                    unnamed_files.push(buffer);
6015                    None
6016                }
6017            })
6018            .collect();
6019        cx.background_executor()
6020            .spawn(Self::background_search(
6021                unnamed_files,
6022                opened_buffers,
6023                cx.background_executor().clone(),
6024                self.fs.clone(),
6025                workers,
6026                query.clone(),
6027                path_count,
6028                snapshots,
6029                matching_paths_tx,
6030            ))
6031            .detach();
6032
6033        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
6034        let background = cx.background_executor().clone();
6035        let (result_tx, result_rx) = smol::channel::bounded(1024);
6036        cx.background_executor()
6037            .spawn(async move {
6038                let Ok(buffers) = buffers.await else {
6039                    return;
6040                };
6041
6042                let buffers_len = buffers.len();
6043                if buffers_len == 0 {
6044                    return;
6045                }
6046                let query = &query;
6047                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
6048                background
6049                    .scoped(|scope| {
6050                        #[derive(Clone)]
6051                        struct FinishedStatus {
6052                            entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
6053                            buffer_index: SearchMatchCandidateIndex,
6054                        }
6055
6056                        for _ in 0..workers {
6057                            let finished_tx = finished_tx.clone();
6058                            let mut buffers_rx = buffers_rx.clone();
6059                            scope.spawn(async move {
6060                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
6061                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
6062                                    {
6063                                        if query.file_matches(
6064                                            snapshot.file().map(|file| file.path().as_ref()),
6065                                        ) {
6066                                            query
6067                                                .search(snapshot, None)
6068                                                .await
6069                                                .iter()
6070                                                .map(|range| {
6071                                                    snapshot.anchor_before(range.start)
6072                                                        ..snapshot.anchor_after(range.end)
6073                                                })
6074                                                .collect()
6075                                        } else {
6076                                            Vec::new()
6077                                        }
6078                                    } else {
6079                                        Vec::new()
6080                                    };
6081
6082                                    let status = if !buffer_matches.is_empty() {
6083                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
6084                                            Some((buffer.clone(), buffer_matches))
6085                                        } else {
6086                                            None
6087                                        };
6088                                        FinishedStatus {
6089                                            entry,
6090                                            buffer_index,
6091                                        }
6092                                    } else {
6093                                        FinishedStatus {
6094                                            entry: None,
6095                                            buffer_index,
6096                                        }
6097                                    };
6098                                    if finished_tx.send(status).await.is_err() {
6099                                        break;
6100                                    }
6101                                }
6102                            });
6103                        }
6104                        // Report sorted matches
6105                        scope.spawn(async move {
6106                            let mut current_index = 0;
6107                            let mut scratch = vec![None; buffers_len];
6108                            while let Some(status) = finished_rx.next().await {
6109                                debug_assert!(
6110                                    scratch[status.buffer_index].is_none(),
6111                                    "Got match status of position {} twice",
6112                                    status.buffer_index
6113                                );
6114                                let index = status.buffer_index;
6115                                scratch[index] = Some(status);
6116                                while current_index < buffers_len {
6117                                    let Some(current_entry) = scratch[current_index].take() else {
6118                                        // We intentionally **do not** increment `current_index` here. When next element arrives
6119                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
6120                                        // this time.
6121                                        break;
6122                                    };
6123                                    if let Some(entry) = current_entry.entry {
6124                                        result_tx.send(entry).await.log_err();
6125                                    }
6126                                    current_index += 1;
6127                                }
6128                                if current_index == buffers_len {
6129                                    break;
6130                                }
6131                            }
6132                        });
6133                    })
6134                    .await;
6135            })
6136            .detach();
6137        result_rx
6138    }
6139
6140    /// Pick paths that might potentially contain a match of a given search query.
6141    async fn background_search(
6142        unnamed_buffers: Vec<Model<Buffer>>,
6143        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
6144        executor: BackgroundExecutor,
6145        fs: Arc<dyn Fs>,
6146        workers: usize,
6147        query: SearchQuery,
6148        path_count: usize,
6149        snapshots: Vec<LocalSnapshot>,
6150        matching_paths_tx: Sender<SearchMatchCandidate>,
6151    ) {
6152        let fs = &fs;
6153        let query = &query;
6154        let matching_paths_tx = &matching_paths_tx;
6155        let snapshots = &snapshots;
6156        let paths_per_worker = (path_count + workers - 1) / workers;
6157        for buffer in unnamed_buffers {
6158            matching_paths_tx
6159                .send(SearchMatchCandidate::OpenBuffer {
6160                    buffer: buffer.clone(),
6161                    path: None,
6162                })
6163                .await
6164                .log_err();
6165        }
6166        for (path, (buffer, _)) in opened_buffers.iter() {
6167            matching_paths_tx
6168                .send(SearchMatchCandidate::OpenBuffer {
6169                    buffer: buffer.clone(),
6170                    path: Some(path.clone()),
6171                })
6172                .await
6173                .log_err();
6174        }
6175        executor
6176            .scoped(|scope| {
6177                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
6178
6179                for worker_ix in 0..workers {
6180                    let worker_start_ix = worker_ix * paths_per_worker;
6181                    let worker_end_ix = worker_start_ix + paths_per_worker;
6182                    let unnamed_buffers = opened_buffers.clone();
6183                    let limiter = Arc::clone(&max_concurrent_workers);
6184                    scope.spawn(async move {
6185                        let _guard = limiter.acquire().await;
6186                        let mut snapshot_start_ix = 0;
6187                        let mut abs_path = PathBuf::new();
6188                        for snapshot in snapshots {
6189                            let snapshot_end_ix = snapshot_start_ix
6190                                + if query.include_ignored() {
6191                                    snapshot.file_count()
6192                                } else {
6193                                    snapshot.visible_file_count()
6194                                };
6195                            if worker_end_ix <= snapshot_start_ix {
6196                                break;
6197                            } else if worker_start_ix > snapshot_end_ix {
6198                                snapshot_start_ix = snapshot_end_ix;
6199                                continue;
6200                            } else {
6201                                let start_in_snapshot =
6202                                    worker_start_ix.saturating_sub(snapshot_start_ix);
6203                                let end_in_snapshot =
6204                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
6205
6206                                for entry in snapshot
6207                                    .files(query.include_ignored(), start_in_snapshot)
6208                                    .take(end_in_snapshot - start_in_snapshot)
6209                                {
6210                                    if matching_paths_tx.is_closed() {
6211                                        break;
6212                                    }
6213                                    if unnamed_buffers.contains_key(&entry.path) {
6214                                        continue;
6215                                    }
6216                                    let matches = if query.file_matches(Some(&entry.path)) {
6217                                        abs_path.clear();
6218                                        abs_path.push(&snapshot.abs_path());
6219                                        abs_path.push(&entry.path);
6220                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
6221                                        {
6222                                            query.detect(file).unwrap_or(false)
6223                                        } else {
6224                                            false
6225                                        }
6226                                    } else {
6227                                        false
6228                                    };
6229
6230                                    if matches {
6231                                        let project_path = SearchMatchCandidate::Path {
6232                                            worktree_id: snapshot.id(),
6233                                            path: entry.path.clone(),
6234                                            is_ignored: entry.is_ignored,
6235                                        };
6236                                        if matching_paths_tx.send(project_path).await.is_err() {
6237                                            break;
6238                                        }
6239                                    }
6240                                }
6241
6242                                snapshot_start_ix = snapshot_end_ix;
6243                            }
6244                        }
6245                    });
6246                }
6247
6248                if query.include_ignored() {
6249                    for snapshot in snapshots {
6250                        for ignored_entry in snapshot
6251                            .entries(query.include_ignored())
6252                            .filter(|e| e.is_ignored)
6253                        {
6254                            let limiter = Arc::clone(&max_concurrent_workers);
6255                            scope.spawn(async move {
6256                                let _guard = limiter.acquire().await;
6257                                let mut ignored_paths_to_process =
6258                                    VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
6259                                while let Some(ignored_abs_path) =
6260                                    ignored_paths_to_process.pop_front()
6261                                {
6262                                    if let Some(fs_metadata) = fs
6263                                        .metadata(&ignored_abs_path)
6264                                        .await
6265                                        .with_context(|| {
6266                                            format!("fetching fs metadata for {ignored_abs_path:?}")
6267                                        })
6268                                        .log_err()
6269                                        .flatten()
6270                                    {
6271                                        if fs_metadata.is_dir {
6272                                            if let Some(mut subfiles) = fs
6273                                                .read_dir(&ignored_abs_path)
6274                                                .await
6275                                                .with_context(|| {
6276                                                    format!(
6277                                                        "listing ignored path {ignored_abs_path:?}"
6278                                                    )
6279                                                })
6280                                                .log_err()
6281                                            {
6282                                                while let Some(subfile) = subfiles.next().await {
6283                                                    if let Some(subfile) = subfile.log_err() {
6284                                                        ignored_paths_to_process.push_back(subfile);
6285                                                    }
6286                                                }
6287                                            }
6288                                        } else if !fs_metadata.is_symlink {
6289                                            if !query.file_matches(Some(&ignored_abs_path))
6290                                                || snapshot.is_path_excluded(
6291                                                    ignored_entry.path.to_path_buf(),
6292                                                )
6293                                            {
6294                                                continue;
6295                                            }
6296                                            let matches = if let Some(file) = fs
6297                                                .open_sync(&ignored_abs_path)
6298                                                .await
6299                                                .with_context(|| {
6300                                                    format!(
6301                                                        "Opening ignored path {ignored_abs_path:?}"
6302                                                    )
6303                                                })
6304                                                .log_err()
6305                                            {
6306                                                query.detect(file).unwrap_or(false)
6307                                            } else {
6308                                                false
6309                                            };
6310                                            if matches {
6311                                                let project_path = SearchMatchCandidate::Path {
6312                                                    worktree_id: snapshot.id(),
6313                                                    path: Arc::from(
6314                                                        ignored_abs_path
6315                                                            .strip_prefix(snapshot.abs_path())
6316                                                            .expect(
6317                                                                "scanning worktree-related files",
6318                                                            ),
6319                                                    ),
6320                                                    is_ignored: true,
6321                                                };
6322                                                if matching_paths_tx
6323                                                    .send(project_path)
6324                                                    .await
6325                                                    .is_err()
6326                                                {
6327                                                    return;
6328                                                }
6329                                            }
6330                                        }
6331                                    }
6332                                }
6333                            });
6334                        }
6335                    }
6336                }
6337            })
6338            .await;
6339    }
6340
6341    pub fn request_lsp<R: LspCommand>(
6342        &self,
6343        buffer_handle: Model<Buffer>,
6344        server: LanguageServerToQuery,
6345        request: R,
6346        cx: &mut ModelContext<Self>,
6347    ) -> Task<Result<R::Response>>
6348    where
6349        <R::LspRequest as lsp::request::Request>::Result: Send,
6350        <R::LspRequest as lsp::request::Request>::Params: Send,
6351    {
6352        let buffer = buffer_handle.read(cx);
6353        if self.is_local() {
6354            let language_server = match server {
6355                LanguageServerToQuery::Primary => {
6356                    match self.primary_language_server_for_buffer(buffer, cx) {
6357                        Some((_, server)) => Some(Arc::clone(server)),
6358                        None => return Task::ready(Ok(Default::default())),
6359                    }
6360                }
6361                LanguageServerToQuery::Other(id) => self
6362                    .language_server_for_buffer(buffer, id, cx)
6363                    .map(|(_, server)| Arc::clone(server)),
6364            };
6365            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
6366            if let (Some(file), Some(language_server)) = (file, language_server) {
6367                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
6368                return cx.spawn(move |this, cx| async move {
6369                    if !request.check_capabilities(language_server.capabilities()) {
6370                        return Ok(Default::default());
6371                    }
6372
6373                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
6374                    let response = match result {
6375                        Ok(response) => response,
6376
6377                        Err(err) => {
6378                            log::warn!(
6379                                "Generic lsp request to {} failed: {}",
6380                                language_server.name(),
6381                                err
6382                            );
6383                            return Err(err);
6384                        }
6385                    };
6386
6387                    request
6388                        .response_from_lsp(
6389                            response,
6390                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6391                            buffer_handle,
6392                            language_server.server_id(),
6393                            cx,
6394                        )
6395                        .await
6396                });
6397            }
6398        } else if let Some(project_id) = self.remote_id() {
6399            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6400        }
6401
6402        Task::ready(Ok(Default::default()))
6403    }
6404
6405    fn send_lsp_proto_request<R: LspCommand>(
6406        &self,
6407        buffer: Model<Buffer>,
6408        project_id: u64,
6409        request: R,
6410        cx: &mut ModelContext<'_, Project>,
6411    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6412        let rpc = self.client.clone();
6413        let message = request.to_proto(project_id, buffer.read(cx));
6414        cx.spawn(move |this, mut cx| async move {
6415            // Ensure the project is still alive by the time the task
6416            // is scheduled.
6417            this.upgrade().context("project dropped")?;
6418            let response = rpc.request(message).await?;
6419            let this = this.upgrade().context("project dropped")?;
6420            if this.update(&mut cx, |this, _| this.is_disconnected())? {
6421                Err(anyhow!("disconnected before completing request"))
6422            } else {
6423                request
6424                    .response_from_proto(response, this, buffer, cx)
6425                    .await
6426            }
6427        })
6428    }
6429
6430    fn sort_candidates_and_open_buffers(
6431        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
6432        cx: &mut ModelContext<Self>,
6433    ) -> (
6434        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
6435        Receiver<(
6436            Option<(Model<Buffer>, BufferSnapshot)>,
6437            SearchMatchCandidateIndex,
6438        )>,
6439    ) {
6440        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
6441        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
6442        cx.spawn(move |this, cx| async move {
6443            let mut buffers = Vec::new();
6444            let mut ignored_buffers = Vec::new();
6445            while let Some(entry) = matching_paths_rx.next().await {
6446                if matches!(
6447                    entry,
6448                    SearchMatchCandidate::Path {
6449                        is_ignored: true,
6450                        ..
6451                    }
6452                ) {
6453                    ignored_buffers.push(entry);
6454                } else {
6455                    buffers.push(entry);
6456                }
6457            }
6458            buffers.sort_by_key(|candidate| candidate.path());
6459            ignored_buffers.sort_by_key(|candidate| candidate.path());
6460            buffers.extend(ignored_buffers);
6461            let matching_paths = buffers.clone();
6462            let _ = sorted_buffers_tx.send(buffers);
6463            for (index, candidate) in matching_paths.into_iter().enumerate() {
6464                if buffers_tx.is_closed() {
6465                    break;
6466                }
6467                let this = this.clone();
6468                let buffers_tx = buffers_tx.clone();
6469                cx.spawn(move |mut cx| async move {
6470                    let buffer = match candidate {
6471                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6472                        SearchMatchCandidate::Path {
6473                            worktree_id, path, ..
6474                        } => this
6475                            .update(&mut cx, |this, cx| {
6476                                this.open_buffer((worktree_id, path), cx)
6477                            })?
6478                            .await
6479                            .log_err(),
6480                    };
6481                    if let Some(buffer) = buffer {
6482                        let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6483                        buffers_tx
6484                            .send((Some((buffer, snapshot)), index))
6485                            .await
6486                            .log_err();
6487                    } else {
6488                        buffers_tx.send((None, index)).await.log_err();
6489                    }
6490
6491                    Ok::<_, anyhow::Error>(())
6492                })
6493                .detach();
6494            }
6495        })
6496        .detach();
6497        (sorted_buffers_rx, buffers_rx)
6498    }
6499
6500    pub fn find_or_create_local_worktree(
6501        &mut self,
6502        abs_path: impl AsRef<Path>,
6503        visible: bool,
6504        cx: &mut ModelContext<Self>,
6505    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6506        let abs_path = abs_path.as_ref();
6507        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6508            Task::ready(Ok((tree, relative_path)))
6509        } else {
6510            let worktree = self.create_local_worktree(abs_path, visible, cx);
6511            cx.background_executor()
6512                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6513        }
6514    }
6515
6516    pub fn find_local_worktree(
6517        &self,
6518        abs_path: &Path,
6519        cx: &AppContext,
6520    ) -> Option<(Model<Worktree>, PathBuf)> {
6521        for tree in &self.worktrees {
6522            if let Some(tree) = tree.upgrade() {
6523                if let Some(relative_path) = tree
6524                    .read(cx)
6525                    .as_local()
6526                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6527                {
6528                    return Some((tree.clone(), relative_path.into()));
6529                }
6530            }
6531        }
6532        None
6533    }
6534
6535    pub fn is_shared(&self) -> bool {
6536        match &self.client_state {
6537            ProjectClientState::Shared { .. } => true,
6538            ProjectClientState::Local | ProjectClientState::Remote { .. } => false,
6539        }
6540    }
6541
6542    fn create_local_worktree(
6543        &mut self,
6544        abs_path: impl AsRef<Path>,
6545        visible: bool,
6546        cx: &mut ModelContext<Self>,
6547    ) -> Task<Result<Model<Worktree>>> {
6548        let fs = self.fs.clone();
6549        let client = self.client.clone();
6550        let next_entry_id = self.next_entry_id.clone();
6551        let path: Arc<Path> = abs_path.as_ref().into();
6552        let task = self
6553            .loading_local_worktrees
6554            .entry(path.clone())
6555            .or_insert_with(|| {
6556                cx.spawn(move |project, mut cx| {
6557                    async move {
6558                        let worktree = Worktree::local(
6559                            client.clone(),
6560                            path.clone(),
6561                            visible,
6562                            fs,
6563                            next_entry_id,
6564                            &mut cx,
6565                        )
6566                        .await;
6567
6568                        project.update(&mut cx, |project, _| {
6569                            project.loading_local_worktrees.remove(&path);
6570                        })?;
6571
6572                        let worktree = worktree?;
6573                        project
6574                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6575                        Ok(worktree)
6576                    }
6577                    .map_err(Arc::new)
6578                })
6579                .shared()
6580            })
6581            .clone();
6582        cx.background_executor().spawn(async move {
6583            match task.await {
6584                Ok(worktree) => Ok(worktree),
6585                Err(err) => Err(anyhow!("{}", err)),
6586            }
6587        })
6588    }
6589
6590    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6591        let mut servers_to_remove = HashMap::default();
6592        let mut servers_to_preserve = HashSet::default();
6593        for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
6594            if worktree_id == &id_to_remove {
6595                servers_to_remove.insert(server_id, server_name.clone());
6596            } else {
6597                servers_to_preserve.insert(server_id);
6598            }
6599        }
6600        servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
6601        for (server_id_to_remove, server_name) in servers_to_remove {
6602            self.language_server_ids
6603                .remove(&(id_to_remove, server_name));
6604            self.language_server_statuses.remove(&server_id_to_remove);
6605            self.last_workspace_edits_by_language_server
6606                .remove(&server_id_to_remove);
6607            self.language_servers.remove(&server_id_to_remove);
6608            cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
6609        }
6610
6611        let mut prettier_instances_to_clean = FuturesUnordered::new();
6612        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
6613            for path in prettier_paths.iter().flatten() {
6614                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
6615                    prettier_instances_to_clean.push(async move {
6616                        prettier_instance
6617                            .server()
6618                            .await
6619                            .map(|server| server.server_id())
6620                    });
6621                }
6622            }
6623        }
6624        cx.spawn(|project, mut cx| async move {
6625            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
6626                if let Some(prettier_server_id) = prettier_server_id {
6627                    project
6628                        .update(&mut cx, |project, cx| {
6629                            project
6630                                .supplementary_language_servers
6631                                .remove(&prettier_server_id);
6632                            cx.emit(Event::LanguageServerRemoved(prettier_server_id));
6633                        })
6634                        .ok();
6635                }
6636            }
6637        })
6638        .detach();
6639
6640        self.task_inventory().update(cx, |inventory, _| {
6641            inventory.remove_worktree_sources(id_to_remove);
6642        });
6643
6644        self.worktrees.retain(|worktree| {
6645            if let Some(worktree) = worktree.upgrade() {
6646                let id = worktree.read(cx).id();
6647                if id == id_to_remove {
6648                    cx.emit(Event::WorktreeRemoved(id));
6649                    false
6650                } else {
6651                    true
6652                }
6653            } else {
6654                false
6655            }
6656        });
6657        self.metadata_changed(cx);
6658    }
6659
6660    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6661        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6662        if worktree.read(cx).is_local() {
6663            cx.subscribe(worktree, |this, worktree, event, cx| match event {
6664                worktree::Event::UpdatedEntries(changes) => {
6665                    this.update_local_worktree_buffers(&worktree, changes, cx);
6666                    this.update_local_worktree_language_servers(&worktree, changes, cx);
6667                    this.update_local_worktree_settings(&worktree, changes, cx);
6668                    this.update_prettier_settings(&worktree, changes, cx);
6669                    cx.emit(Event::WorktreeUpdatedEntries(
6670                        worktree.read(cx).id(),
6671                        changes.clone(),
6672                    ));
6673                }
6674                worktree::Event::UpdatedGitRepositories(updated_repos) => {
6675                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6676                }
6677            })
6678            .detach();
6679        }
6680
6681        let push_strong_handle = {
6682            let worktree = worktree.read(cx);
6683            self.is_shared() || worktree.is_visible() || worktree.is_remote()
6684        };
6685        if push_strong_handle {
6686            self.worktrees
6687                .push(WorktreeHandle::Strong(worktree.clone()));
6688        } else {
6689            self.worktrees
6690                .push(WorktreeHandle::Weak(worktree.downgrade()));
6691        }
6692
6693        let handle_id = worktree.entity_id();
6694        cx.observe_release(worktree, move |this, worktree, cx| {
6695            let _ = this.remove_worktree(worktree.id(), cx);
6696            cx.update_global::<SettingsStore, _>(|store, cx| {
6697                store
6698                    .clear_local_settings(handle_id.as_u64() as usize, cx)
6699                    .log_err()
6700            });
6701        })
6702        .detach();
6703
6704        cx.emit(Event::WorktreeAdded);
6705        self.metadata_changed(cx);
6706    }
6707
6708    fn update_local_worktree_buffers(
6709        &mut self,
6710        worktree_handle: &Model<Worktree>,
6711        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6712        cx: &mut ModelContext<Self>,
6713    ) {
6714        let snapshot = worktree_handle.read(cx).snapshot();
6715
6716        let mut renamed_buffers = Vec::new();
6717        for (path, entry_id, _) in changes {
6718            let worktree_id = worktree_handle.read(cx).id();
6719            let project_path = ProjectPath {
6720                worktree_id,
6721                path: path.clone(),
6722            };
6723
6724            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6725                Some(&buffer_id) => buffer_id,
6726                None => match self.local_buffer_ids_by_path.get(&project_path) {
6727                    Some(&buffer_id) => buffer_id,
6728                    None => {
6729                        continue;
6730                    }
6731                },
6732            };
6733
6734            let open_buffer = self.opened_buffers.get(&buffer_id);
6735            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6736                buffer
6737            } else {
6738                self.opened_buffers.remove(&buffer_id);
6739                self.local_buffer_ids_by_path.remove(&project_path);
6740                self.local_buffer_ids_by_entry_id.remove(entry_id);
6741                continue;
6742            };
6743
6744            buffer.update(cx, |buffer, cx| {
6745                if let Some(old_file) = File::from_dyn(buffer.file()) {
6746                    if old_file.worktree != *worktree_handle {
6747                        return;
6748                    }
6749
6750                    let new_file = if let Some(entry) = old_file
6751                        .entry_id
6752                        .and_then(|entry_id| snapshot.entry_for_id(entry_id))
6753                    {
6754                        File {
6755                            is_local: true,
6756                            entry_id: Some(entry.id),
6757                            mtime: entry.mtime,
6758                            path: entry.path.clone(),
6759                            worktree: worktree_handle.clone(),
6760                            is_deleted: false,
6761                            is_private: entry.is_private,
6762                        }
6763                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6764                        File {
6765                            is_local: true,
6766                            entry_id: Some(entry.id),
6767                            mtime: entry.mtime,
6768                            path: entry.path.clone(),
6769                            worktree: worktree_handle.clone(),
6770                            is_deleted: false,
6771                            is_private: entry.is_private,
6772                        }
6773                    } else {
6774                        File {
6775                            is_local: true,
6776                            entry_id: old_file.entry_id,
6777                            path: old_file.path().clone(),
6778                            mtime: old_file.mtime(),
6779                            worktree: worktree_handle.clone(),
6780                            is_deleted: true,
6781                            is_private: old_file.is_private,
6782                        }
6783                    };
6784
6785                    let old_path = old_file.abs_path(cx);
6786                    if new_file.abs_path(cx) != old_path {
6787                        renamed_buffers.push((cx.handle(), old_file.clone()));
6788                        self.local_buffer_ids_by_path.remove(&project_path);
6789                        self.local_buffer_ids_by_path.insert(
6790                            ProjectPath {
6791                                worktree_id,
6792                                path: path.clone(),
6793                            },
6794                            buffer_id,
6795                        );
6796                    }
6797
6798                    if new_file.entry_id != Some(*entry_id) {
6799                        self.local_buffer_ids_by_entry_id.remove(entry_id);
6800                        if let Some(entry_id) = new_file.entry_id {
6801                            self.local_buffer_ids_by_entry_id
6802                                .insert(entry_id, buffer_id);
6803                        }
6804                    }
6805
6806                    if new_file != *old_file {
6807                        if let Some(project_id) = self.remote_id() {
6808                            self.client
6809                                .send(proto::UpdateBufferFile {
6810                                    project_id,
6811                                    buffer_id: buffer_id.into(),
6812                                    file: Some(new_file.to_proto()),
6813                                })
6814                                .log_err();
6815                        }
6816
6817                        buffer.file_updated(Arc::new(new_file), cx);
6818                    }
6819                }
6820            });
6821        }
6822
6823        for (buffer, old_file) in renamed_buffers {
6824            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6825            self.detect_language_for_buffer(&buffer, cx);
6826            self.register_buffer_with_language_servers(&buffer, cx);
6827        }
6828    }
6829
6830    fn update_local_worktree_language_servers(
6831        &mut self,
6832        worktree_handle: &Model<Worktree>,
6833        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6834        cx: &mut ModelContext<Self>,
6835    ) {
6836        if changes.is_empty() {
6837            return;
6838        }
6839
6840        let worktree_id = worktree_handle.read(cx).id();
6841        let mut language_server_ids = self
6842            .language_server_ids
6843            .iter()
6844            .filter_map(|((server_worktree_id, _), server_id)| {
6845                (*server_worktree_id == worktree_id).then_some(*server_id)
6846            })
6847            .collect::<Vec<_>>();
6848        language_server_ids.sort();
6849        language_server_ids.dedup();
6850
6851        let abs_path = worktree_handle.read(cx).abs_path();
6852        for server_id in &language_server_ids {
6853            if let Some(LanguageServerState::Running {
6854                server,
6855                watched_paths,
6856                ..
6857            }) = self.language_servers.get(server_id)
6858            {
6859                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6860                    let params = lsp::DidChangeWatchedFilesParams {
6861                        changes: changes
6862                            .iter()
6863                            .filter_map(|(path, _, change)| {
6864                                if !watched_paths.is_match(&path) {
6865                                    return None;
6866                                }
6867                                let typ = match change {
6868                                    PathChange::Loaded => return None,
6869                                    PathChange::Added => lsp::FileChangeType::CREATED,
6870                                    PathChange::Removed => lsp::FileChangeType::DELETED,
6871                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
6872                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6873                                };
6874                                Some(lsp::FileEvent {
6875                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6876                                    typ,
6877                                })
6878                            })
6879                            .collect(),
6880                    };
6881
6882                    if !params.changes.is_empty() {
6883                        server
6884                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6885                            .log_err();
6886                    }
6887                }
6888            }
6889        }
6890    }
6891
6892    fn update_local_worktree_buffers_git_repos(
6893        &mut self,
6894        worktree_handle: Model<Worktree>,
6895        changed_repos: &UpdatedGitRepositoriesSet,
6896        cx: &mut ModelContext<Self>,
6897    ) {
6898        debug_assert!(worktree_handle.read(cx).is_local());
6899
6900        // Identify the loading buffers whose containing repository that has changed.
6901        let future_buffers = self
6902            .loading_buffers_by_path
6903            .iter()
6904            .filter_map(|(project_path, receiver)| {
6905                if project_path.worktree_id != worktree_handle.read(cx).id() {
6906                    return None;
6907                }
6908                let path = &project_path.path;
6909                changed_repos
6910                    .iter()
6911                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6912                let receiver = receiver.clone();
6913                let path = path.clone();
6914                Some(async move {
6915                    wait_for_loading_buffer(receiver)
6916                        .await
6917                        .ok()
6918                        .map(|buffer| (buffer, path))
6919                })
6920            })
6921            .collect::<FuturesUnordered<_>>();
6922
6923        // Identify the current buffers whose containing repository has changed.
6924        let current_buffers = self
6925            .opened_buffers
6926            .values()
6927            .filter_map(|buffer| {
6928                let buffer = buffer.upgrade()?;
6929                let file = File::from_dyn(buffer.read(cx).file())?;
6930                if file.worktree != worktree_handle {
6931                    return None;
6932                }
6933                let path = file.path();
6934                changed_repos
6935                    .iter()
6936                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6937                Some((buffer, path.clone()))
6938            })
6939            .collect::<Vec<_>>();
6940
6941        if future_buffers.len() + current_buffers.len() == 0 {
6942            return;
6943        }
6944
6945        let remote_id = self.remote_id();
6946        let client = self.client.clone();
6947        cx.spawn(move |_, mut cx| async move {
6948            // Wait for all of the buffers to load.
6949            let future_buffers = future_buffers.collect::<Vec<_>>().await;
6950
6951            // Reload the diff base for every buffer whose containing git repository has changed.
6952            let snapshot =
6953                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
6954            let diff_bases_by_buffer = cx
6955                .background_executor()
6956                .spawn(async move {
6957                    future_buffers
6958                        .into_iter()
6959                        .filter_map(|e| e)
6960                        .chain(current_buffers)
6961                        .filter_map(|(buffer, path)| {
6962                            let (work_directory, repo) =
6963                                snapshot.repository_and_work_directory_for_path(&path)?;
6964                            let repo = snapshot.get_local_repo(&repo)?;
6965                            let relative_path = path.strip_prefix(&work_directory).ok()?;
6966                            let base_text = repo.load_index_text(relative_path);
6967                            Some((buffer, base_text))
6968                        })
6969                        .collect::<Vec<_>>()
6970                })
6971                .await;
6972
6973            // Assign the new diff bases on all of the buffers.
6974            for (buffer, diff_base) in diff_bases_by_buffer {
6975                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6976                    buffer.set_diff_base(diff_base.clone(), cx);
6977                    buffer.remote_id().into()
6978                })?;
6979                if let Some(project_id) = remote_id {
6980                    client
6981                        .send(proto::UpdateDiffBase {
6982                            project_id,
6983                            buffer_id,
6984                            diff_base,
6985                        })
6986                        .log_err();
6987                }
6988            }
6989
6990            anyhow::Ok(())
6991        })
6992        .detach();
6993    }
6994
6995    fn update_local_worktree_settings(
6996        &mut self,
6997        worktree: &Model<Worktree>,
6998        changes: &UpdatedEntriesSet,
6999        cx: &mut ModelContext<Self>,
7000    ) {
7001        if worktree.read(cx).as_local().is_none() {
7002            return;
7003        }
7004        let project_id = self.remote_id();
7005        let worktree_id = worktree.entity_id();
7006        let remote_worktree_id = worktree.read(cx).id();
7007
7008        let mut settings_contents = Vec::new();
7009        for (path, _, change) in changes.iter() {
7010            let removed = change == &PathChange::Removed;
7011            let abs_path = match worktree.read(cx).absolutize(path) {
7012                Ok(abs_path) => abs_path,
7013                Err(e) => {
7014                    log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
7015                    continue;
7016                }
7017            };
7018
7019            if abs_path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
7020                let settings_dir = Arc::from(
7021                    path.ancestors()
7022                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
7023                        .unwrap(),
7024                );
7025                let fs = self.fs.clone();
7026                settings_contents.push(async move {
7027                    (
7028                        settings_dir,
7029                        if removed {
7030                            None
7031                        } else {
7032                            Some(async move { fs.load(&abs_path).await }.await)
7033                        },
7034                    )
7035                });
7036            } else if abs_path.ends_with(&*LOCAL_TASKS_RELATIVE_PATH) {
7037                self.task_inventory().update(cx, |task_inventory, cx| {
7038                    if removed {
7039                        task_inventory.remove_local_static_source(&abs_path);
7040                    } else {
7041                        let fs = self.fs.clone();
7042                        let task_abs_path = abs_path.clone();
7043                        task_inventory.add_source(
7044                            TaskSourceKind::Worktree {
7045                                id: remote_worktree_id,
7046                                abs_path,
7047                            },
7048                            |cx| {
7049                                let tasks_file_rx =
7050                                    watch_config_file(&cx.background_executor(), fs, task_abs_path);
7051                                StaticSource::new(
7052                                    format!("local_tasks_for_workspace_{remote_worktree_id}"),
7053                                    tasks_file_rx,
7054                                    cx,
7055                                )
7056                            },
7057                            cx,
7058                        );
7059                    }
7060                })
7061            }
7062        }
7063
7064        if settings_contents.is_empty() {
7065            return;
7066        }
7067
7068        let client = self.client.clone();
7069        cx.spawn(move |_, cx| async move {
7070            let settings_contents: Vec<(Arc<Path>, _)> =
7071                futures::future::join_all(settings_contents).await;
7072            cx.update(|cx| {
7073                cx.update_global::<SettingsStore, _>(|store, cx| {
7074                    for (directory, file_content) in settings_contents {
7075                        let file_content = file_content.and_then(|content| content.log_err());
7076                        store
7077                            .set_local_settings(
7078                                worktree_id.as_u64() as usize,
7079                                directory.clone(),
7080                                file_content.as_ref().map(String::as_str),
7081                                cx,
7082                            )
7083                            .log_err();
7084                        if let Some(remote_id) = project_id {
7085                            client
7086                                .send(proto::UpdateWorktreeSettings {
7087                                    project_id: remote_id,
7088                                    worktree_id: remote_worktree_id.to_proto(),
7089                                    path: directory.to_string_lossy().into_owned(),
7090                                    content: file_content,
7091                                })
7092                                .log_err();
7093                        }
7094                    }
7095                });
7096            })
7097            .ok();
7098        })
7099        .detach();
7100    }
7101
7102    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
7103        let new_active_entry = entry.and_then(|project_path| {
7104            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
7105            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
7106            Some(entry.id)
7107        });
7108        if new_active_entry != self.active_entry {
7109            self.active_entry = new_active_entry;
7110            cx.emit(Event::ActiveEntryChanged(new_active_entry));
7111        }
7112    }
7113
7114    pub fn language_servers_running_disk_based_diagnostics(
7115        &self,
7116    ) -> impl Iterator<Item = LanguageServerId> + '_ {
7117        self.language_server_statuses
7118            .iter()
7119            .filter_map(|(id, status)| {
7120                if status.has_pending_diagnostic_updates {
7121                    Some(*id)
7122                } else {
7123                    None
7124                }
7125            })
7126    }
7127
7128    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
7129        let mut summary = DiagnosticSummary::default();
7130        for (_, _, path_summary) in
7131            self.diagnostic_summaries(include_ignored, cx)
7132                .filter(|(path, _, _)| {
7133                    let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
7134                    include_ignored || worktree == Some(false)
7135                })
7136        {
7137            summary.error_count += path_summary.error_count;
7138            summary.warning_count += path_summary.warning_count;
7139        }
7140        summary
7141    }
7142
7143    pub fn diagnostic_summaries<'a>(
7144        &'a self,
7145        include_ignored: bool,
7146        cx: &'a AppContext,
7147    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
7148        self.visible_worktrees(cx)
7149            .flat_map(move |worktree| {
7150                let worktree = worktree.read(cx);
7151                let worktree_id = worktree.id();
7152                worktree
7153                    .diagnostic_summaries()
7154                    .map(move |(path, server_id, summary)| {
7155                        (ProjectPath { worktree_id, path }, server_id, summary)
7156                    })
7157            })
7158            .filter(move |(path, _, _)| {
7159                let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
7160                include_ignored || worktree == Some(false)
7161            })
7162    }
7163
7164    pub fn disk_based_diagnostics_started(
7165        &mut self,
7166        language_server_id: LanguageServerId,
7167        cx: &mut ModelContext<Self>,
7168    ) {
7169        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
7170    }
7171
7172    pub fn disk_based_diagnostics_finished(
7173        &mut self,
7174        language_server_id: LanguageServerId,
7175        cx: &mut ModelContext<Self>,
7176    ) {
7177        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
7178    }
7179
7180    pub fn active_entry(&self) -> Option<ProjectEntryId> {
7181        self.active_entry
7182    }
7183
7184    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
7185        self.worktree_for_id(path.worktree_id, cx)?
7186            .read(cx)
7187            .entry_for_path(&path.path)
7188            .cloned()
7189    }
7190
7191    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
7192        let worktree = self.worktree_for_entry(entry_id, cx)?;
7193        let worktree = worktree.read(cx);
7194        let worktree_id = worktree.id();
7195        let path = worktree.entry_for_id(entry_id)?.path.clone();
7196        Some(ProjectPath { worktree_id, path })
7197    }
7198
7199    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
7200        let workspace_root = self
7201            .worktree_for_id(project_path.worktree_id, cx)?
7202            .read(cx)
7203            .abs_path();
7204        let project_path = project_path.path.as_ref();
7205
7206        Some(if project_path == Path::new("") {
7207            workspace_root.to_path_buf()
7208        } else {
7209            workspace_root.join(project_path)
7210        })
7211    }
7212
7213    // RPC message handlers
7214
7215    async fn handle_unshare_project(
7216        this: Model<Self>,
7217        _: TypedEnvelope<proto::UnshareProject>,
7218        _: Arc<Client>,
7219        mut cx: AsyncAppContext,
7220    ) -> Result<()> {
7221        this.update(&mut cx, |this, cx| {
7222            if this.is_local() {
7223                this.unshare(cx)?;
7224            } else {
7225                this.disconnected_from_host(cx);
7226            }
7227            Ok(())
7228        })?
7229    }
7230
7231    async fn handle_add_collaborator(
7232        this: Model<Self>,
7233        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
7234        _: Arc<Client>,
7235        mut cx: AsyncAppContext,
7236    ) -> Result<()> {
7237        let collaborator = envelope
7238            .payload
7239            .collaborator
7240            .take()
7241            .ok_or_else(|| anyhow!("empty collaborator"))?;
7242
7243        let collaborator = Collaborator::from_proto(collaborator)?;
7244        this.update(&mut cx, |this, cx| {
7245            this.shared_buffers.remove(&collaborator.peer_id);
7246            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
7247            this.collaborators
7248                .insert(collaborator.peer_id, collaborator);
7249            cx.notify();
7250        })?;
7251
7252        Ok(())
7253    }
7254
7255    async fn handle_update_project_collaborator(
7256        this: Model<Self>,
7257        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
7258        _: Arc<Client>,
7259        mut cx: AsyncAppContext,
7260    ) -> Result<()> {
7261        let old_peer_id = envelope
7262            .payload
7263            .old_peer_id
7264            .ok_or_else(|| anyhow!("missing old peer id"))?;
7265        let new_peer_id = envelope
7266            .payload
7267            .new_peer_id
7268            .ok_or_else(|| anyhow!("missing new peer id"))?;
7269        this.update(&mut cx, |this, cx| {
7270            let collaborator = this
7271                .collaborators
7272                .remove(&old_peer_id)
7273                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
7274            let is_host = collaborator.replica_id == 0;
7275            this.collaborators.insert(new_peer_id, collaborator);
7276
7277            let buffers = this.shared_buffers.remove(&old_peer_id);
7278            log::info!(
7279                "peer {} became {}. moving buffers {:?}",
7280                old_peer_id,
7281                new_peer_id,
7282                &buffers
7283            );
7284            if let Some(buffers) = buffers {
7285                this.shared_buffers.insert(new_peer_id, buffers);
7286            }
7287
7288            if is_host {
7289                this.opened_buffers
7290                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
7291                this.buffer_ordered_messages_tx
7292                    .unbounded_send(BufferOrderedMessage::Resync)
7293                    .unwrap();
7294            }
7295
7296            cx.emit(Event::CollaboratorUpdated {
7297                old_peer_id,
7298                new_peer_id,
7299            });
7300            cx.notify();
7301            Ok(())
7302        })?
7303    }
7304
7305    async fn handle_remove_collaborator(
7306        this: Model<Self>,
7307        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
7308        _: Arc<Client>,
7309        mut cx: AsyncAppContext,
7310    ) -> Result<()> {
7311        this.update(&mut cx, |this, cx| {
7312            let peer_id = envelope
7313                .payload
7314                .peer_id
7315                .ok_or_else(|| anyhow!("invalid peer id"))?;
7316            let replica_id = this
7317                .collaborators
7318                .remove(&peer_id)
7319                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
7320                .replica_id;
7321            for buffer in this.opened_buffers.values() {
7322                if let Some(buffer) = buffer.upgrade() {
7323                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
7324                }
7325            }
7326            this.shared_buffers.remove(&peer_id);
7327
7328            cx.emit(Event::CollaboratorLeft(peer_id));
7329            cx.notify();
7330            Ok(())
7331        })?
7332    }
7333
7334    async fn handle_update_project(
7335        this: Model<Self>,
7336        envelope: TypedEnvelope<proto::UpdateProject>,
7337        _: Arc<Client>,
7338        mut cx: AsyncAppContext,
7339    ) -> Result<()> {
7340        this.update(&mut cx, |this, cx| {
7341            // Don't handle messages that were sent before the response to us joining the project
7342            if envelope.message_id > this.join_project_response_message_id {
7343                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
7344            }
7345            Ok(())
7346        })?
7347    }
7348
7349    async fn handle_update_worktree(
7350        this: Model<Self>,
7351        envelope: TypedEnvelope<proto::UpdateWorktree>,
7352        _: Arc<Client>,
7353        mut cx: AsyncAppContext,
7354    ) -> Result<()> {
7355        this.update(&mut cx, |this, cx| {
7356            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7357            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7358                worktree.update(cx, |worktree, _| {
7359                    let worktree = worktree.as_remote_mut().unwrap();
7360                    worktree.update_from_remote(envelope.payload);
7361                });
7362            }
7363            Ok(())
7364        })?
7365    }
7366
7367    async fn handle_update_worktree_settings(
7368        this: Model<Self>,
7369        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
7370        _: Arc<Client>,
7371        mut cx: AsyncAppContext,
7372    ) -> Result<()> {
7373        this.update(&mut cx, |this, cx| {
7374            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7375            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7376                cx.update_global::<SettingsStore, _>(|store, cx| {
7377                    store
7378                        .set_local_settings(
7379                            worktree.entity_id().as_u64() as usize,
7380                            PathBuf::from(&envelope.payload.path).into(),
7381                            envelope.payload.content.as_ref().map(String::as_str),
7382                            cx,
7383                        )
7384                        .log_err();
7385                });
7386            }
7387            Ok(())
7388        })?
7389    }
7390
7391    async fn handle_create_project_entry(
7392        this: Model<Self>,
7393        envelope: TypedEnvelope<proto::CreateProjectEntry>,
7394        _: Arc<Client>,
7395        mut cx: AsyncAppContext,
7396    ) -> Result<proto::ProjectEntryResponse> {
7397        let worktree = this.update(&mut cx, |this, cx| {
7398            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7399            this.worktree_for_id(worktree_id, cx)
7400                .ok_or_else(|| anyhow!("worktree not found"))
7401        })??;
7402        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7403        let entry = worktree
7404            .update(&mut cx, |worktree, cx| {
7405                let worktree = worktree.as_local_mut().unwrap();
7406                let path = PathBuf::from(envelope.payload.path);
7407                worktree.create_entry(path, envelope.payload.is_directory, cx)
7408            })?
7409            .await?;
7410        Ok(proto::ProjectEntryResponse {
7411            entry: entry.as_ref().map(|e| e.into()),
7412            worktree_scan_id: worktree_scan_id as u64,
7413        })
7414    }
7415
7416    async fn handle_rename_project_entry(
7417        this: Model<Self>,
7418        envelope: TypedEnvelope<proto::RenameProjectEntry>,
7419        _: Arc<Client>,
7420        mut cx: AsyncAppContext,
7421    ) -> Result<proto::ProjectEntryResponse> {
7422        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7423        let worktree = this.update(&mut cx, |this, cx| {
7424            this.worktree_for_entry(entry_id, cx)
7425                .ok_or_else(|| anyhow!("worktree not found"))
7426        })??;
7427        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7428        let entry = worktree
7429            .update(&mut cx, |worktree, cx| {
7430                let new_path = PathBuf::from(envelope.payload.new_path);
7431                worktree
7432                    .as_local_mut()
7433                    .unwrap()
7434                    .rename_entry(entry_id, new_path, cx)
7435            })?
7436            .await?;
7437        Ok(proto::ProjectEntryResponse {
7438            entry: entry.as_ref().map(|e| e.into()),
7439            worktree_scan_id: worktree_scan_id as u64,
7440        })
7441    }
7442
7443    async fn handle_copy_project_entry(
7444        this: Model<Self>,
7445        envelope: TypedEnvelope<proto::CopyProjectEntry>,
7446        _: Arc<Client>,
7447        mut cx: AsyncAppContext,
7448    ) -> Result<proto::ProjectEntryResponse> {
7449        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7450        let worktree = this.update(&mut cx, |this, cx| {
7451            this.worktree_for_entry(entry_id, cx)
7452                .ok_or_else(|| anyhow!("worktree not found"))
7453        })??;
7454        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7455        let entry = worktree
7456            .update(&mut cx, |worktree, cx| {
7457                let new_path = PathBuf::from(envelope.payload.new_path);
7458                worktree
7459                    .as_local_mut()
7460                    .unwrap()
7461                    .copy_entry(entry_id, new_path, cx)
7462            })?
7463            .await?;
7464        Ok(proto::ProjectEntryResponse {
7465            entry: entry.as_ref().map(|e| e.into()),
7466            worktree_scan_id: worktree_scan_id as u64,
7467        })
7468    }
7469
7470    async fn handle_delete_project_entry(
7471        this: Model<Self>,
7472        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
7473        _: Arc<Client>,
7474        mut cx: AsyncAppContext,
7475    ) -> Result<proto::ProjectEntryResponse> {
7476        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7477
7478        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
7479
7480        let worktree = this.update(&mut cx, |this, cx| {
7481            this.worktree_for_entry(entry_id, cx)
7482                .ok_or_else(|| anyhow!("worktree not found"))
7483        })??;
7484        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7485        worktree
7486            .update(&mut cx, |worktree, cx| {
7487                worktree
7488                    .as_local_mut()
7489                    .unwrap()
7490                    .delete_entry(entry_id, cx)
7491                    .ok_or_else(|| anyhow!("invalid entry"))
7492            })??
7493            .await?;
7494        Ok(proto::ProjectEntryResponse {
7495            entry: None,
7496            worktree_scan_id: worktree_scan_id as u64,
7497        })
7498    }
7499
7500    async fn handle_expand_project_entry(
7501        this: Model<Self>,
7502        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7503        _: Arc<Client>,
7504        mut cx: AsyncAppContext,
7505    ) -> Result<proto::ExpandProjectEntryResponse> {
7506        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7507        let worktree = this
7508            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7509            .ok_or_else(|| anyhow!("invalid request"))?;
7510        worktree
7511            .update(&mut cx, |worktree, cx| {
7512                worktree
7513                    .as_local_mut()
7514                    .unwrap()
7515                    .expand_entry(entry_id, cx)
7516                    .ok_or_else(|| anyhow!("invalid entry"))
7517            })??
7518            .await?;
7519        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7520        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7521    }
7522
7523    async fn handle_update_diagnostic_summary(
7524        this: Model<Self>,
7525        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7526        _: Arc<Client>,
7527        mut cx: AsyncAppContext,
7528    ) -> Result<()> {
7529        this.update(&mut cx, |this, cx| {
7530            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7531            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7532                if let Some(summary) = envelope.payload.summary {
7533                    let project_path = ProjectPath {
7534                        worktree_id,
7535                        path: Path::new(&summary.path).into(),
7536                    };
7537                    worktree.update(cx, |worktree, _| {
7538                        worktree
7539                            .as_remote_mut()
7540                            .unwrap()
7541                            .update_diagnostic_summary(project_path.path.clone(), &summary);
7542                    });
7543                    cx.emit(Event::DiagnosticsUpdated {
7544                        language_server_id: LanguageServerId(summary.language_server_id as usize),
7545                        path: project_path,
7546                    });
7547                }
7548            }
7549            Ok(())
7550        })?
7551    }
7552
7553    async fn handle_start_language_server(
7554        this: Model<Self>,
7555        envelope: TypedEnvelope<proto::StartLanguageServer>,
7556        _: Arc<Client>,
7557        mut cx: AsyncAppContext,
7558    ) -> Result<()> {
7559        let server = envelope
7560            .payload
7561            .server
7562            .ok_or_else(|| anyhow!("invalid server"))?;
7563        this.update(&mut cx, |this, cx| {
7564            this.language_server_statuses.insert(
7565                LanguageServerId(server.id as usize),
7566                LanguageServerStatus {
7567                    name: server.name,
7568                    pending_work: Default::default(),
7569                    has_pending_diagnostic_updates: false,
7570                    progress_tokens: Default::default(),
7571                },
7572            );
7573            cx.notify();
7574        })?;
7575        Ok(())
7576    }
7577
7578    async fn handle_update_language_server(
7579        this: Model<Self>,
7580        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7581        _: Arc<Client>,
7582        mut cx: AsyncAppContext,
7583    ) -> Result<()> {
7584        this.update(&mut cx, |this, cx| {
7585            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7586
7587            match envelope
7588                .payload
7589                .variant
7590                .ok_or_else(|| anyhow!("invalid variant"))?
7591            {
7592                proto::update_language_server::Variant::WorkStart(payload) => {
7593                    this.on_lsp_work_start(
7594                        language_server_id,
7595                        payload.token,
7596                        LanguageServerProgress {
7597                            message: payload.message,
7598                            percentage: payload.percentage.map(|p| p as usize),
7599                            last_update_at: Instant::now(),
7600                        },
7601                        cx,
7602                    );
7603                }
7604
7605                proto::update_language_server::Variant::WorkProgress(payload) => {
7606                    this.on_lsp_work_progress(
7607                        language_server_id,
7608                        payload.token,
7609                        LanguageServerProgress {
7610                            message: payload.message,
7611                            percentage: payload.percentage.map(|p| p as usize),
7612                            last_update_at: Instant::now(),
7613                        },
7614                        cx,
7615                    );
7616                }
7617
7618                proto::update_language_server::Variant::WorkEnd(payload) => {
7619                    this.on_lsp_work_end(language_server_id, payload.token, cx);
7620                }
7621
7622                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7623                    this.disk_based_diagnostics_started(language_server_id, cx);
7624                }
7625
7626                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7627                    this.disk_based_diagnostics_finished(language_server_id, cx)
7628                }
7629            }
7630
7631            Ok(())
7632        })?
7633    }
7634
7635    async fn handle_update_buffer(
7636        this: Model<Self>,
7637        envelope: TypedEnvelope<proto::UpdateBuffer>,
7638        _: Arc<Client>,
7639        mut cx: AsyncAppContext,
7640    ) -> Result<proto::Ack> {
7641        this.update(&mut cx, |this, cx| {
7642            let payload = envelope.payload.clone();
7643            let buffer_id = BufferId::new(payload.buffer_id)?;
7644            let ops = payload
7645                .operations
7646                .into_iter()
7647                .map(language::proto::deserialize_operation)
7648                .collect::<Result<Vec<_>, _>>()?;
7649            let is_remote = this.is_remote();
7650            match this.opened_buffers.entry(buffer_id) {
7651                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7652                    OpenBuffer::Strong(buffer) => {
7653                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7654                    }
7655                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7656                    OpenBuffer::Weak(_) => {}
7657                },
7658                hash_map::Entry::Vacant(e) => {
7659                    assert!(
7660                        is_remote,
7661                        "received buffer update from {:?}",
7662                        envelope.original_sender_id
7663                    );
7664                    e.insert(OpenBuffer::Operations(ops));
7665                }
7666            }
7667            Ok(proto::Ack {})
7668        })?
7669    }
7670
7671    async fn handle_create_buffer_for_peer(
7672        this: Model<Self>,
7673        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7674        _: Arc<Client>,
7675        mut cx: AsyncAppContext,
7676    ) -> Result<()> {
7677        this.update(&mut cx, |this, cx| {
7678            match envelope
7679                .payload
7680                .variant
7681                .ok_or_else(|| anyhow!("missing variant"))?
7682            {
7683                proto::create_buffer_for_peer::Variant::State(mut state) => {
7684                    let mut buffer_file = None;
7685                    if let Some(file) = state.file.take() {
7686                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
7687                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7688                            anyhow!("no worktree found for id {}", file.worktree_id)
7689                        })?;
7690                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7691                            as Arc<dyn language::File>);
7692                    }
7693
7694                    let buffer_id = BufferId::new(state.id)?;
7695                    let buffer = cx.new_model(|_| {
7696                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
7697                            .unwrap()
7698                    });
7699                    this.incomplete_remote_buffers
7700                        .insert(buffer_id, Some(buffer));
7701                }
7702                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7703                    let buffer_id = BufferId::new(chunk.buffer_id)?;
7704                    let buffer = this
7705                        .incomplete_remote_buffers
7706                        .get(&buffer_id)
7707                        .cloned()
7708                        .flatten()
7709                        .ok_or_else(|| {
7710                            anyhow!(
7711                                "received chunk for buffer {} without initial state",
7712                                chunk.buffer_id
7713                            )
7714                        })?;
7715                    let operations = chunk
7716                        .operations
7717                        .into_iter()
7718                        .map(language::proto::deserialize_operation)
7719                        .collect::<Result<Vec<_>>>()?;
7720                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7721
7722                    if chunk.is_last {
7723                        this.incomplete_remote_buffers.remove(&buffer_id);
7724                        this.register_buffer(&buffer, cx)?;
7725                    }
7726                }
7727            }
7728
7729            Ok(())
7730        })?
7731    }
7732
7733    async fn handle_update_diff_base(
7734        this: Model<Self>,
7735        envelope: TypedEnvelope<proto::UpdateDiffBase>,
7736        _: Arc<Client>,
7737        mut cx: AsyncAppContext,
7738    ) -> Result<()> {
7739        this.update(&mut cx, |this, cx| {
7740            let buffer_id = envelope.payload.buffer_id;
7741            let buffer_id = BufferId::new(buffer_id)?;
7742            let diff_base = envelope.payload.diff_base;
7743            if let Some(buffer) = this
7744                .opened_buffers
7745                .get_mut(&buffer_id)
7746                .and_then(|b| b.upgrade())
7747                .or_else(|| {
7748                    this.incomplete_remote_buffers
7749                        .get(&buffer_id)
7750                        .cloned()
7751                        .flatten()
7752                })
7753            {
7754                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7755            }
7756            Ok(())
7757        })?
7758    }
7759
7760    async fn handle_update_buffer_file(
7761        this: Model<Self>,
7762        envelope: TypedEnvelope<proto::UpdateBufferFile>,
7763        _: Arc<Client>,
7764        mut cx: AsyncAppContext,
7765    ) -> Result<()> {
7766        let buffer_id = envelope.payload.buffer_id;
7767        let buffer_id = BufferId::new(buffer_id)?;
7768
7769        this.update(&mut cx, |this, cx| {
7770            let payload = envelope.payload.clone();
7771            if let Some(buffer) = this
7772                .opened_buffers
7773                .get(&buffer_id)
7774                .and_then(|b| b.upgrade())
7775                .or_else(|| {
7776                    this.incomplete_remote_buffers
7777                        .get(&buffer_id)
7778                        .cloned()
7779                        .flatten()
7780                })
7781            {
7782                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7783                let worktree = this
7784                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7785                    .ok_or_else(|| anyhow!("no such worktree"))?;
7786                let file = File::from_proto(file, worktree, cx)?;
7787                buffer.update(cx, |buffer, cx| {
7788                    buffer.file_updated(Arc::new(file), cx);
7789                });
7790                this.detect_language_for_buffer(&buffer, cx);
7791            }
7792            Ok(())
7793        })?
7794    }
7795
7796    async fn handle_save_buffer(
7797        this: Model<Self>,
7798        envelope: TypedEnvelope<proto::SaveBuffer>,
7799        _: Arc<Client>,
7800        mut cx: AsyncAppContext,
7801    ) -> Result<proto::BufferSaved> {
7802        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7803        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7804            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7805            let buffer = this
7806                .opened_buffers
7807                .get(&buffer_id)
7808                .and_then(|buffer| buffer.upgrade())
7809                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7810            anyhow::Ok((project_id, buffer))
7811        })??;
7812        buffer
7813            .update(&mut cx, |buffer, _| {
7814                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7815            })?
7816            .await?;
7817        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7818
7819        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7820            .await?;
7821        Ok(buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7822            project_id,
7823            buffer_id: buffer_id.into(),
7824            version: serialize_version(buffer.saved_version()),
7825            mtime: Some(buffer.saved_mtime().into()),
7826            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7827        })?)
7828    }
7829
7830    async fn handle_reload_buffers(
7831        this: Model<Self>,
7832        envelope: TypedEnvelope<proto::ReloadBuffers>,
7833        _: Arc<Client>,
7834        mut cx: AsyncAppContext,
7835    ) -> Result<proto::ReloadBuffersResponse> {
7836        let sender_id = envelope.original_sender_id()?;
7837        let reload = this.update(&mut cx, |this, cx| {
7838            let mut buffers = HashSet::default();
7839            for buffer_id in &envelope.payload.buffer_ids {
7840                let buffer_id = BufferId::new(*buffer_id)?;
7841                buffers.insert(
7842                    this.opened_buffers
7843                        .get(&buffer_id)
7844                        .and_then(|buffer| buffer.upgrade())
7845                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7846                );
7847            }
7848            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7849        })??;
7850
7851        let project_transaction = reload.await?;
7852        let project_transaction = this.update(&mut cx, |this, cx| {
7853            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7854        })?;
7855        Ok(proto::ReloadBuffersResponse {
7856            transaction: Some(project_transaction),
7857        })
7858    }
7859
7860    async fn handle_synchronize_buffers(
7861        this: Model<Self>,
7862        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7863        _: Arc<Client>,
7864        mut cx: AsyncAppContext,
7865    ) -> Result<proto::SynchronizeBuffersResponse> {
7866        let project_id = envelope.payload.project_id;
7867        let mut response = proto::SynchronizeBuffersResponse {
7868            buffers: Default::default(),
7869        };
7870
7871        this.update(&mut cx, |this, cx| {
7872            let Some(guest_id) = envelope.original_sender_id else {
7873                error!("missing original_sender_id on SynchronizeBuffers request");
7874                bail!("missing original_sender_id on SynchronizeBuffers request");
7875            };
7876
7877            this.shared_buffers.entry(guest_id).or_default().clear();
7878            for buffer in envelope.payload.buffers {
7879                let buffer_id = BufferId::new(buffer.id)?;
7880                let remote_version = language::proto::deserialize_version(&buffer.version);
7881                if let Some(buffer) = this.buffer_for_id(buffer_id) {
7882                    this.shared_buffers
7883                        .entry(guest_id)
7884                        .or_default()
7885                        .insert(buffer_id);
7886
7887                    let buffer = buffer.read(cx);
7888                    response.buffers.push(proto::BufferVersion {
7889                        id: buffer_id.into(),
7890                        version: language::proto::serialize_version(&buffer.version),
7891                    });
7892
7893                    let operations = buffer.serialize_ops(Some(remote_version), cx);
7894                    let client = this.client.clone();
7895                    if let Some(file) = buffer.file() {
7896                        client
7897                            .send(proto::UpdateBufferFile {
7898                                project_id,
7899                                buffer_id: buffer_id.into(),
7900                                file: Some(file.to_proto()),
7901                            })
7902                            .log_err();
7903                    }
7904
7905                    client
7906                        .send(proto::UpdateDiffBase {
7907                            project_id,
7908                            buffer_id: buffer_id.into(),
7909                            diff_base: buffer.diff_base().map(Into::into),
7910                        })
7911                        .log_err();
7912
7913                    client
7914                        .send(proto::BufferReloaded {
7915                            project_id,
7916                            buffer_id: buffer_id.into(),
7917                            version: language::proto::serialize_version(buffer.saved_version()),
7918                            mtime: Some(buffer.saved_mtime().into()),
7919                            fingerprint: language::proto::serialize_fingerprint(
7920                                buffer.saved_version_fingerprint(),
7921                            ),
7922                            line_ending: language::proto::serialize_line_ending(
7923                                buffer.line_ending(),
7924                            ) as i32,
7925                        })
7926                        .log_err();
7927
7928                    cx.background_executor()
7929                        .spawn(
7930                            async move {
7931                                let operations = operations.await;
7932                                for chunk in split_operations(operations) {
7933                                    client
7934                                        .request(proto::UpdateBuffer {
7935                                            project_id,
7936                                            buffer_id: buffer_id.into(),
7937                                            operations: chunk,
7938                                        })
7939                                        .await?;
7940                                }
7941                                anyhow::Ok(())
7942                            }
7943                            .log_err(),
7944                        )
7945                        .detach();
7946                }
7947            }
7948            Ok(())
7949        })??;
7950
7951        Ok(response)
7952    }
7953
7954    async fn handle_format_buffers(
7955        this: Model<Self>,
7956        envelope: TypedEnvelope<proto::FormatBuffers>,
7957        _: Arc<Client>,
7958        mut cx: AsyncAppContext,
7959    ) -> Result<proto::FormatBuffersResponse> {
7960        let sender_id = envelope.original_sender_id()?;
7961        let format = this.update(&mut cx, |this, cx| {
7962            let mut buffers = HashSet::default();
7963            for buffer_id in &envelope.payload.buffer_ids {
7964                let buffer_id = BufferId::new(*buffer_id)?;
7965                buffers.insert(
7966                    this.opened_buffers
7967                        .get(&buffer_id)
7968                        .and_then(|buffer| buffer.upgrade())
7969                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7970                );
7971            }
7972            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7973            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7974        })??;
7975
7976        let project_transaction = format.await?;
7977        let project_transaction = this.update(&mut cx, |this, cx| {
7978            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7979        })?;
7980        Ok(proto::FormatBuffersResponse {
7981            transaction: Some(project_transaction),
7982        })
7983    }
7984
7985    async fn handle_apply_additional_edits_for_completion(
7986        this: Model<Self>,
7987        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7988        _: Arc<Client>,
7989        mut cx: AsyncAppContext,
7990    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7991        let languages = this.update(&mut cx, |this, _| this.languages.clone())?;
7992        let (buffer, completion) = this.update(&mut cx, |this, cx| {
7993            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7994            let buffer = this
7995                .opened_buffers
7996                .get(&buffer_id)
7997                .and_then(|buffer| buffer.upgrade())
7998                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7999            let language = buffer.read(cx).language();
8000            let completion = language::proto::deserialize_completion(
8001                envelope
8002                    .payload
8003                    .completion
8004                    .ok_or_else(|| anyhow!("invalid completion"))?,
8005                language.cloned(),
8006                &languages,
8007            );
8008            Ok::<_, anyhow::Error>((buffer, completion))
8009        })??;
8010
8011        let completion = completion.await?;
8012
8013        let apply_additional_edits = this.update(&mut cx, |this, cx| {
8014            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
8015        })?;
8016
8017        Ok(proto::ApplyCompletionAdditionalEditsResponse {
8018            transaction: apply_additional_edits
8019                .await?
8020                .as_ref()
8021                .map(language::proto::serialize_transaction),
8022        })
8023    }
8024
8025    async fn handle_resolve_completion_documentation(
8026        this: Model<Self>,
8027        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
8028        _: Arc<Client>,
8029        mut cx: AsyncAppContext,
8030    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
8031        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
8032
8033        let completion = this
8034            .read_with(&mut cx, |this, _| {
8035                let id = LanguageServerId(envelope.payload.language_server_id as usize);
8036                let Some(server) = this.language_server_for_id(id) else {
8037                    return Err(anyhow!("No language server {id}"));
8038                };
8039
8040                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
8041            })??
8042            .await?;
8043
8044        let mut is_markdown = false;
8045        let text = match completion.documentation {
8046            Some(lsp::Documentation::String(text)) => text,
8047
8048            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
8049                is_markdown = kind == lsp::MarkupKind::Markdown;
8050                value
8051            }
8052
8053            _ => String::new(),
8054        };
8055
8056        Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
8057    }
8058
8059    async fn handle_apply_code_action(
8060        this: Model<Self>,
8061        envelope: TypedEnvelope<proto::ApplyCodeAction>,
8062        _: Arc<Client>,
8063        mut cx: AsyncAppContext,
8064    ) -> Result<proto::ApplyCodeActionResponse> {
8065        let sender_id = envelope.original_sender_id()?;
8066        let action = language::proto::deserialize_code_action(
8067            envelope
8068                .payload
8069                .action
8070                .ok_or_else(|| anyhow!("invalid action"))?,
8071        )?;
8072        let apply_code_action = this.update(&mut cx, |this, cx| {
8073            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8074            let buffer = this
8075                .opened_buffers
8076                .get(&buffer_id)
8077                .and_then(|buffer| buffer.upgrade())
8078                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
8079            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
8080        })??;
8081
8082        let project_transaction = apply_code_action.await?;
8083        let project_transaction = this.update(&mut cx, |this, cx| {
8084            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8085        })?;
8086        Ok(proto::ApplyCodeActionResponse {
8087            transaction: Some(project_transaction),
8088        })
8089    }
8090
8091    async fn handle_on_type_formatting(
8092        this: Model<Self>,
8093        envelope: TypedEnvelope<proto::OnTypeFormatting>,
8094        _: Arc<Client>,
8095        mut cx: AsyncAppContext,
8096    ) -> Result<proto::OnTypeFormattingResponse> {
8097        let on_type_formatting = this.update(&mut cx, |this, cx| {
8098            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8099            let buffer = this
8100                .opened_buffers
8101                .get(&buffer_id)
8102                .and_then(|buffer| buffer.upgrade())
8103                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8104            let position = envelope
8105                .payload
8106                .position
8107                .and_then(deserialize_anchor)
8108                .ok_or_else(|| anyhow!("invalid position"))?;
8109            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
8110                buffer,
8111                position,
8112                envelope.payload.trigger.clone(),
8113                cx,
8114            ))
8115        })??;
8116
8117        let transaction = on_type_formatting
8118            .await?
8119            .as_ref()
8120            .map(language::proto::serialize_transaction);
8121        Ok(proto::OnTypeFormattingResponse { transaction })
8122    }
8123
8124    async fn handle_inlay_hints(
8125        this: Model<Self>,
8126        envelope: TypedEnvelope<proto::InlayHints>,
8127        _: Arc<Client>,
8128        mut cx: AsyncAppContext,
8129    ) -> Result<proto::InlayHintsResponse> {
8130        let sender_id = envelope.original_sender_id()?;
8131        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8132        let buffer = this.update(&mut cx, |this, _| {
8133            this.opened_buffers
8134                .get(&buffer_id)
8135                .and_then(|buffer| buffer.upgrade())
8136                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
8137        })??;
8138        buffer
8139            .update(&mut cx, |buffer, _| {
8140                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
8141            })?
8142            .await
8143            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
8144
8145        let start = envelope
8146            .payload
8147            .start
8148            .and_then(deserialize_anchor)
8149            .context("missing range start")?;
8150        let end = envelope
8151            .payload
8152            .end
8153            .and_then(deserialize_anchor)
8154            .context("missing range end")?;
8155        let buffer_hints = this
8156            .update(&mut cx, |project, cx| {
8157                project.inlay_hints(buffer.clone(), start..end, cx)
8158            })?
8159            .await
8160            .context("inlay hints fetch")?;
8161
8162        Ok(this.update(&mut cx, |project, cx| {
8163            InlayHints::response_to_proto(
8164                buffer_hints,
8165                project,
8166                sender_id,
8167                &buffer.read(cx).version(),
8168                cx,
8169            )
8170        })?)
8171    }
8172
8173    async fn handle_resolve_inlay_hint(
8174        this: Model<Self>,
8175        envelope: TypedEnvelope<proto::ResolveInlayHint>,
8176        _: Arc<Client>,
8177        mut cx: AsyncAppContext,
8178    ) -> Result<proto::ResolveInlayHintResponse> {
8179        let proto_hint = envelope
8180            .payload
8181            .hint
8182            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
8183        let hint = InlayHints::proto_to_project_hint(proto_hint)
8184            .context("resolved proto inlay hint conversion")?;
8185        let buffer = this.update(&mut cx, |this, _cx| {
8186            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8187            this.opened_buffers
8188                .get(&buffer_id)
8189                .and_then(|buffer| buffer.upgrade())
8190                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
8191        })??;
8192        let response_hint = this
8193            .update(&mut cx, |project, cx| {
8194                project.resolve_inlay_hint(
8195                    hint,
8196                    buffer,
8197                    LanguageServerId(envelope.payload.language_server_id as usize),
8198                    cx,
8199                )
8200            })?
8201            .await
8202            .context("inlay hints fetch")?;
8203        Ok(proto::ResolveInlayHintResponse {
8204            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
8205        })
8206    }
8207
8208    async fn handle_refresh_inlay_hints(
8209        this: Model<Self>,
8210        _: TypedEnvelope<proto::RefreshInlayHints>,
8211        _: Arc<Client>,
8212        mut cx: AsyncAppContext,
8213    ) -> Result<proto::Ack> {
8214        this.update(&mut cx, |_, cx| {
8215            cx.emit(Event::RefreshInlayHints);
8216        })?;
8217        Ok(proto::Ack {})
8218    }
8219
8220    async fn handle_lsp_command<T: LspCommand>(
8221        this: Model<Self>,
8222        envelope: TypedEnvelope<T::ProtoRequest>,
8223        _: Arc<Client>,
8224        mut cx: AsyncAppContext,
8225    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
8226    where
8227        <T::LspRequest as lsp::request::Request>::Params: Send,
8228        <T::LspRequest as lsp::request::Request>::Result: Send,
8229    {
8230        let sender_id = envelope.original_sender_id()?;
8231        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
8232        let buffer_handle = this.update(&mut cx, |this, _cx| {
8233            this.opened_buffers
8234                .get(&buffer_id)
8235                .and_then(|buffer| buffer.upgrade())
8236                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
8237        })??;
8238        let request = T::from_proto(
8239            envelope.payload,
8240            this.clone(),
8241            buffer_handle.clone(),
8242            cx.clone(),
8243        )
8244        .await?;
8245        let response = this
8246            .update(&mut cx, |this, cx| {
8247                this.request_lsp(
8248                    buffer_handle.clone(),
8249                    LanguageServerToQuery::Primary,
8250                    request,
8251                    cx,
8252                )
8253            })?
8254            .await?;
8255        this.update(&mut cx, |this, cx| {
8256            Ok(T::response_to_proto(
8257                response,
8258                this,
8259                sender_id,
8260                &buffer_handle.read(cx).version(),
8261                cx,
8262            ))
8263        })?
8264    }
8265
8266    async fn handle_get_project_symbols(
8267        this: Model<Self>,
8268        envelope: TypedEnvelope<proto::GetProjectSymbols>,
8269        _: Arc<Client>,
8270        mut cx: AsyncAppContext,
8271    ) -> Result<proto::GetProjectSymbolsResponse> {
8272        let symbols = this
8273            .update(&mut cx, |this, cx| {
8274                this.symbols(&envelope.payload.query, cx)
8275            })?
8276            .await?;
8277
8278        Ok(proto::GetProjectSymbolsResponse {
8279            symbols: symbols.iter().map(serialize_symbol).collect(),
8280        })
8281    }
8282
8283    async fn handle_search_project(
8284        this: Model<Self>,
8285        envelope: TypedEnvelope<proto::SearchProject>,
8286        _: Arc<Client>,
8287        mut cx: AsyncAppContext,
8288    ) -> Result<proto::SearchProjectResponse> {
8289        let peer_id = envelope.original_sender_id()?;
8290        let query = SearchQuery::from_proto(envelope.payload)?;
8291        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
8292
8293        cx.spawn(move |mut cx| async move {
8294            let mut locations = Vec::new();
8295            while let Some((buffer, ranges)) = result.next().await {
8296                for range in ranges {
8297                    let start = serialize_anchor(&range.start);
8298                    let end = serialize_anchor(&range.end);
8299                    let buffer_id = this.update(&mut cx, |this, cx| {
8300                        this.create_buffer_for_peer(&buffer, peer_id, cx).into()
8301                    })?;
8302                    locations.push(proto::Location {
8303                        buffer_id,
8304                        start: Some(start),
8305                        end: Some(end),
8306                    });
8307                }
8308            }
8309            Ok(proto::SearchProjectResponse { locations })
8310        })
8311        .await
8312    }
8313
8314    async fn handle_open_buffer_for_symbol(
8315        this: Model<Self>,
8316        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
8317        _: Arc<Client>,
8318        mut cx: AsyncAppContext,
8319    ) -> Result<proto::OpenBufferForSymbolResponse> {
8320        let peer_id = envelope.original_sender_id()?;
8321        let symbol = envelope
8322            .payload
8323            .symbol
8324            .ok_or_else(|| anyhow!("invalid symbol"))?;
8325        let symbol = this
8326            .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
8327            .await?;
8328        let symbol = this.update(&mut cx, |this, _| {
8329            let signature = this.symbol_signature(&symbol.path);
8330            if signature == symbol.signature {
8331                Ok(symbol)
8332            } else {
8333                Err(anyhow!("invalid symbol signature"))
8334            }
8335        })??;
8336        let buffer = this
8337            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
8338            .await?;
8339
8340        this.update(&mut cx, |this, cx| {
8341            let is_private = buffer
8342                .read(cx)
8343                .file()
8344                .map(|f| f.is_private())
8345                .unwrap_or_default();
8346            if is_private {
8347                Err(anyhow!(ErrorCode::UnsharedItem))
8348            } else {
8349                Ok(proto::OpenBufferForSymbolResponse {
8350                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8351                })
8352            }
8353        })?
8354    }
8355
8356    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
8357        let mut hasher = Sha256::new();
8358        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
8359        hasher.update(project_path.path.to_string_lossy().as_bytes());
8360        hasher.update(self.nonce.to_be_bytes());
8361        hasher.finalize().as_slice().try_into().unwrap()
8362    }
8363
8364    async fn handle_open_buffer_by_id(
8365        this: Model<Self>,
8366        envelope: TypedEnvelope<proto::OpenBufferById>,
8367        _: Arc<Client>,
8368        mut cx: AsyncAppContext,
8369    ) -> Result<proto::OpenBufferResponse> {
8370        let peer_id = envelope.original_sender_id()?;
8371        let buffer_id = BufferId::new(envelope.payload.id)?;
8372        let buffer = this
8373            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
8374            .await?;
8375        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8376    }
8377
8378    async fn handle_open_buffer_by_path(
8379        this: Model<Self>,
8380        envelope: TypedEnvelope<proto::OpenBufferByPath>,
8381        _: Arc<Client>,
8382        mut cx: AsyncAppContext,
8383    ) -> Result<proto::OpenBufferResponse> {
8384        let peer_id = envelope.original_sender_id()?;
8385        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8386        let open_buffer = this.update(&mut cx, |this, cx| {
8387            this.open_buffer(
8388                ProjectPath {
8389                    worktree_id,
8390                    path: PathBuf::from(envelope.payload.path).into(),
8391                },
8392                cx,
8393            )
8394        })?;
8395
8396        let buffer = open_buffer.await?;
8397        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8398    }
8399
8400    fn respond_to_open_buffer_request(
8401        this: Model<Self>,
8402        buffer: Model<Buffer>,
8403        peer_id: proto::PeerId,
8404        cx: &mut AsyncAppContext,
8405    ) -> Result<proto::OpenBufferResponse> {
8406        this.update(cx, |this, cx| {
8407            let is_private = buffer
8408                .read(cx)
8409                .file()
8410                .map(|f| f.is_private())
8411                .unwrap_or_default();
8412            if is_private {
8413                Err(anyhow!(ErrorCode::UnsharedItem))
8414            } else {
8415                Ok(proto::OpenBufferResponse {
8416                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8417                })
8418            }
8419        })?
8420    }
8421
8422    fn serialize_project_transaction_for_peer(
8423        &mut self,
8424        project_transaction: ProjectTransaction,
8425        peer_id: proto::PeerId,
8426        cx: &mut AppContext,
8427    ) -> proto::ProjectTransaction {
8428        let mut serialized_transaction = proto::ProjectTransaction {
8429            buffer_ids: Default::default(),
8430            transactions: Default::default(),
8431        };
8432        for (buffer, transaction) in project_transaction.0 {
8433            serialized_transaction
8434                .buffer_ids
8435                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
8436            serialized_transaction
8437                .transactions
8438                .push(language::proto::serialize_transaction(&transaction));
8439        }
8440        serialized_transaction
8441    }
8442
8443    fn deserialize_project_transaction(
8444        &mut self,
8445        message: proto::ProjectTransaction,
8446        push_to_history: bool,
8447        cx: &mut ModelContext<Self>,
8448    ) -> Task<Result<ProjectTransaction>> {
8449        cx.spawn(move |this, mut cx| async move {
8450            let mut project_transaction = ProjectTransaction::default();
8451            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
8452            {
8453                let buffer_id = BufferId::new(buffer_id)?;
8454                let buffer = this
8455                    .update(&mut cx, |this, cx| {
8456                        this.wait_for_remote_buffer(buffer_id, cx)
8457                    })?
8458                    .await?;
8459                let transaction = language::proto::deserialize_transaction(transaction)?;
8460                project_transaction.0.insert(buffer, transaction);
8461            }
8462
8463            for (buffer, transaction) in &project_transaction.0 {
8464                buffer
8465                    .update(&mut cx, |buffer, _| {
8466                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
8467                    })?
8468                    .await?;
8469
8470                if push_to_history {
8471                    buffer.update(&mut cx, |buffer, _| {
8472                        buffer.push_transaction(transaction.clone(), Instant::now());
8473                    })?;
8474                }
8475            }
8476
8477            Ok(project_transaction)
8478        })
8479    }
8480
8481    fn create_buffer_for_peer(
8482        &mut self,
8483        buffer: &Model<Buffer>,
8484        peer_id: proto::PeerId,
8485        cx: &mut AppContext,
8486    ) -> BufferId {
8487        let buffer_id = buffer.read(cx).remote_id();
8488        if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
8489            updates_tx
8490                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
8491                .ok();
8492        }
8493        buffer_id
8494    }
8495
8496    fn wait_for_remote_buffer(
8497        &mut self,
8498        id: BufferId,
8499        cx: &mut ModelContext<Self>,
8500    ) -> Task<Result<Model<Buffer>>> {
8501        let mut opened_buffer_rx = self.opened_buffer.1.clone();
8502
8503        cx.spawn(move |this, mut cx| async move {
8504            let buffer = loop {
8505                let Some(this) = this.upgrade() else {
8506                    return Err(anyhow!("project dropped"));
8507                };
8508
8509                let buffer = this.update(&mut cx, |this, _cx| {
8510                    this.opened_buffers
8511                        .get(&id)
8512                        .and_then(|buffer| buffer.upgrade())
8513                })?;
8514
8515                if let Some(buffer) = buffer {
8516                    break buffer;
8517                } else if this.update(&mut cx, |this, _| this.is_disconnected())? {
8518                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
8519                }
8520
8521                this.update(&mut cx, |this, _| {
8522                    this.incomplete_remote_buffers.entry(id).or_default();
8523                })?;
8524                drop(this);
8525
8526                opened_buffer_rx
8527                    .next()
8528                    .await
8529                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
8530            };
8531
8532            Ok(buffer)
8533        })
8534    }
8535
8536    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
8537        let project_id = match self.client_state {
8538            ProjectClientState::Remote {
8539                sharing_has_stopped,
8540                remote_id,
8541                ..
8542            } => {
8543                if sharing_has_stopped {
8544                    return Task::ready(Err(anyhow!(
8545                        "can't synchronize remote buffers on a readonly project"
8546                    )));
8547                } else {
8548                    remote_id
8549                }
8550            }
8551            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
8552                return Task::ready(Err(anyhow!(
8553                    "can't synchronize remote buffers on a local project"
8554                )))
8555            }
8556        };
8557
8558        let client = self.client.clone();
8559        cx.spawn(move |this, mut cx| async move {
8560            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
8561                let buffers = this
8562                    .opened_buffers
8563                    .iter()
8564                    .filter_map(|(id, buffer)| {
8565                        let buffer = buffer.upgrade()?;
8566                        Some(proto::BufferVersion {
8567                            id: (*id).into(),
8568                            version: language::proto::serialize_version(&buffer.read(cx).version),
8569                        })
8570                    })
8571                    .collect();
8572                let incomplete_buffer_ids = this
8573                    .incomplete_remote_buffers
8574                    .keys()
8575                    .copied()
8576                    .collect::<Vec<_>>();
8577
8578                (buffers, incomplete_buffer_ids)
8579            })?;
8580            let response = client
8581                .request(proto::SynchronizeBuffers {
8582                    project_id,
8583                    buffers,
8584                })
8585                .await?;
8586
8587            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8588                response
8589                    .buffers
8590                    .into_iter()
8591                    .map(|buffer| {
8592                        let client = client.clone();
8593                        let buffer_id = match BufferId::new(buffer.id) {
8594                            Ok(id) => id,
8595                            Err(e) => {
8596                                return Task::ready(Err(e));
8597                            }
8598                        };
8599                        let remote_version = language::proto::deserialize_version(&buffer.version);
8600                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
8601                            let operations =
8602                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
8603                            cx.background_executor().spawn(async move {
8604                                let operations = operations.await;
8605                                for chunk in split_operations(operations) {
8606                                    client
8607                                        .request(proto::UpdateBuffer {
8608                                            project_id,
8609                                            buffer_id: buffer_id.into(),
8610                                            operations: chunk,
8611                                        })
8612                                        .await?;
8613                                }
8614                                anyhow::Ok(())
8615                            })
8616                        } else {
8617                            Task::ready(Ok(()))
8618                        }
8619                    })
8620                    .collect::<Vec<_>>()
8621            })?;
8622
8623            // Any incomplete buffers have open requests waiting. Request that the host sends
8624            // creates these buffers for us again to unblock any waiting futures.
8625            for id in incomplete_buffer_ids {
8626                cx.background_executor()
8627                    .spawn(client.request(proto::OpenBufferById {
8628                        project_id,
8629                        id: id.into(),
8630                    }))
8631                    .detach();
8632            }
8633
8634            futures::future::join_all(send_updates_for_buffers)
8635                .await
8636                .into_iter()
8637                .collect()
8638        })
8639    }
8640
8641    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8642        self.worktrees()
8643            .map(|worktree| {
8644                let worktree = worktree.read(cx);
8645                proto::WorktreeMetadata {
8646                    id: worktree.id().to_proto(),
8647                    root_name: worktree.root_name().into(),
8648                    visible: worktree.is_visible(),
8649                    abs_path: worktree.abs_path().to_string_lossy().into(),
8650                }
8651            })
8652            .collect()
8653    }
8654
8655    fn set_worktrees_from_proto(
8656        &mut self,
8657        worktrees: Vec<proto::WorktreeMetadata>,
8658        cx: &mut ModelContext<Project>,
8659    ) -> Result<()> {
8660        let replica_id = self.replica_id();
8661        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8662
8663        let mut old_worktrees_by_id = self
8664            .worktrees
8665            .drain(..)
8666            .filter_map(|worktree| {
8667                let worktree = worktree.upgrade()?;
8668                Some((worktree.read(cx).id(), worktree))
8669            })
8670            .collect::<HashMap<_, _>>();
8671
8672        for worktree in worktrees {
8673            if let Some(old_worktree) =
8674                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8675            {
8676                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8677            } else {
8678                let worktree =
8679                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8680                let _ = self.add_worktree(&worktree, cx);
8681            }
8682        }
8683
8684        self.metadata_changed(cx);
8685        for id in old_worktrees_by_id.keys() {
8686            cx.emit(Event::WorktreeRemoved(*id));
8687        }
8688
8689        Ok(())
8690    }
8691
8692    fn set_collaborators_from_proto(
8693        &mut self,
8694        messages: Vec<proto::Collaborator>,
8695        cx: &mut ModelContext<Self>,
8696    ) -> Result<()> {
8697        let mut collaborators = HashMap::default();
8698        for message in messages {
8699            let collaborator = Collaborator::from_proto(message)?;
8700            collaborators.insert(collaborator.peer_id, collaborator);
8701        }
8702        for old_peer_id in self.collaborators.keys() {
8703            if !collaborators.contains_key(old_peer_id) {
8704                cx.emit(Event::CollaboratorLeft(*old_peer_id));
8705            }
8706        }
8707        self.collaborators = collaborators;
8708        Ok(())
8709    }
8710
8711    fn deserialize_symbol(
8712        &self,
8713        serialized_symbol: proto::Symbol,
8714    ) -> impl Future<Output = Result<Symbol>> {
8715        let languages = self.languages.clone();
8716        async move {
8717            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8718            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8719            let start = serialized_symbol
8720                .start
8721                .ok_or_else(|| anyhow!("invalid start"))?;
8722            let end = serialized_symbol
8723                .end
8724                .ok_or_else(|| anyhow!("invalid end"))?;
8725            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8726            let path = ProjectPath {
8727                worktree_id,
8728                path: PathBuf::from(serialized_symbol.path).into(),
8729            };
8730            let language = languages
8731                .language_for_file(&path.path, None)
8732                .await
8733                .log_err();
8734            let adapter = language
8735                .as_ref()
8736                .and_then(|language| languages.lsp_adapters(language).first().cloned());
8737            Ok(Symbol {
8738                language_server_name: LanguageServerName(
8739                    serialized_symbol.language_server_name.into(),
8740                ),
8741                source_worktree_id,
8742                path,
8743                label: {
8744                    match language.as_ref().zip(adapter.as_ref()) {
8745                        Some((language, adapter)) => {
8746                            adapter
8747                                .label_for_symbol(&serialized_symbol.name, kind, language)
8748                                .await
8749                        }
8750                        None => None,
8751                    }
8752                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8753                },
8754
8755                name: serialized_symbol.name,
8756                range: Unclipped(PointUtf16::new(start.row, start.column))
8757                    ..Unclipped(PointUtf16::new(end.row, end.column)),
8758                kind,
8759                signature: serialized_symbol
8760                    .signature
8761                    .try_into()
8762                    .map_err(|_| anyhow!("invalid signature"))?,
8763            })
8764        }
8765    }
8766
8767    async fn handle_buffer_saved(
8768        this: Model<Self>,
8769        envelope: TypedEnvelope<proto::BufferSaved>,
8770        _: Arc<Client>,
8771        mut cx: AsyncAppContext,
8772    ) -> Result<()> {
8773        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8774        let version = deserialize_version(&envelope.payload.version);
8775        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8776        let mtime = envelope
8777            .payload
8778            .mtime
8779            .ok_or_else(|| anyhow!("missing mtime"))?
8780            .into();
8781
8782        this.update(&mut cx, |this, cx| {
8783            let buffer = this
8784                .opened_buffers
8785                .get(&buffer_id)
8786                .and_then(|buffer| buffer.upgrade())
8787                .or_else(|| {
8788                    this.incomplete_remote_buffers
8789                        .get(&buffer_id)
8790                        .and_then(|b| b.clone())
8791                });
8792            if let Some(buffer) = buffer {
8793                buffer.update(cx, |buffer, cx| {
8794                    buffer.did_save(version, fingerprint, mtime, cx);
8795                });
8796            }
8797            Ok(())
8798        })?
8799    }
8800
8801    async fn handle_buffer_reloaded(
8802        this: Model<Self>,
8803        envelope: TypedEnvelope<proto::BufferReloaded>,
8804        _: Arc<Client>,
8805        mut cx: AsyncAppContext,
8806    ) -> Result<()> {
8807        let payload = envelope.payload;
8808        let version = deserialize_version(&payload.version);
8809        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8810        let line_ending = deserialize_line_ending(
8811            proto::LineEnding::from_i32(payload.line_ending)
8812                .ok_or_else(|| anyhow!("missing line ending"))?,
8813        );
8814        let mtime = payload
8815            .mtime
8816            .ok_or_else(|| anyhow!("missing mtime"))?
8817            .into();
8818        let buffer_id = BufferId::new(payload.buffer_id)?;
8819        this.update(&mut cx, |this, cx| {
8820            let buffer = this
8821                .opened_buffers
8822                .get(&buffer_id)
8823                .and_then(|buffer| buffer.upgrade())
8824                .or_else(|| {
8825                    this.incomplete_remote_buffers
8826                        .get(&buffer_id)
8827                        .cloned()
8828                        .flatten()
8829                });
8830            if let Some(buffer) = buffer {
8831                buffer.update(cx, |buffer, cx| {
8832                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8833                });
8834            }
8835            Ok(())
8836        })?
8837    }
8838
8839    #[allow(clippy::type_complexity)]
8840    fn edits_from_lsp(
8841        &mut self,
8842        buffer: &Model<Buffer>,
8843        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8844        server_id: LanguageServerId,
8845        version: Option<i32>,
8846        cx: &mut ModelContext<Self>,
8847    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8848        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8849        cx.background_executor().spawn(async move {
8850            let snapshot = snapshot?;
8851            let mut lsp_edits = lsp_edits
8852                .into_iter()
8853                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8854                .collect::<Vec<_>>();
8855            lsp_edits.sort_by_key(|(range, _)| range.start);
8856
8857            let mut lsp_edits = lsp_edits.into_iter().peekable();
8858            let mut edits = Vec::new();
8859            while let Some((range, mut new_text)) = lsp_edits.next() {
8860                // Clip invalid ranges provided by the language server.
8861                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8862                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
8863
8864                // Combine any LSP edits that are adjacent.
8865                //
8866                // Also, combine LSP edits that are separated from each other by only
8867                // a newline. This is important because for some code actions,
8868                // Rust-analyzer rewrites the entire buffer via a series of edits that
8869                // are separated by unchanged newline characters.
8870                //
8871                // In order for the diffing logic below to work properly, any edits that
8872                // cancel each other out must be combined into one.
8873                while let Some((next_range, next_text)) = lsp_edits.peek() {
8874                    if next_range.start.0 > range.end {
8875                        if next_range.start.0.row > range.end.row + 1
8876                            || next_range.start.0.column > 0
8877                            || snapshot.clip_point_utf16(
8878                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8879                                Bias::Left,
8880                            ) > range.end
8881                        {
8882                            break;
8883                        }
8884                        new_text.push('\n');
8885                    }
8886                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8887                    new_text.push_str(next_text);
8888                    lsp_edits.next();
8889                }
8890
8891                // For multiline edits, perform a diff of the old and new text so that
8892                // we can identify the changes more precisely, preserving the locations
8893                // of any anchors positioned in the unchanged regions.
8894                if range.end.row > range.start.row {
8895                    let mut offset = range.start.to_offset(&snapshot);
8896                    let old_text = snapshot.text_for_range(range).collect::<String>();
8897
8898                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8899                    let mut moved_since_edit = true;
8900                    for change in diff.iter_all_changes() {
8901                        let tag = change.tag();
8902                        let value = change.value();
8903                        match tag {
8904                            ChangeTag::Equal => {
8905                                offset += value.len();
8906                                moved_since_edit = true;
8907                            }
8908                            ChangeTag::Delete => {
8909                                let start = snapshot.anchor_after(offset);
8910                                let end = snapshot.anchor_before(offset + value.len());
8911                                if moved_since_edit {
8912                                    edits.push((start..end, String::new()));
8913                                } else {
8914                                    edits.last_mut().unwrap().0.end = end;
8915                                }
8916                                offset += value.len();
8917                                moved_since_edit = false;
8918                            }
8919                            ChangeTag::Insert => {
8920                                if moved_since_edit {
8921                                    let anchor = snapshot.anchor_after(offset);
8922                                    edits.push((anchor..anchor, value.to_string()));
8923                                } else {
8924                                    edits.last_mut().unwrap().1.push_str(value);
8925                                }
8926                                moved_since_edit = false;
8927                            }
8928                        }
8929                    }
8930                } else if range.end == range.start {
8931                    let anchor = snapshot.anchor_after(range.start);
8932                    edits.push((anchor..anchor, new_text));
8933                } else {
8934                    let edit_start = snapshot.anchor_after(range.start);
8935                    let edit_end = snapshot.anchor_before(range.end);
8936                    edits.push((edit_start..edit_end, new_text));
8937                }
8938            }
8939
8940            Ok(edits)
8941        })
8942    }
8943
8944    fn buffer_snapshot_for_lsp_version(
8945        &mut self,
8946        buffer: &Model<Buffer>,
8947        server_id: LanguageServerId,
8948        version: Option<i32>,
8949        cx: &AppContext,
8950    ) -> Result<TextBufferSnapshot> {
8951        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8952
8953        if let Some(version) = version {
8954            let buffer_id = buffer.read(cx).remote_id();
8955            let snapshots = self
8956                .buffer_snapshots
8957                .get_mut(&buffer_id)
8958                .and_then(|m| m.get_mut(&server_id))
8959                .ok_or_else(|| {
8960                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
8961                })?;
8962
8963            let found_snapshot = snapshots
8964                .binary_search_by_key(&version, |e| e.version)
8965                .map(|ix| snapshots[ix].snapshot.clone())
8966                .map_err(|_| {
8967                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
8968                })?;
8969
8970            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
8971            Ok(found_snapshot)
8972        } else {
8973            Ok((buffer.read(cx)).text_snapshot())
8974        }
8975    }
8976
8977    pub fn language_servers(
8978        &self,
8979    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
8980        self.language_server_ids
8981            .iter()
8982            .map(|((worktree_id, server_name), server_id)| {
8983                (*server_id, server_name.clone(), *worktree_id)
8984            })
8985    }
8986
8987    pub fn supplementary_language_servers(
8988        &self,
8989    ) -> impl '_
8990           + Iterator<
8991        Item = (
8992            &LanguageServerId,
8993            &(LanguageServerName, Arc<LanguageServer>),
8994        ),
8995    > {
8996        self.supplementary_language_servers.iter()
8997    }
8998
8999    pub fn language_server_adapter_for_id(
9000        &self,
9001        id: LanguageServerId,
9002    ) -> Option<Arc<CachedLspAdapter>> {
9003        if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
9004            Some(adapter.clone())
9005        } else {
9006            None
9007        }
9008    }
9009
9010    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
9011        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
9012            Some(server.clone())
9013        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
9014            Some(Arc::clone(server))
9015        } else {
9016            None
9017        }
9018    }
9019
9020    pub fn language_servers_for_buffer(
9021        &self,
9022        buffer: &Buffer,
9023        cx: &AppContext,
9024    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9025        self.language_server_ids_for_buffer(buffer, cx)
9026            .into_iter()
9027            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
9028                LanguageServerState::Running {
9029                    adapter, server, ..
9030                } => Some((adapter, server)),
9031                _ => None,
9032            })
9033    }
9034
9035    fn primary_language_server_for_buffer(
9036        &self,
9037        buffer: &Buffer,
9038        cx: &AppContext,
9039    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9040        self.language_servers_for_buffer(buffer, cx).next()
9041    }
9042
9043    pub fn language_server_for_buffer(
9044        &self,
9045        buffer: &Buffer,
9046        server_id: LanguageServerId,
9047        cx: &AppContext,
9048    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9049        self.language_servers_for_buffer(buffer, cx)
9050            .find(|(_, s)| s.server_id() == server_id)
9051    }
9052
9053    fn language_server_ids_for_buffer(
9054        &self,
9055        buffer: &Buffer,
9056        cx: &AppContext,
9057    ) -> Vec<LanguageServerId> {
9058        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
9059            let worktree_id = file.worktree_id(cx);
9060            self.languages
9061                .lsp_adapters(&language)
9062                .iter()
9063                .flat_map(|adapter| {
9064                    let key = (worktree_id, adapter.name.clone());
9065                    self.language_server_ids.get(&key).copied()
9066                })
9067                .collect()
9068        } else {
9069            Vec::new()
9070        }
9071    }
9072}
9073
9074fn subscribe_for_copilot_events(
9075    copilot: &Model<Copilot>,
9076    cx: &mut ModelContext<'_, Project>,
9077) -> gpui::Subscription {
9078    cx.subscribe(
9079        copilot,
9080        |project, copilot, copilot_event, cx| match copilot_event {
9081            copilot::Event::CopilotLanguageServerStarted => {
9082                match copilot.read(cx).language_server() {
9083                    Some((name, copilot_server)) => {
9084                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
9085                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
9086                            let new_server_id = copilot_server.server_id();
9087                            let weak_project = cx.weak_model();
9088                            let copilot_log_subscription = copilot_server
9089                                .on_notification::<copilot::request::LogMessage, _>(
9090                                    move |params, mut cx| {
9091                                        weak_project.update(&mut cx, |_, cx| {
9092                                            cx.emit(Event::LanguageServerLog(
9093                                                new_server_id,
9094                                                params.message,
9095                                            ));
9096                                        }).ok();
9097                                    },
9098                                );
9099                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
9100                            project.copilot_log_subscription = Some(copilot_log_subscription);
9101                            cx.emit(Event::LanguageServerAdded(new_server_id));
9102                        }
9103                    }
9104                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
9105                }
9106            }
9107        },
9108    )
9109}
9110
9111fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
9112    let mut literal_end = 0;
9113    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
9114        if part.contains(&['*', '?', '{', '}']) {
9115            break;
9116        } else {
9117            if i > 0 {
9118                // Account for separator prior to this part
9119                literal_end += path::MAIN_SEPARATOR.len_utf8();
9120            }
9121            literal_end += part.len();
9122        }
9123    }
9124    &glob[..literal_end]
9125}
9126
9127impl WorktreeHandle {
9128    pub fn upgrade(&self) -> Option<Model<Worktree>> {
9129        match self {
9130            WorktreeHandle::Strong(handle) => Some(handle.clone()),
9131            WorktreeHandle::Weak(handle) => handle.upgrade(),
9132        }
9133    }
9134
9135    pub fn handle_id(&self) -> usize {
9136        match self {
9137            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
9138            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
9139        }
9140    }
9141}
9142
9143impl OpenBuffer {
9144    pub fn upgrade(&self) -> Option<Model<Buffer>> {
9145        match self {
9146            OpenBuffer::Strong(handle) => Some(handle.clone()),
9147            OpenBuffer::Weak(handle) => handle.upgrade(),
9148            OpenBuffer::Operations(_) => None,
9149        }
9150    }
9151}
9152
9153pub struct PathMatchCandidateSet {
9154    pub snapshot: Snapshot,
9155    pub include_ignored: bool,
9156    pub include_root_name: bool,
9157}
9158
9159impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
9160    type Candidates = PathMatchCandidateSetIter<'a>;
9161
9162    fn id(&self) -> usize {
9163        self.snapshot.id().to_usize()
9164    }
9165
9166    fn len(&self) -> usize {
9167        if self.include_ignored {
9168            self.snapshot.file_count()
9169        } else {
9170            self.snapshot.visible_file_count()
9171        }
9172    }
9173
9174    fn prefix(&self) -> Arc<str> {
9175        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
9176            self.snapshot.root_name().into()
9177        } else if self.include_root_name {
9178            format!("{}/", self.snapshot.root_name()).into()
9179        } else {
9180            "".into()
9181        }
9182    }
9183
9184    fn candidates(&'a self, start: usize) -> Self::Candidates {
9185        PathMatchCandidateSetIter {
9186            traversal: self.snapshot.files(self.include_ignored, start),
9187        }
9188    }
9189}
9190
9191pub struct PathMatchCandidateSetIter<'a> {
9192    traversal: Traversal<'a>,
9193}
9194
9195impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
9196    type Item = fuzzy::PathMatchCandidate<'a>;
9197
9198    fn next(&mut self) -> Option<Self::Item> {
9199        self.traversal.next().map(|entry| {
9200            if let EntryKind::File(char_bag) = entry.kind {
9201                fuzzy::PathMatchCandidate {
9202                    path: &entry.path,
9203                    char_bag,
9204                }
9205            } else {
9206                unreachable!()
9207            }
9208        })
9209    }
9210}
9211
9212impl EventEmitter<Event> for Project {}
9213
9214impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
9215    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
9216        Self {
9217            worktree_id,
9218            path: path.as_ref().into(),
9219        }
9220    }
9221}
9222
9223struct ProjectLspAdapterDelegate {
9224    project: Model<Project>,
9225    worktree: worktree::Snapshot,
9226    fs: Arc<dyn Fs>,
9227    http_client: Arc<dyn HttpClient>,
9228    language_registry: Arc<LanguageRegistry>,
9229}
9230
9231impl ProjectLspAdapterDelegate {
9232    fn new(project: &Project, worktree: &Model<Worktree>, cx: &ModelContext<Project>) -> Arc<Self> {
9233        Arc::new(Self {
9234            project: cx.handle(),
9235            worktree: worktree.read(cx).snapshot(),
9236            fs: project.fs.clone(),
9237            http_client: project.client.http_client(),
9238            language_registry: project.languages.clone(),
9239        })
9240    }
9241}
9242
9243#[async_trait]
9244impl LspAdapterDelegate for ProjectLspAdapterDelegate {
9245    fn show_notification(&self, message: &str, cx: &mut AppContext) {
9246        self.project
9247            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
9248    }
9249
9250    fn http_client(&self) -> Arc<dyn HttpClient> {
9251        self.http_client.clone()
9252    }
9253
9254    async fn which_command(&self, command: OsString) -> Option<(PathBuf, HashMap<String, String>)> {
9255        let worktree_abs_path = self.worktree.abs_path();
9256
9257        let shell_env = load_shell_environment(&worktree_abs_path)
9258            .await
9259            .with_context(|| {
9260                format!("failed to determine load login shell environment in {worktree_abs_path:?}")
9261            })
9262            .log_err();
9263
9264        if let Some(shell_env) = shell_env {
9265            let shell_path = shell_env.get("PATH");
9266            match which::which_in(&command, shell_path, &worktree_abs_path) {
9267                Ok(command_path) => Some((command_path, shell_env)),
9268                Err(error) => {
9269                    log::warn!(
9270                        "failed to determine path for command {:?} in shell PATH {:?}: {error}",
9271                        command.to_string_lossy(),
9272                        shell_path.map(String::as_str).unwrap_or("")
9273                    );
9274                    None
9275                }
9276            }
9277        } else {
9278            None
9279        }
9280    }
9281
9282    fn update_status(
9283        &self,
9284        server_name: LanguageServerName,
9285        status: language::LanguageServerBinaryStatus,
9286    ) {
9287        self.language_registry
9288            .update_lsp_status(server_name, status);
9289    }
9290
9291    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
9292        if self.worktree.entry_for_path(&path).is_none() {
9293            return Err(anyhow!("no such path {path:?}"));
9294        }
9295        let path = self.worktree.absolutize(path.as_ref())?;
9296        let content = self.fs.load(&path).await?;
9297        Ok(content)
9298    }
9299}
9300
9301fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
9302    proto::Symbol {
9303        language_server_name: symbol.language_server_name.0.to_string(),
9304        source_worktree_id: symbol.source_worktree_id.to_proto(),
9305        worktree_id: symbol.path.worktree_id.to_proto(),
9306        path: symbol.path.path.to_string_lossy().to_string(),
9307        name: symbol.name.clone(),
9308        kind: unsafe { mem::transmute(symbol.kind) },
9309        start: Some(proto::PointUtf16 {
9310            row: symbol.range.start.0.row,
9311            column: symbol.range.start.0.column,
9312        }),
9313        end: Some(proto::PointUtf16 {
9314            row: symbol.range.end.0.row,
9315            column: symbol.range.end.0.column,
9316        }),
9317        signature: symbol.signature.to_vec(),
9318    }
9319}
9320
9321fn relativize_path(base: &Path, path: &Path) -> PathBuf {
9322    let mut path_components = path.components();
9323    let mut base_components = base.components();
9324    let mut components: Vec<Component> = Vec::new();
9325    loop {
9326        match (path_components.next(), base_components.next()) {
9327            (None, None) => break,
9328            (Some(a), None) => {
9329                components.push(a);
9330                components.extend(path_components.by_ref());
9331                break;
9332            }
9333            (None, _) => components.push(Component::ParentDir),
9334            (Some(a), Some(b)) if components.is_empty() && a == b => (),
9335            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
9336            (Some(a), Some(_)) => {
9337                components.push(Component::ParentDir);
9338                for _ in base_components {
9339                    components.push(Component::ParentDir);
9340                }
9341                components.push(a);
9342                components.extend(path_components.by_ref());
9343                break;
9344            }
9345        }
9346    }
9347    components.iter().map(|c| c.as_os_str()).collect()
9348}
9349
9350fn resolve_path(base: &Path, path: &Path) -> PathBuf {
9351    let mut result = base.to_path_buf();
9352    for component in path.components() {
9353        match component {
9354            Component::ParentDir => {
9355                result.pop();
9356            }
9357            Component::CurDir => (),
9358            _ => result.push(component),
9359        }
9360    }
9361    result
9362}
9363
9364impl Item for Buffer {
9365    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
9366        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
9367    }
9368
9369    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
9370        File::from_dyn(self.file()).map(|file| ProjectPath {
9371            worktree_id: file.worktree_id(cx),
9372            path: file.path().clone(),
9373        })
9374    }
9375}
9376
9377async fn wait_for_loading_buffer(
9378    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
9379) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
9380    loop {
9381        if let Some(result) = receiver.borrow().as_ref() {
9382            match result {
9383                Ok(buffer) => return Ok(buffer.to_owned()),
9384                Err(e) => return Err(e.to_owned()),
9385            }
9386        }
9387        receiver.next().await;
9388    }
9389}
9390
9391fn include_text(server: &lsp::LanguageServer) -> bool {
9392    server
9393        .capabilities()
9394        .text_document_sync
9395        .as_ref()
9396        .and_then(|sync| match sync {
9397            lsp::TextDocumentSyncCapability::Kind(_) => None,
9398            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
9399        })
9400        .and_then(|save_options| match save_options {
9401            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
9402            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
9403        })
9404        .unwrap_or(false)
9405}
9406
9407async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
9408    let marker = "ZED_SHELL_START";
9409    let shell = env::var("SHELL").context(
9410        "SHELL environment variable is not assigned so we can't source login environment variables",
9411    )?;
9412    let output = smol::process::Command::new(&shell)
9413        .args([
9414            "-i",
9415            "-c",
9416            // What we're doing here is to spawn a shell and then `cd` into
9417            // the project directory to get the env in there as if the user
9418            // `cd`'d into it. We do that because tools like direnv, asdf, ...
9419            // hook into `cd` and only set up the env after that.
9420            //
9421            // The `exit 0` is the result of hours of debugging, trying to find out
9422            // why running this command here, without `exit 0`, would mess
9423            // up signal process for our process so that `ctrl-c` doesn't work
9424            // anymore.
9425            // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
9426            // do that, but it does, and `exit 0` helps.
9427            &format!("cd {dir:?}; echo {marker}; /usr/bin/env -0; exit 0;"),
9428        ])
9429        .output()
9430        .await
9431        .context("failed to spawn login shell to source login environment variables")?;
9432
9433    anyhow::ensure!(
9434        output.status.success(),
9435        "login shell exited with error {:?}",
9436        output.status
9437    );
9438
9439    let stdout = String::from_utf8_lossy(&output.stdout);
9440    let env_output_start = stdout.find(marker).ok_or_else(|| {
9441        anyhow!(
9442            "failed to parse output of `env` command in login shell: {}",
9443            stdout
9444        )
9445    })?;
9446
9447    let mut parsed_env = HashMap::default();
9448    let env_output = &stdout[env_output_start + marker.len()..];
9449    for line in env_output.split_terminator('\0') {
9450        if let Some(separator_index) = line.find('=') {
9451            let key = line[..separator_index].to_string();
9452            let value = line[separator_index + 1..].to_string();
9453            parsed_env.insert(key, value);
9454        }
9455    }
9456    Ok(parsed_env)
9457}