project.rs

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