project.rs

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