project.rs

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