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::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    #[cfg(not(any(test, feature = "test-support")))]
 176    installed_plugins: HashSet<&'static str>,
 177}
 178
 179struct DelayedDebounced {
 180    task: Option<Task<()>>,
 181    cancel_channel: Option<oneshot::Sender<()>>,
 182}
 183
 184enum LanguageServerToQuery {
 185    Primary,
 186    Other(LanguageServerId),
 187}
 188
 189impl DelayedDebounced {
 190    fn new() -> DelayedDebounced {
 191        DelayedDebounced {
 192            task: None,
 193            cancel_channel: None,
 194        }
 195    }
 196
 197    fn fire_new<F>(&mut self, delay: Duration, cx: &mut ModelContext<Project>, func: F)
 198    where
 199        F: 'static + FnOnce(&mut Project, &mut ModelContext<Project>) -> Task<()>,
 200    {
 201        if let Some(channel) = self.cancel_channel.take() {
 202            _ = channel.send(());
 203        }
 204
 205        let (sender, mut receiver) = oneshot::channel::<()>();
 206        self.cancel_channel = Some(sender);
 207
 208        let previous_task = self.task.take();
 209        self.task = Some(cx.spawn(|workspace, mut cx| async move {
 210            let mut timer = cx.background().timer(delay).fuse();
 211            if let Some(previous_task) = previous_task {
 212                previous_task.await;
 213            }
 214
 215            futures::select_biased! {
 216                _ = receiver => return,
 217                    _ = timer => {}
 218            }
 219
 220            workspace
 221                .update(&mut cx, |workspace, cx| (func)(workspace, cx))
 222                .await;
 223        }));
 224    }
 225}
 226
 227struct LspBufferSnapshot {
 228    version: i32,
 229    snapshot: TextBufferSnapshot,
 230}
 231
 232/// Message ordered with respect to buffer operations
 233enum BufferOrderedMessage {
 234    Operation {
 235        buffer_id: u64,
 236        operation: proto::Operation,
 237    },
 238    LanguageServerUpdate {
 239        language_server_id: LanguageServerId,
 240        message: proto::update_language_server::Variant,
 241    },
 242    Resync,
 243}
 244
 245enum LocalProjectUpdate {
 246    WorktreesChanged,
 247    CreateBufferForPeer {
 248        peer_id: proto::PeerId,
 249        buffer_id: u64,
 250    },
 251}
 252
 253enum OpenBuffer {
 254    Strong(ModelHandle<Buffer>),
 255    Weak(WeakModelHandle<Buffer>),
 256    Operations(Vec<Operation>),
 257}
 258
 259#[derive(Clone)]
 260enum WorktreeHandle {
 261    Strong(ModelHandle<Worktree>),
 262    Weak(WeakModelHandle<Worktree>),
 263}
 264
 265enum ProjectClientState {
 266    Local {
 267        remote_id: u64,
 268        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
 269        _send_updates: Task<()>,
 270    },
 271    Remote {
 272        sharing_has_stopped: bool,
 273        remote_id: u64,
 274        replica_id: ReplicaId,
 275    },
 276}
 277
 278#[derive(Clone, Debug, PartialEq)]
 279pub enum Event {
 280    LanguageServerAdded(LanguageServerId),
 281    LanguageServerRemoved(LanguageServerId),
 282    LanguageServerLog(LanguageServerId, String),
 283    Notification(String),
 284    ActiveEntryChanged(Option<ProjectEntryId>),
 285    ActivateProjectPanel,
 286    WorktreeAdded,
 287    WorktreeRemoved(WorktreeId),
 288    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 289    DiskBasedDiagnosticsStarted {
 290        language_server_id: LanguageServerId,
 291    },
 292    DiskBasedDiagnosticsFinished {
 293        language_server_id: LanguageServerId,
 294    },
 295    DiagnosticsUpdated {
 296        path: ProjectPath,
 297        language_server_id: LanguageServerId,
 298    },
 299    RemoteIdChanged(Option<u64>),
 300    DisconnectedFromHost,
 301    Closed,
 302    DeletedEntry(ProjectEntryId),
 303    CollaboratorUpdated {
 304        old_peer_id: proto::PeerId,
 305        new_peer_id: proto::PeerId,
 306    },
 307    CollaboratorJoined(proto::PeerId),
 308    CollaboratorLeft(proto::PeerId),
 309    RefreshInlayHints,
 310}
 311
 312pub enum LanguageServerState {
 313    Starting(Task<Option<Arc<LanguageServer>>>),
 314
 315    Running {
 316        language: Arc<Language>,
 317        adapter: Arc<CachedLspAdapter>,
 318        server: Arc<LanguageServer>,
 319        watched_paths: HashMap<WorktreeId, GlobSet>,
 320        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
 321    },
 322}
 323
 324#[derive(Serialize)]
 325pub struct LanguageServerStatus {
 326    pub name: String,
 327    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 328    pub has_pending_diagnostic_updates: bool,
 329    progress_tokens: HashSet<String>,
 330}
 331
 332#[derive(Clone, Debug, Serialize)]
 333pub struct LanguageServerProgress {
 334    pub message: Option<String>,
 335    pub percentage: Option<usize>,
 336    #[serde(skip_serializing)]
 337    pub last_update_at: Instant,
 338}
 339
 340#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 341pub struct ProjectPath {
 342    pub worktree_id: WorktreeId,
 343    pub path: Arc<Path>,
 344}
 345
 346#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 347pub struct DiagnosticSummary {
 348    pub error_count: usize,
 349    pub warning_count: usize,
 350}
 351
 352#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 353pub struct Location {
 354    pub buffer: ModelHandle<Buffer>,
 355    pub range: Range<language::Anchor>,
 356}
 357
 358#[derive(Debug, Clone, PartialEq, Eq)]
 359pub struct InlayHint {
 360    pub position: language::Anchor,
 361    pub label: InlayHintLabel,
 362    pub kind: Option<InlayHintKind>,
 363    pub padding_left: bool,
 364    pub padding_right: bool,
 365    pub tooltip: Option<InlayHintTooltip>,
 366    pub resolve_state: ResolveState,
 367}
 368
 369#[derive(Debug, Clone, PartialEq, Eq)]
 370pub enum ResolveState {
 371    Resolved,
 372    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 373    Resolving,
 374}
 375
 376impl InlayHint {
 377    pub fn text(&self) -> String {
 378        match &self.label {
 379            InlayHintLabel::String(s) => s.to_owned(),
 380            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
 381        }
 382    }
 383}
 384
 385#[derive(Debug, Clone, PartialEq, Eq)]
 386pub enum InlayHintLabel {
 387    String(String),
 388    LabelParts(Vec<InlayHintLabelPart>),
 389}
 390
 391#[derive(Debug, Clone, PartialEq, Eq)]
 392pub struct InlayHintLabelPart {
 393    pub value: String,
 394    pub tooltip: Option<InlayHintLabelPartTooltip>,
 395    pub location: Option<(LanguageServerId, lsp::Location)>,
 396}
 397
 398#[derive(Debug, Clone, PartialEq, Eq)]
 399pub enum InlayHintTooltip {
 400    String(String),
 401    MarkupContent(MarkupContent),
 402}
 403
 404#[derive(Debug, Clone, PartialEq, Eq)]
 405pub enum InlayHintLabelPartTooltip {
 406    String(String),
 407    MarkupContent(MarkupContent),
 408}
 409
 410#[derive(Debug, Clone, PartialEq, Eq)]
 411pub struct MarkupContent {
 412    pub kind: HoverBlockKind,
 413    pub value: String,
 414}
 415
 416#[derive(Debug, Clone)]
 417pub struct LocationLink {
 418    pub origin: Option<Location>,
 419    pub target: Location,
 420}
 421
 422#[derive(Debug)]
 423pub struct DocumentHighlight {
 424    pub range: Range<language::Anchor>,
 425    pub kind: DocumentHighlightKind,
 426}
 427
 428#[derive(Clone, Debug)]
 429pub struct Symbol {
 430    pub language_server_name: LanguageServerName,
 431    pub source_worktree_id: WorktreeId,
 432    pub path: ProjectPath,
 433    pub label: CodeLabel,
 434    pub name: String,
 435    pub kind: lsp::SymbolKind,
 436    pub range: Range<Unclipped<PointUtf16>>,
 437    pub signature: [u8; 32],
 438}
 439
 440#[derive(Clone, Debug, PartialEq)]
 441pub struct HoverBlock {
 442    pub text: String,
 443    pub kind: HoverBlockKind,
 444}
 445
 446#[derive(Clone, Debug, PartialEq, Eq)]
 447pub enum HoverBlockKind {
 448    PlainText,
 449    Markdown,
 450    Code { language: String },
 451}
 452
 453#[derive(Debug)]
 454pub struct Hover {
 455    pub contents: Vec<HoverBlock>,
 456    pub range: Option<Range<language::Anchor>>,
 457    pub language: Option<Arc<Language>>,
 458}
 459
 460impl Hover {
 461    pub fn is_empty(&self) -> bool {
 462        self.contents.iter().all(|block| block.text.is_empty())
 463    }
 464}
 465
 466#[derive(Default)]
 467pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 468
 469impl DiagnosticSummary {
 470    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 471        let mut this = Self {
 472            error_count: 0,
 473            warning_count: 0,
 474        };
 475
 476        for entry in diagnostics {
 477            if entry.diagnostic.is_primary {
 478                match entry.diagnostic.severity {
 479                    DiagnosticSeverity::ERROR => this.error_count += 1,
 480                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 481                    _ => {}
 482                }
 483            }
 484        }
 485
 486        this
 487    }
 488
 489    pub fn is_empty(&self) -> bool {
 490        self.error_count == 0 && self.warning_count == 0
 491    }
 492
 493    pub fn to_proto(
 494        &self,
 495        language_server_id: LanguageServerId,
 496        path: &Path,
 497    ) -> proto::DiagnosticSummary {
 498        proto::DiagnosticSummary {
 499            path: path.to_string_lossy().to_string(),
 500            language_server_id: language_server_id.0 as u64,
 501            error_count: self.error_count as u32,
 502            warning_count: self.warning_count as u32,
 503        }
 504    }
 505}
 506
 507#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 508pub struct ProjectEntryId(usize);
 509
 510impl ProjectEntryId {
 511    pub const MAX: Self = Self(usize::MAX);
 512
 513    pub fn new(counter: &AtomicUsize) -> Self {
 514        Self(counter.fetch_add(1, SeqCst))
 515    }
 516
 517    pub fn from_proto(id: u64) -> Self {
 518        Self(id as usize)
 519    }
 520
 521    pub fn to_proto(&self) -> u64 {
 522        self.0 as u64
 523    }
 524
 525    pub fn to_usize(&self) -> usize {
 526        self.0
 527    }
 528}
 529
 530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 531pub enum FormatTrigger {
 532    Save,
 533    Manual,
 534}
 535
 536struct ProjectLspAdapterDelegate {
 537    project: ModelHandle<Project>,
 538    http_client: Arc<dyn HttpClient>,
 539}
 540
 541impl FormatTrigger {
 542    fn from_proto(value: i32) -> FormatTrigger {
 543        match value {
 544            0 => FormatTrigger::Save,
 545            1 => FormatTrigger::Manual,
 546            _ => FormatTrigger::Save,
 547        }
 548    }
 549}
 550#[derive(Clone, Debug, PartialEq)]
 551enum SearchMatchCandidate {
 552    OpenBuffer {
 553        buffer: ModelHandle<Buffer>,
 554        // This might be an unnamed file without representation on filesystem
 555        path: Option<Arc<Path>>,
 556    },
 557    Path {
 558        worktree_id: WorktreeId,
 559        path: Arc<Path>,
 560    },
 561}
 562
 563type SearchMatchCandidateIndex = usize;
 564impl SearchMatchCandidate {
 565    fn path(&self) -> Option<Arc<Path>> {
 566        match self {
 567            SearchMatchCandidate::OpenBuffer { path, .. } => path.clone(),
 568            SearchMatchCandidate::Path { path, .. } => Some(path.clone()),
 569        }
 570    }
 571}
 572
 573impl Project {
 574    pub fn init_settings(cx: &mut AppContext) {
 575        settings::register::<ProjectSettings>(cx);
 576    }
 577
 578    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
 579        Self::init_settings(cx);
 580
 581        client.add_model_message_handler(Self::handle_add_collaborator);
 582        client.add_model_message_handler(Self::handle_update_project_collaborator);
 583        client.add_model_message_handler(Self::handle_remove_collaborator);
 584        client.add_model_message_handler(Self::handle_buffer_reloaded);
 585        client.add_model_message_handler(Self::handle_buffer_saved);
 586        client.add_model_message_handler(Self::handle_start_language_server);
 587        client.add_model_message_handler(Self::handle_update_language_server);
 588        client.add_model_message_handler(Self::handle_update_project);
 589        client.add_model_message_handler(Self::handle_unshare_project);
 590        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 591        client.add_model_message_handler(Self::handle_update_buffer_file);
 592        client.add_model_request_handler(Self::handle_update_buffer);
 593        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 594        client.add_model_message_handler(Self::handle_update_worktree);
 595        client.add_model_message_handler(Self::handle_update_worktree_settings);
 596        client.add_model_request_handler(Self::handle_create_project_entry);
 597        client.add_model_request_handler(Self::handle_rename_project_entry);
 598        client.add_model_request_handler(Self::handle_copy_project_entry);
 599        client.add_model_request_handler(Self::handle_delete_project_entry);
 600        client.add_model_request_handler(Self::handle_expand_project_entry);
 601        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 602        client.add_model_request_handler(Self::handle_apply_code_action);
 603        client.add_model_request_handler(Self::handle_on_type_formatting);
 604        client.add_model_request_handler(Self::handle_inlay_hints);
 605        client.add_model_request_handler(Self::handle_resolve_completion_documentation);
 606        client.add_model_request_handler(Self::handle_resolve_inlay_hint);
 607        client.add_model_request_handler(Self::handle_refresh_inlay_hints);
 608        client.add_model_request_handler(Self::handle_reload_buffers);
 609        client.add_model_request_handler(Self::handle_synchronize_buffers);
 610        client.add_model_request_handler(Self::handle_format_buffers);
 611        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
 612        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
 613        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 614        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 615        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
 616        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 617        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 618        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 619        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 620        client.add_model_request_handler(Self::handle_search_project);
 621        client.add_model_request_handler(Self::handle_get_project_symbols);
 622        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 623        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 624        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 625        client.add_model_request_handler(Self::handle_save_buffer);
 626        client.add_model_message_handler(Self::handle_update_diff_base);
 627    }
 628
 629    pub fn local(
 630        client: Arc<Client>,
 631        node: Arc<dyn NodeRuntime>,
 632        user_store: ModelHandle<UserStore>,
 633        languages: Arc<LanguageRegistry>,
 634        fs: Arc<dyn Fs>,
 635        cx: &mut AppContext,
 636    ) -> ModelHandle<Self> {
 637        cx.add_model(|cx: &mut ModelContext<Self>| {
 638            let (tx, rx) = mpsc::unbounded();
 639            cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 640                .detach();
 641            let copilot_lsp_subscription =
 642                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 643            Self {
 644                worktrees: Default::default(),
 645                buffer_ordered_messages_tx: tx,
 646                collaborators: Default::default(),
 647                next_buffer_id: 0,
 648                opened_buffers: Default::default(),
 649                shared_buffers: Default::default(),
 650                incomplete_remote_buffers: Default::default(),
 651                loading_buffers_by_path: Default::default(),
 652                loading_local_worktrees: Default::default(),
 653                local_buffer_ids_by_path: Default::default(),
 654                local_buffer_ids_by_entry_id: Default::default(),
 655                buffer_snapshots: Default::default(),
 656                join_project_response_message_id: 0,
 657                client_state: None,
 658                opened_buffer: watch::channel(),
 659                client_subscriptions: Vec::new(),
 660                _subscriptions: vec![
 661                    cx.observe_global::<SettingsStore, _>(Self::on_settings_changed)
 662                ],
 663                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 664                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 665                active_entry: None,
 666                languages,
 667                client,
 668                user_store,
 669                fs,
 670                next_entry_id: Default::default(),
 671                next_diagnostic_group_id: Default::default(),
 672                supplementary_language_servers: HashMap::default(),
 673                language_servers: Default::default(),
 674                language_server_ids: Default::default(),
 675                language_server_statuses: Default::default(),
 676                last_workspace_edits_by_language_server: Default::default(),
 677                buffers_being_formatted: Default::default(),
 678                buffers_needing_diff: Default::default(),
 679                git_diff_debouncer: DelayedDebounced::new(),
 680                nonce: StdRng::from_entropy().gen(),
 681                terminals: Terminals {
 682                    local_handles: Vec::new(),
 683                },
 684                copilot_lsp_subscription,
 685                copilot_log_subscription: None,
 686                current_lsp_settings: settings::get::<ProjectSettings>(cx).lsp.clone(),
 687                node: Some(node),
 688                default_prettier: None,
 689                prettiers_per_worktree: HashMap::default(),
 690                prettier_instances: HashMap::default(),
 691            }
 692        })
 693    }
 694
 695    pub async fn remote(
 696        remote_id: u64,
 697        client: Arc<Client>,
 698        user_store: ModelHandle<UserStore>,
 699        languages: Arc<LanguageRegistry>,
 700        fs: Arc<dyn Fs>,
 701        mut cx: AsyncAppContext,
 702    ) -> Result<ModelHandle<Self>> {
 703        client.authenticate_and_connect(true, &cx).await?;
 704
 705        let subscription = client.subscribe_to_entity(remote_id)?;
 706        let response = client
 707            .request_envelope(proto::JoinProject {
 708                project_id: remote_id,
 709            })
 710            .await?;
 711        let this = cx.add_model(|cx| {
 712            let replica_id = response.payload.replica_id as ReplicaId;
 713
 714            let mut worktrees = Vec::new();
 715            for worktree in response.payload.worktrees {
 716                let worktree = cx.update(|cx| {
 717                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
 718                });
 719                worktrees.push(worktree);
 720            }
 721
 722            let (tx, rx) = mpsc::unbounded();
 723            cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 724                .detach();
 725            let copilot_lsp_subscription =
 726                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 727            let mut this = Self {
 728                worktrees: Vec::new(),
 729                buffer_ordered_messages_tx: tx,
 730                loading_buffers_by_path: Default::default(),
 731                next_buffer_id: 0,
 732                opened_buffer: watch::channel(),
 733                shared_buffers: Default::default(),
 734                incomplete_remote_buffers: Default::default(),
 735                loading_local_worktrees: Default::default(),
 736                local_buffer_ids_by_path: Default::default(),
 737                local_buffer_ids_by_entry_id: Default::default(),
 738                active_entry: None,
 739                collaborators: Default::default(),
 740                join_project_response_message_id: response.message_id,
 741                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 742                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 743                languages,
 744                user_store: user_store.clone(),
 745                fs,
 746                next_entry_id: Default::default(),
 747                next_diagnostic_group_id: Default::default(),
 748                client_subscriptions: Default::default(),
 749                _subscriptions: Default::default(),
 750                client: client.clone(),
 751                client_state: Some(ProjectClientState::Remote {
 752                    sharing_has_stopped: false,
 753                    remote_id,
 754                    replica_id,
 755                }),
 756                supplementary_language_servers: HashMap::default(),
 757                language_servers: Default::default(),
 758                language_server_ids: Default::default(),
 759                language_server_statuses: response
 760                    .payload
 761                    .language_servers
 762                    .into_iter()
 763                    .map(|server| {
 764                        (
 765                            LanguageServerId(server.id as usize),
 766                            LanguageServerStatus {
 767                                name: server.name,
 768                                pending_work: Default::default(),
 769                                has_pending_diagnostic_updates: false,
 770                                progress_tokens: Default::default(),
 771                            },
 772                        )
 773                    })
 774                    .collect(),
 775                last_workspace_edits_by_language_server: Default::default(),
 776                opened_buffers: Default::default(),
 777                buffers_being_formatted: Default::default(),
 778                buffers_needing_diff: Default::default(),
 779                git_diff_debouncer: DelayedDebounced::new(),
 780                buffer_snapshots: Default::default(),
 781                nonce: StdRng::from_entropy().gen(),
 782                terminals: Terminals {
 783                    local_handles: Vec::new(),
 784                },
 785                copilot_lsp_subscription,
 786                copilot_log_subscription: None,
 787                current_lsp_settings: settings::get::<ProjectSettings>(cx).lsp.clone(),
 788                node: None,
 789                default_prettier: None,
 790                prettiers_per_worktree: HashMap::default(),
 791                prettier_instances: HashMap::default(),
 792            };
 793            for worktree in worktrees {
 794                let _ = this.add_worktree(&worktree, cx);
 795            }
 796            this
 797        });
 798        let subscription = subscription.set_model(&this, &mut cx);
 799
 800        let user_ids = response
 801            .payload
 802            .collaborators
 803            .iter()
 804            .map(|peer| peer.user_id)
 805            .collect();
 806        user_store
 807            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
 808            .await?;
 809
 810        this.update(&mut cx, |this, cx| {
 811            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
 812            this.client_subscriptions.push(subscription);
 813            anyhow::Ok(())
 814        })?;
 815
 816        Ok(this)
 817    }
 818
 819    #[cfg(any(test, feature = "test-support"))]
 820    pub async fn test(
 821        fs: Arc<dyn Fs>,
 822        root_paths: impl IntoIterator<Item = &Path>,
 823        cx: &mut gpui::TestAppContext,
 824    ) -> ModelHandle<Project> {
 825        let mut languages = LanguageRegistry::test();
 826        languages.set_executor(cx.background());
 827        let http_client = util::http::FakeHttpClient::with_404_response();
 828        let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
 829        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 830        let project = cx.update(|cx| {
 831            Project::local(
 832                client,
 833                node_runtime::FakeNodeRuntime::new(),
 834                user_store,
 835                Arc::new(languages),
 836                fs,
 837                cx,
 838            )
 839        });
 840        for path in root_paths {
 841            let (tree, _) = project
 842                .update(cx, |project, cx| {
 843                    project.find_or_create_local_worktree(path, true, cx)
 844                })
 845                .await
 846                .unwrap();
 847            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 848                .await;
 849        }
 850        project
 851    }
 852
 853    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 854        let mut language_servers_to_start = Vec::new();
 855        let mut language_formatters_to_check = Vec::new();
 856        for buffer in self.opened_buffers.values() {
 857            if let Some(buffer) = buffer.upgrade(cx) {
 858                let buffer = buffer.read(cx);
 859                let buffer_file = File::from_dyn(buffer.file());
 860                let buffer_language = buffer.language();
 861                let settings = language_settings(buffer_language, buffer.file(), cx);
 862                if let Some(language) = buffer_language {
 863                    if settings.enable_language_server {
 864                        if let Some(file) = buffer_file {
 865                            language_servers_to_start
 866                                .push((file.worktree.clone(), Arc::clone(language)));
 867                        }
 868                    }
 869                    language_formatters_to_check.push((
 870                        buffer_file.map(|f| f.worktree_id(cx)),
 871                        Arc::clone(language),
 872                        settings.clone(),
 873                    ));
 874                }
 875            }
 876        }
 877
 878        let mut language_servers_to_stop = Vec::new();
 879        let mut language_servers_to_restart = Vec::new();
 880        let languages = self.languages.to_vec();
 881
 882        let new_lsp_settings = settings::get::<ProjectSettings>(cx).lsp.clone();
 883        let current_lsp_settings = &self.current_lsp_settings;
 884        for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 885            let language = languages.iter().find_map(|l| {
 886                let adapter = l
 887                    .lsp_adapters()
 888                    .iter()
 889                    .find(|adapter| &adapter.name == started_lsp_name)?;
 890                Some((l, adapter))
 891            });
 892            if let Some((language, adapter)) = language {
 893                let worktree = self.worktree_for_id(*worktree_id, cx);
 894                let file = worktree.as_ref().and_then(|tree| {
 895                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
 896                });
 897                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
 898                    language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 899                } else if let Some(worktree) = worktree {
 900                    let server_name = &adapter.name.0;
 901                    match (
 902                        current_lsp_settings.get(server_name),
 903                        new_lsp_settings.get(server_name),
 904                    ) {
 905                        (None, None) => {}
 906                        (Some(_), None) | (None, Some(_)) => {
 907                            language_servers_to_restart.push((worktree, Arc::clone(language)));
 908                        }
 909                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
 910                            if current_lsp_settings != new_lsp_settings {
 911                                language_servers_to_restart.push((worktree, Arc::clone(language)));
 912                            }
 913                        }
 914                    }
 915                }
 916            }
 917        }
 918        self.current_lsp_settings = new_lsp_settings;
 919
 920        // Stop all newly-disabled language servers.
 921        for (worktree_id, adapter_name) in language_servers_to_stop {
 922            self.stop_language_server(worktree_id, adapter_name, cx)
 923                .detach();
 924        }
 925
 926        for (worktree, language, settings) in language_formatters_to_check {
 927            self.install_default_formatters(worktree, &language, &settings, cx)
 928                .detach_and_log_err(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                cx.spawn(move |this, mut cx| async move {
1713                    let load_result = load_buffer.await;
1714                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1715                        // Record the fact that the buffer is no longer loading.
1716                        this.loading_buffers_by_path.remove(&project_path);
1717                        let buffer = load_result.map_err(Arc::new)?;
1718                        Ok(buffer)
1719                    }));
1720                })
1721                .detach();
1722                rx
1723            }
1724        };
1725
1726        cx.foreground().spawn(async move {
1727            wait_for_loading_buffer(loading_watch)
1728                .await
1729                .map_err(|error| anyhow!("{}", error))
1730        })
1731    }
1732
1733    fn open_local_buffer_internal(
1734        &mut self,
1735        path: &Arc<Path>,
1736        worktree: &ModelHandle<Worktree>,
1737        cx: &mut ModelContext<Self>,
1738    ) -> Task<Result<ModelHandle<Buffer>>> {
1739        let buffer_id = post_inc(&mut self.next_buffer_id);
1740        let load_buffer = worktree.update(cx, |worktree, cx| {
1741            let worktree = worktree.as_local_mut().unwrap();
1742            worktree.load_buffer(buffer_id, path, cx)
1743        });
1744        cx.spawn(|this, mut cx| async move {
1745            let buffer = load_buffer.await?;
1746            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1747            Ok(buffer)
1748        })
1749    }
1750
1751    fn open_remote_buffer_internal(
1752        &mut self,
1753        path: &Arc<Path>,
1754        worktree: &ModelHandle<Worktree>,
1755        cx: &mut ModelContext<Self>,
1756    ) -> Task<Result<ModelHandle<Buffer>>> {
1757        let rpc = self.client.clone();
1758        let project_id = self.remote_id().unwrap();
1759        let remote_worktree_id = worktree.read(cx).id();
1760        let path = path.clone();
1761        let path_string = path.to_string_lossy().to_string();
1762        cx.spawn(|this, mut cx| async move {
1763            let response = rpc
1764                .request(proto::OpenBufferByPath {
1765                    project_id,
1766                    worktree_id: remote_worktree_id.to_proto(),
1767                    path: path_string,
1768                })
1769                .await?;
1770            this.update(&mut cx, |this, cx| {
1771                this.wait_for_remote_buffer(response.buffer_id, cx)
1772            })
1773            .await
1774        })
1775    }
1776
1777    /// LanguageServerName is owned, because it is inserted into a map
1778    pub fn open_local_buffer_via_lsp(
1779        &mut self,
1780        abs_path: lsp::Url,
1781        language_server_id: LanguageServerId,
1782        language_server_name: LanguageServerName,
1783        cx: &mut ModelContext<Self>,
1784    ) -> Task<Result<ModelHandle<Buffer>>> {
1785        cx.spawn(|this, mut cx| async move {
1786            let abs_path = abs_path
1787                .to_file_path()
1788                .map_err(|_| anyhow!("can't convert URI to path"))?;
1789            let (worktree, relative_path) = if let Some(result) =
1790                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1791            {
1792                result
1793            } else {
1794                let worktree = this
1795                    .update(&mut cx, |this, cx| {
1796                        this.create_local_worktree(&abs_path, false, cx)
1797                    })
1798                    .await?;
1799                this.update(&mut cx, |this, cx| {
1800                    this.language_server_ids.insert(
1801                        (worktree.read(cx).id(), language_server_name),
1802                        language_server_id,
1803                    );
1804                });
1805                (worktree, PathBuf::new())
1806            };
1807
1808            let project_path = ProjectPath {
1809                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1810                path: relative_path.into(),
1811            };
1812            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1813                .await
1814        })
1815    }
1816
1817    pub fn open_buffer_by_id(
1818        &mut self,
1819        id: u64,
1820        cx: &mut ModelContext<Self>,
1821    ) -> Task<Result<ModelHandle<Buffer>>> {
1822        if let Some(buffer) = self.buffer_for_id(id, cx) {
1823            Task::ready(Ok(buffer))
1824        } else if self.is_local() {
1825            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1826        } else if let Some(project_id) = self.remote_id() {
1827            let request = self
1828                .client
1829                .request(proto::OpenBufferById { project_id, id });
1830            cx.spawn(|this, mut cx| async move {
1831                let buffer_id = request.await?.buffer_id;
1832                this.update(&mut cx, |this, cx| {
1833                    this.wait_for_remote_buffer(buffer_id, cx)
1834                })
1835                .await
1836            })
1837        } else {
1838            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1839        }
1840    }
1841
1842    pub fn save_buffers(
1843        &self,
1844        buffers: HashSet<ModelHandle<Buffer>>,
1845        cx: &mut ModelContext<Self>,
1846    ) -> Task<Result<()>> {
1847        cx.spawn(|this, mut cx| async move {
1848            let save_tasks = buffers
1849                .into_iter()
1850                .map(|buffer| this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx)));
1851            try_join_all(save_tasks).await?;
1852            Ok(())
1853        })
1854    }
1855
1856    pub fn save_buffer(
1857        &self,
1858        buffer: ModelHandle<Buffer>,
1859        cx: &mut ModelContext<Self>,
1860    ) -> Task<Result<()>> {
1861        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1862            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1863        };
1864        let worktree = file.worktree.clone();
1865        let path = file.path.clone();
1866        worktree.update(cx, |worktree, cx| match worktree {
1867            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1868            Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1869        })
1870    }
1871
1872    pub fn save_buffer_as(
1873        &mut self,
1874        buffer: ModelHandle<Buffer>,
1875        abs_path: PathBuf,
1876        cx: &mut ModelContext<Self>,
1877    ) -> Task<Result<()>> {
1878        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1879        let old_file = File::from_dyn(buffer.read(cx).file())
1880            .filter(|f| f.is_local())
1881            .cloned();
1882        cx.spawn(|this, mut cx| async move {
1883            if let Some(old_file) = &old_file {
1884                this.update(&mut cx, |this, cx| {
1885                    this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
1886                });
1887            }
1888            let (worktree, path) = worktree_task.await?;
1889            worktree
1890                .update(&mut cx, |worktree, cx| match worktree {
1891                    Worktree::Local(worktree) => {
1892                        worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1893                    }
1894                    Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1895                })
1896                .await?;
1897
1898            this.update(&mut cx, |this, cx| {
1899                this.detect_language_for_buffer(&buffer, cx);
1900                this.register_buffer_with_language_servers(&buffer, cx);
1901            });
1902            Ok(())
1903        })
1904    }
1905
1906    pub fn get_open_buffer(
1907        &mut self,
1908        path: &ProjectPath,
1909        cx: &mut ModelContext<Self>,
1910    ) -> Option<ModelHandle<Buffer>> {
1911        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1912        self.opened_buffers.values().find_map(|buffer| {
1913            let buffer = buffer.upgrade(cx)?;
1914            let file = File::from_dyn(buffer.read(cx).file())?;
1915            if file.worktree == worktree && file.path() == &path.path {
1916                Some(buffer)
1917            } else {
1918                None
1919            }
1920        })
1921    }
1922
1923    fn register_buffer(
1924        &mut self,
1925        buffer: &ModelHandle<Buffer>,
1926        cx: &mut ModelContext<Self>,
1927    ) -> Result<()> {
1928        self.request_buffer_diff_recalculation(buffer, cx);
1929        buffer.update(cx, |buffer, _| {
1930            buffer.set_language_registry(self.languages.clone())
1931        });
1932
1933        let remote_id = buffer.read(cx).remote_id();
1934        let is_remote = self.is_remote();
1935        let open_buffer = if is_remote || self.is_shared() {
1936            OpenBuffer::Strong(buffer.clone())
1937        } else {
1938            OpenBuffer::Weak(buffer.downgrade())
1939        };
1940
1941        match self.opened_buffers.entry(remote_id) {
1942            hash_map::Entry::Vacant(entry) => {
1943                entry.insert(open_buffer);
1944            }
1945            hash_map::Entry::Occupied(mut entry) => {
1946                if let OpenBuffer::Operations(operations) = entry.get_mut() {
1947                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
1948                } else if entry.get().upgrade(cx).is_some() {
1949                    if is_remote {
1950                        return Ok(());
1951                    } else {
1952                        debug_panic!("buffer {} was already registered", remote_id);
1953                        Err(anyhow!("buffer {} was already registered", remote_id))?;
1954                    }
1955                }
1956                entry.insert(open_buffer);
1957            }
1958        }
1959        cx.subscribe(buffer, |this, buffer, event, cx| {
1960            this.on_buffer_event(buffer, event, cx);
1961        })
1962        .detach();
1963
1964        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1965            if file.is_local {
1966                self.local_buffer_ids_by_path.insert(
1967                    ProjectPath {
1968                        worktree_id: file.worktree_id(cx),
1969                        path: file.path.clone(),
1970                    },
1971                    remote_id,
1972                );
1973
1974                self.local_buffer_ids_by_entry_id
1975                    .insert(file.entry_id, remote_id);
1976            }
1977        }
1978
1979        self.detect_language_for_buffer(buffer, cx);
1980        self.register_buffer_with_language_servers(buffer, cx);
1981        self.register_buffer_with_copilot(buffer, cx);
1982        cx.observe_release(buffer, |this, buffer, cx| {
1983            if let Some(file) = File::from_dyn(buffer.file()) {
1984                if file.is_local() {
1985                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1986                    for server in this.language_servers_for_buffer(buffer, cx) {
1987                        server
1988                            .1
1989                            .notify::<lsp::notification::DidCloseTextDocument>(
1990                                lsp::DidCloseTextDocumentParams {
1991                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1992                                },
1993                            )
1994                            .log_err();
1995                    }
1996                }
1997            }
1998        })
1999        .detach();
2000
2001        *self.opened_buffer.0.borrow_mut() = ();
2002        Ok(())
2003    }
2004
2005    fn register_buffer_with_language_servers(
2006        &mut self,
2007        buffer_handle: &ModelHandle<Buffer>,
2008        cx: &mut ModelContext<Self>,
2009    ) {
2010        let buffer = buffer_handle.read(cx);
2011        let buffer_id = buffer.remote_id();
2012
2013        if let Some(file) = File::from_dyn(buffer.file()) {
2014            if !file.is_local() {
2015                return;
2016            }
2017
2018            let abs_path = file.abs_path(cx);
2019            let uri = lsp::Url::from_file_path(&abs_path)
2020                .unwrap_or_else(|()| panic!("Failed to register file {abs_path:?}"));
2021            let initial_snapshot = buffer.text_snapshot();
2022            let language = buffer.language().cloned();
2023            let worktree_id = file.worktree_id(cx);
2024
2025            if let Some(local_worktree) = file.worktree.read(cx).as_local() {
2026                for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
2027                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
2028                        .log_err();
2029                }
2030            }
2031
2032            if let Some(language) = language {
2033                for adapter in language.lsp_adapters() {
2034                    let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
2035                    let server = self
2036                        .language_server_ids
2037                        .get(&(worktree_id, adapter.name.clone()))
2038                        .and_then(|id| self.language_servers.get(id))
2039                        .and_then(|server_state| {
2040                            if let LanguageServerState::Running { server, .. } = server_state {
2041                                Some(server.clone())
2042                            } else {
2043                                None
2044                            }
2045                        });
2046                    let server = match server {
2047                        Some(server) => server,
2048                        None => continue,
2049                    };
2050
2051                    server
2052                        .notify::<lsp::notification::DidOpenTextDocument>(
2053                            lsp::DidOpenTextDocumentParams {
2054                                text_document: lsp::TextDocumentItem::new(
2055                                    uri.clone(),
2056                                    language_id.unwrap_or_default(),
2057                                    0,
2058                                    initial_snapshot.text(),
2059                                ),
2060                            },
2061                        )
2062                        .log_err();
2063
2064                    buffer_handle.update(cx, |buffer, cx| {
2065                        buffer.set_completion_triggers(
2066                            server
2067                                .capabilities()
2068                                .completion_provider
2069                                .as_ref()
2070                                .and_then(|provider| provider.trigger_characters.clone())
2071                                .unwrap_or_default(),
2072                            cx,
2073                        );
2074                    });
2075
2076                    let snapshot = LspBufferSnapshot {
2077                        version: 0,
2078                        snapshot: initial_snapshot.clone(),
2079                    };
2080                    self.buffer_snapshots
2081                        .entry(buffer_id)
2082                        .or_default()
2083                        .insert(server.server_id(), vec![snapshot]);
2084                }
2085            }
2086        }
2087    }
2088
2089    fn unregister_buffer_from_language_servers(
2090        &mut self,
2091        buffer: &ModelHandle<Buffer>,
2092        old_file: &File,
2093        cx: &mut ModelContext<Self>,
2094    ) {
2095        let old_path = match old_file.as_local() {
2096            Some(local) => local.abs_path(cx),
2097            None => return,
2098        };
2099
2100        buffer.update(cx, |buffer, cx| {
2101            let worktree_id = old_file.worktree_id(cx);
2102            let ids = &self.language_server_ids;
2103
2104            let language = buffer.language().cloned();
2105            let adapters = language.iter().flat_map(|language| language.lsp_adapters());
2106            for &server_id in adapters.flat_map(|a| ids.get(&(worktree_id, a.name.clone()))) {
2107                buffer.update_diagnostics(server_id, Default::default(), cx);
2108            }
2109
2110            self.buffer_snapshots.remove(&buffer.remote_id());
2111            let file_url = lsp::Url::from_file_path(old_path).unwrap();
2112            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2113                language_server
2114                    .notify::<lsp::notification::DidCloseTextDocument>(
2115                        lsp::DidCloseTextDocumentParams {
2116                            text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
2117                        },
2118                    )
2119                    .log_err();
2120            }
2121        });
2122    }
2123
2124    fn register_buffer_with_copilot(
2125        &self,
2126        buffer_handle: &ModelHandle<Buffer>,
2127        cx: &mut ModelContext<Self>,
2128    ) {
2129        if let Some(copilot) = Copilot::global(cx) {
2130            copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
2131        }
2132    }
2133
2134    async fn send_buffer_ordered_messages(
2135        this: WeakModelHandle<Self>,
2136        rx: UnboundedReceiver<BufferOrderedMessage>,
2137        mut cx: AsyncAppContext,
2138    ) -> Option<()> {
2139        const MAX_BATCH_SIZE: usize = 128;
2140
2141        let mut operations_by_buffer_id = HashMap::default();
2142        async fn flush_operations(
2143            this: &ModelHandle<Project>,
2144            operations_by_buffer_id: &mut HashMap<u64, Vec<proto::Operation>>,
2145            needs_resync_with_host: &mut bool,
2146            is_local: bool,
2147            cx: &AsyncAppContext,
2148        ) {
2149            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2150                let request = this.read_with(cx, |this, _| {
2151                    let project_id = this.remote_id()?;
2152                    Some(this.client.request(proto::UpdateBuffer {
2153                        buffer_id,
2154                        project_id,
2155                        operations,
2156                    }))
2157                });
2158                if let Some(request) = request {
2159                    if request.await.is_err() && !is_local {
2160                        *needs_resync_with_host = true;
2161                        break;
2162                    }
2163                }
2164            }
2165        }
2166
2167        let mut needs_resync_with_host = false;
2168        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2169
2170        while let Some(changes) = changes.next().await {
2171            let this = this.upgrade(&mut cx)?;
2172            let is_local = this.read_with(&cx, |this, _| this.is_local());
2173
2174            for change in changes {
2175                match change {
2176                    BufferOrderedMessage::Operation {
2177                        buffer_id,
2178                        operation,
2179                    } => {
2180                        if needs_resync_with_host {
2181                            continue;
2182                        }
2183
2184                        operations_by_buffer_id
2185                            .entry(buffer_id)
2186                            .or_insert(Vec::new())
2187                            .push(operation);
2188                    }
2189
2190                    BufferOrderedMessage::Resync => {
2191                        operations_by_buffer_id.clear();
2192                        if this
2193                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))
2194                            .await
2195                            .is_ok()
2196                        {
2197                            needs_resync_with_host = false;
2198                        }
2199                    }
2200
2201                    BufferOrderedMessage::LanguageServerUpdate {
2202                        language_server_id,
2203                        message,
2204                    } => {
2205                        flush_operations(
2206                            &this,
2207                            &mut operations_by_buffer_id,
2208                            &mut needs_resync_with_host,
2209                            is_local,
2210                            &cx,
2211                        )
2212                        .await;
2213
2214                        this.read_with(&cx, |this, _| {
2215                            if let Some(project_id) = this.remote_id() {
2216                                this.client
2217                                    .send(proto::UpdateLanguageServer {
2218                                        project_id,
2219                                        language_server_id: language_server_id.0 as u64,
2220                                        variant: Some(message),
2221                                    })
2222                                    .log_err();
2223                            }
2224                        });
2225                    }
2226                }
2227            }
2228
2229            flush_operations(
2230                &this,
2231                &mut operations_by_buffer_id,
2232                &mut needs_resync_with_host,
2233                is_local,
2234                &cx,
2235            )
2236            .await;
2237        }
2238
2239        None
2240    }
2241
2242    fn on_buffer_event(
2243        &mut self,
2244        buffer: ModelHandle<Buffer>,
2245        event: &BufferEvent,
2246        cx: &mut ModelContext<Self>,
2247    ) -> Option<()> {
2248        if matches!(
2249            event,
2250            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2251        ) {
2252            self.request_buffer_diff_recalculation(&buffer, cx);
2253        }
2254
2255        match event {
2256            BufferEvent::Operation(operation) => {
2257                self.buffer_ordered_messages_tx
2258                    .unbounded_send(BufferOrderedMessage::Operation {
2259                        buffer_id: buffer.read(cx).remote_id(),
2260                        operation: language::proto::serialize_operation(operation),
2261                    })
2262                    .ok();
2263            }
2264
2265            BufferEvent::Edited { .. } => {
2266                let buffer = buffer.read(cx);
2267                let file = File::from_dyn(buffer.file())?;
2268                let abs_path = file.as_local()?.abs_path(cx);
2269                let uri = lsp::Url::from_file_path(abs_path).unwrap();
2270                let next_snapshot = buffer.text_snapshot();
2271
2272                let language_servers: Vec<_> = self
2273                    .language_servers_for_buffer(buffer, cx)
2274                    .map(|i| i.1.clone())
2275                    .collect();
2276
2277                for language_server in language_servers {
2278                    let language_server = language_server.clone();
2279
2280                    let buffer_snapshots = self
2281                        .buffer_snapshots
2282                        .get_mut(&buffer.remote_id())
2283                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
2284                    let previous_snapshot = buffer_snapshots.last()?;
2285
2286                    let build_incremental_change = || {
2287                        buffer
2288                            .edits_since::<(PointUtf16, usize)>(
2289                                previous_snapshot.snapshot.version(),
2290                            )
2291                            .map(|edit| {
2292                                let edit_start = edit.new.start.0;
2293                                let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
2294                                let new_text = next_snapshot
2295                                    .text_for_range(edit.new.start.1..edit.new.end.1)
2296                                    .collect();
2297                                lsp::TextDocumentContentChangeEvent {
2298                                    range: Some(lsp::Range::new(
2299                                        point_to_lsp(edit_start),
2300                                        point_to_lsp(edit_end),
2301                                    )),
2302                                    range_length: None,
2303                                    text: new_text,
2304                                }
2305                            })
2306                            .collect()
2307                    };
2308
2309                    let document_sync_kind = language_server
2310                        .capabilities()
2311                        .text_document_sync
2312                        .as_ref()
2313                        .and_then(|sync| match sync {
2314                            lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
2315                            lsp::TextDocumentSyncCapability::Options(options) => options.change,
2316                        });
2317
2318                    let content_changes: Vec<_> = match document_sync_kind {
2319                        Some(lsp::TextDocumentSyncKind::FULL) => {
2320                            vec![lsp::TextDocumentContentChangeEvent {
2321                                range: None,
2322                                range_length: None,
2323                                text: next_snapshot.text(),
2324                            }]
2325                        }
2326                        Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
2327                        _ => {
2328                            #[cfg(any(test, feature = "test-support"))]
2329                            {
2330                                build_incremental_change()
2331                            }
2332
2333                            #[cfg(not(any(test, feature = "test-support")))]
2334                            {
2335                                continue;
2336                            }
2337                        }
2338                    };
2339
2340                    let next_version = previous_snapshot.version + 1;
2341
2342                    buffer_snapshots.push(LspBufferSnapshot {
2343                        version: next_version,
2344                        snapshot: next_snapshot.clone(),
2345                    });
2346
2347                    language_server
2348                        .notify::<lsp::notification::DidChangeTextDocument>(
2349                            lsp::DidChangeTextDocumentParams {
2350                                text_document: lsp::VersionedTextDocumentIdentifier::new(
2351                                    uri.clone(),
2352                                    next_version,
2353                                ),
2354                                content_changes,
2355                            },
2356                        )
2357                        .log_err();
2358                }
2359            }
2360
2361            BufferEvent::Saved => {
2362                let file = File::from_dyn(buffer.read(cx).file())?;
2363                let worktree_id = file.worktree_id(cx);
2364                let abs_path = file.as_local()?.abs_path(cx);
2365                let text_document = lsp::TextDocumentIdentifier {
2366                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
2367                };
2368
2369                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
2370                    let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
2371
2372                    server
2373                        .notify::<lsp::notification::DidSaveTextDocument>(
2374                            lsp::DidSaveTextDocumentParams {
2375                                text_document: text_document.clone(),
2376                                text,
2377                            },
2378                        )
2379                        .log_err();
2380                }
2381
2382                let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
2383                for language_server_id in language_server_ids {
2384                    if let Some(LanguageServerState::Running {
2385                        adapter,
2386                        simulate_disk_based_diagnostics_completion,
2387                        ..
2388                    }) = self.language_servers.get_mut(&language_server_id)
2389                    {
2390                        // After saving a buffer using a language server that doesn't provide
2391                        // a disk-based progress token, kick off a timer that will reset every
2392                        // time the buffer is saved. If the timer eventually fires, simulate
2393                        // disk-based diagnostics being finished so that other pieces of UI
2394                        // (e.g., project diagnostics view, diagnostic status bar) can update.
2395                        // We don't emit an event right away because the language server might take
2396                        // some time to publish diagnostics.
2397                        if adapter.disk_based_diagnostics_progress_token.is_none() {
2398                            const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
2399                                Duration::from_secs(1);
2400
2401                            let task = cx.spawn_weak(|this, mut cx| async move {
2402                                cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
2403                                if let Some(this) = this.upgrade(&cx) {
2404                                    this.update(&mut cx, |this, cx| {
2405                                        this.disk_based_diagnostics_finished(
2406                                            language_server_id,
2407                                            cx,
2408                                        );
2409                                        this.buffer_ordered_messages_tx
2410                                            .unbounded_send(
2411                                                BufferOrderedMessage::LanguageServerUpdate {
2412                                                    language_server_id,
2413                                                    message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
2414                                                },
2415                                            )
2416                                            .ok();
2417                                    });
2418                                }
2419                            });
2420                            *simulate_disk_based_diagnostics_completion = Some(task);
2421                        }
2422                    }
2423                }
2424            }
2425            BufferEvent::FileHandleChanged => {
2426                let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
2427                    return None;
2428                };
2429
2430                match self.local_buffer_ids_by_entry_id.get(&file.entry_id) {
2431                    Some(_) => {
2432                        return None;
2433                    }
2434                    None => {
2435                        let remote_id = buffer.read(cx).remote_id();
2436                        self.local_buffer_ids_by_entry_id
2437                            .insert(file.entry_id, remote_id);
2438
2439                        self.local_buffer_ids_by_path.insert(
2440                            ProjectPath {
2441                                worktree_id: file.worktree_id(cx),
2442                                path: file.path.clone(),
2443                            },
2444                            remote_id,
2445                        );
2446                    }
2447                }
2448            }
2449            _ => {}
2450        }
2451
2452        None
2453    }
2454
2455    fn request_buffer_diff_recalculation(
2456        &mut self,
2457        buffer: &ModelHandle<Buffer>,
2458        cx: &mut ModelContext<Self>,
2459    ) {
2460        self.buffers_needing_diff.insert(buffer.downgrade());
2461        let first_insertion = self.buffers_needing_diff.len() == 1;
2462
2463        let settings = settings::get::<ProjectSettings>(cx);
2464        let delay = if let Some(delay) = settings.git.gutter_debounce {
2465            delay
2466        } else {
2467            if first_insertion {
2468                let this = cx.weak_handle();
2469                cx.defer(move |cx| {
2470                    if let Some(this) = this.upgrade(cx) {
2471                        this.update(cx, |this, cx| {
2472                            this.recalculate_buffer_diffs(cx).detach();
2473                        });
2474                    }
2475                });
2476            }
2477            return;
2478        };
2479
2480        const MIN_DELAY: u64 = 50;
2481        let delay = delay.max(MIN_DELAY);
2482        let duration = Duration::from_millis(delay);
2483
2484        self.git_diff_debouncer
2485            .fire_new(duration, cx, move |this, cx| {
2486                this.recalculate_buffer_diffs(cx)
2487            });
2488    }
2489
2490    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2491        cx.spawn(|this, mut cx| async move {
2492            let buffers: Vec<_> = this.update(&mut cx, |this, _| {
2493                this.buffers_needing_diff.drain().collect()
2494            });
2495
2496            let tasks: Vec<_> = this.update(&mut cx, |_, cx| {
2497                buffers
2498                    .iter()
2499                    .filter_map(|buffer| {
2500                        let buffer = buffer.upgrade(cx)?;
2501                        buffer.update(cx, |buffer, cx| buffer.git_diff_recalc(cx))
2502                    })
2503                    .collect()
2504            });
2505
2506            futures::future::join_all(tasks).await;
2507
2508            this.update(&mut cx, |this, cx| {
2509                if !this.buffers_needing_diff.is_empty() {
2510                    this.recalculate_buffer_diffs(cx).detach();
2511                } else {
2512                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2513                    for buffer in buffers {
2514                        if let Some(buffer) = buffer.upgrade(cx) {
2515                            buffer.update(cx, |_, cx| cx.notify());
2516                        }
2517                    }
2518                }
2519            });
2520        })
2521    }
2522
2523    fn language_servers_for_worktree(
2524        &self,
2525        worktree_id: WorktreeId,
2526    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2527        self.language_server_ids
2528            .iter()
2529            .filter_map(move |((language_server_worktree_id, _), id)| {
2530                if *language_server_worktree_id == worktree_id {
2531                    if let Some(LanguageServerState::Running {
2532                        adapter,
2533                        language,
2534                        server,
2535                        ..
2536                    }) = self.language_servers.get(id)
2537                    {
2538                        return Some((adapter, language, server));
2539                    }
2540                }
2541                None
2542            })
2543    }
2544
2545    fn maintain_buffer_languages(
2546        languages: Arc<LanguageRegistry>,
2547        cx: &mut ModelContext<Project>,
2548    ) -> Task<()> {
2549        let mut subscription = languages.subscribe();
2550        let mut prev_reload_count = languages.reload_count();
2551        cx.spawn_weak(|project, mut cx| async move {
2552            while let Some(()) = subscription.next().await {
2553                if let Some(project) = project.upgrade(&cx) {
2554                    // If the language registry has been reloaded, then remove and
2555                    // re-assign the languages on all open buffers.
2556                    let reload_count = languages.reload_count();
2557                    if reload_count > prev_reload_count {
2558                        prev_reload_count = reload_count;
2559                        project.update(&mut cx, |this, cx| {
2560                            let buffers = this
2561                                .opened_buffers
2562                                .values()
2563                                .filter_map(|b| b.upgrade(cx))
2564                                .collect::<Vec<_>>();
2565                            for buffer in buffers {
2566                                if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned() {
2567                                    this.unregister_buffer_from_language_servers(&buffer, &f, cx);
2568                                    buffer.update(cx, |buffer, cx| buffer.set_language(None, cx));
2569                                }
2570                            }
2571                        });
2572                    }
2573
2574                    project.update(&mut cx, |project, cx| {
2575                        let mut plain_text_buffers = Vec::new();
2576                        let mut buffers_with_unknown_injections = Vec::new();
2577                        for buffer in project.opened_buffers.values() {
2578                            if let Some(handle) = buffer.upgrade(cx) {
2579                                let buffer = &handle.read(cx);
2580                                if buffer.language().is_none()
2581                                    || buffer.language() == Some(&*language::PLAIN_TEXT)
2582                                {
2583                                    plain_text_buffers.push(handle);
2584                                } else if buffer.contains_unknown_injections() {
2585                                    buffers_with_unknown_injections.push(handle);
2586                                }
2587                            }
2588                        }
2589
2590                        for buffer in plain_text_buffers {
2591                            project.detect_language_for_buffer(&buffer, cx);
2592                            project.register_buffer_with_language_servers(&buffer, cx);
2593                        }
2594
2595                        for buffer in buffers_with_unknown_injections {
2596                            buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2597                        }
2598                    });
2599                }
2600            }
2601        })
2602    }
2603
2604    fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<()> {
2605        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2606        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2607
2608        let settings_observation = cx.observe_global::<SettingsStore, _>(move |_, _| {
2609            *settings_changed_tx.borrow_mut() = ();
2610        });
2611
2612        cx.spawn_weak(|this, mut cx| async move {
2613            while let Some(_) = settings_changed_rx.next().await {
2614                let Some(this) = this.upgrade(&cx) else {
2615                    break;
2616                };
2617
2618                let servers: Vec<_> = this.read_with(&cx, |this, _| {
2619                    this.language_servers
2620                        .values()
2621                        .filter_map(|state| match state {
2622                            LanguageServerState::Starting(_) => None,
2623                            LanguageServerState::Running {
2624                                adapter, server, ..
2625                            } => Some((adapter.clone(), server.clone())),
2626                        })
2627                        .collect()
2628                });
2629
2630                for (adapter, server) in servers {
2631                    let workspace_config =
2632                        cx.update(|cx| adapter.workspace_configuration(cx)).await;
2633                    server
2634                        .notify::<lsp::notification::DidChangeConfiguration>(
2635                            lsp::DidChangeConfigurationParams {
2636                                settings: workspace_config.clone(),
2637                            },
2638                        )
2639                        .ok();
2640                }
2641            }
2642
2643            drop(settings_observation);
2644        })
2645    }
2646
2647    fn detect_language_for_buffer(
2648        &mut self,
2649        buffer_handle: &ModelHandle<Buffer>,
2650        cx: &mut ModelContext<Self>,
2651    ) -> Option<()> {
2652        // If the buffer has a language, set it and start the language server if we haven't already.
2653        let buffer = buffer_handle.read(cx);
2654        let full_path = buffer.file()?.full_path(cx);
2655        let content = buffer.as_rope();
2656        let new_language = self
2657            .languages
2658            .language_for_file(&full_path, Some(content))
2659            .now_or_never()?
2660            .ok()?;
2661        self.set_language_for_buffer(buffer_handle, new_language, cx);
2662        None
2663    }
2664
2665    pub fn set_language_for_buffer(
2666        &mut self,
2667        buffer: &ModelHandle<Buffer>,
2668        new_language: Arc<Language>,
2669        cx: &mut ModelContext<Self>,
2670    ) {
2671        buffer.update(cx, |buffer, cx| {
2672            if buffer.language().map_or(true, |old_language| {
2673                !Arc::ptr_eq(old_language, &new_language)
2674            }) {
2675                buffer.set_language(Some(new_language.clone()), cx);
2676            }
2677        });
2678
2679        let buffer_file = buffer.read(cx).file().cloned();
2680        let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
2681        let buffer_file = File::from_dyn(buffer_file.as_ref());
2682        let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
2683
2684        self.install_default_formatters(worktree, &new_language, &settings, cx)
2685            .detach_and_log_err(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_file = buffer.update(&mut cx, |buffer, _| buffer.file().cloned());
4162                                            let buffer_path= {
4163                                                File::from_dyn(buffer_file.as_ref()).map(|file| {
4164                                                    cx.update(|cx| {
4165                                                       let worktree_id = file.worktree_id(cx);
4166                                                       let file_abs_path = file.abs_path(cx);
4167                                                       project.update(cx, |project, _| project.prettiers_per_worktree.entry(worktree_id).or_default().insert(prettier_path));
4168                                                       file_abs_path
4169                                                    })
4170                                                })
4171                                            };
4172                                            format_operation = Some(FormatOperation::Prettier(
4173                                                prettier
4174                                                    .format(buffer, buffer_path, &cx)
4175                                                    .await
4176                                                    .context("formatting via prettier")?,
4177                                            ));
4178                                        }
4179                                        Err(e) => {
4180                                            project.update(&mut cx, |project, _| {
4181                                                match &prettier_path {
4182                                                    Some(prettier_path) => {
4183                                                        project.prettier_instances.remove(prettier_path);
4184                                                    },
4185                                                    None => {
4186                                                        if let Some(default_prettier) = project.default_prettier.as_mut() {
4187                                                            default_prettier.instance = None;
4188                                                        }
4189                                                    },
4190                                                }
4191                                            });
4192                                            anyhow::bail!(
4193                                                "Failed to create prettier instance from {prettier_path:?} for buffer during autoformatting: {e:#}"
4194                                            )},
4195                                    }
4196                            } else if let Some((language_server, buffer_abs_path)) =
4197                                language_server.as_ref().zip(buffer_abs_path.as_ref())
4198                            {
4199                                format_operation = Some(FormatOperation::Lsp(
4200                                    Self::format_via_lsp(
4201                                        &project,
4202                                        &buffer,
4203                                        buffer_abs_path,
4204                                        &language_server,
4205                                        tab_size,
4206                                        &mut cx,
4207                                    )
4208                                    .await
4209                                    .context("failed to format via language server")?,
4210                                ));
4211                            }
4212                        }
4213                        (Formatter::Prettier { .. }, FormatOnSave::On | FormatOnSave::Off) => {
4214                            if let Some((prettier_path, prettier_task)) = project
4215                                .update(&mut cx, |project, cx| {
4216                                    project.prettier_instance_for_buffer(buffer, cx)
4217                                }).await {
4218                                    match prettier_task.await
4219                                    {
4220                                        Ok(prettier) => {
4221                                            let buffer_file = buffer.update(&mut cx, |buffer, _| buffer.file().cloned());
4222                                            let buffer_path= {
4223                                                File::from_dyn(buffer_file.as_ref()).map(|file| {
4224                                                    cx.update(|cx| {
4225                                                       let worktree_id = file.worktree_id(cx);
4226                                                       let file_abs_path = file.abs_path(cx);
4227                                                       project.update(cx, |project, _| project.prettiers_per_worktree.entry(worktree_id).or_default().insert(prettier_path));
4228                                                       file_abs_path
4229                                                    })
4230                                                })
4231                                            };
4232                                            format_operation = Some(FormatOperation::Prettier(
4233                                                prettier
4234                                                    .format(buffer, buffer_path, &cx)
4235                                                    .await
4236                                                    .context("formatting via prettier")?,
4237                                            ));
4238                                        }
4239                                        Err(e) => {
4240                                            project.update(&mut cx, |project, _| {
4241                                                match &prettier_path {
4242                                                    Some(prettier_path) => {
4243                                                        project.prettier_instances.remove(prettier_path);
4244                                                    },
4245                                                    None => {
4246                                                        if let Some(default_prettier) = project.default_prettier.as_mut() {
4247                                                            default_prettier.instance = None;
4248                                                        }
4249                                                    },
4250                                                }
4251                                            });
4252                                            anyhow::bail!(
4253                                                "Failed to create prettier instance from {prettier_path:?} for buffer during formatting: {e:#}"
4254                                            )},
4255                                    }
4256                                }
4257                        }
4258                    };
4259
4260                    buffer.update(&mut cx, |b, cx| {
4261                        // If the buffer had its whitespace formatted and was edited while the language-specific
4262                        // formatting was being computed, avoid applying the language-specific formatting, because
4263                        // it can't be grouped with the whitespace formatting in the undo history.
4264                        if let Some(transaction_id) = whitespace_transaction_id {
4265                            if b.peek_undo_stack()
4266                                .map_or(true, |e| e.transaction_id() != transaction_id)
4267                            {
4268                                format_operation.take();
4269                            }
4270                        }
4271
4272                        // Apply any language-specific formatting, and group the two formatting operations
4273                        // in the buffer's undo history.
4274                        if let Some(operation) = format_operation {
4275                            match operation {
4276                                FormatOperation::Lsp(edits) => {
4277                                    b.edit(edits, None, cx);
4278                                }
4279                                FormatOperation::External(diff) => {
4280                                    b.apply_diff(diff, cx);
4281                                }
4282                                FormatOperation::Prettier(diff) => {
4283                                    b.apply_diff(diff, cx);
4284                                }
4285                            }
4286
4287                            if let Some(transaction_id) = whitespace_transaction_id {
4288                                b.group_until_transaction(transaction_id);
4289                            }
4290                        }
4291
4292                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
4293                            if !push_to_history {
4294                                b.forget_transaction(transaction.id);
4295                            }
4296                            project_transaction.0.insert(buffer.clone(), transaction);
4297                        }
4298                    });
4299                }
4300
4301                Ok(project_transaction)
4302            })
4303        } else {
4304            let remote_id = self.remote_id();
4305            let client = self.client.clone();
4306            cx.spawn(|this, mut cx| async move {
4307                let mut project_transaction = ProjectTransaction::default();
4308                if let Some(project_id) = remote_id {
4309                    let response = client
4310                        .request(proto::FormatBuffers {
4311                            project_id,
4312                            trigger: trigger as i32,
4313                            buffer_ids: buffers
4314                                .iter()
4315                                .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
4316                                .collect(),
4317                        })
4318                        .await?
4319                        .transaction
4320                        .ok_or_else(|| anyhow!("missing transaction"))?;
4321                    project_transaction = this
4322                        .update(&mut cx, |this, cx| {
4323                            this.deserialize_project_transaction(response, push_to_history, cx)
4324                        })
4325                        .await?;
4326                }
4327                Ok(project_transaction)
4328            })
4329        }
4330    }
4331
4332    async fn format_via_lsp(
4333        this: &ModelHandle<Self>,
4334        buffer: &ModelHandle<Buffer>,
4335        abs_path: &Path,
4336        language_server: &Arc<LanguageServer>,
4337        tab_size: NonZeroU32,
4338        cx: &mut AsyncAppContext,
4339    ) -> Result<Vec<(Range<Anchor>, String)>> {
4340        let uri = lsp::Url::from_file_path(abs_path)
4341            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4342        let text_document = lsp::TextDocumentIdentifier::new(uri);
4343        let capabilities = &language_server.capabilities();
4344
4345        let formatting_provider = capabilities.document_formatting_provider.as_ref();
4346        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4347
4348        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4349            language_server
4350                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4351                    text_document,
4352                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4353                    work_done_progress_params: Default::default(),
4354                })
4355                .await?
4356        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4357            let buffer_start = lsp::Position::new(0, 0);
4358            let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()));
4359
4360            language_server
4361                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4362                    text_document,
4363                    range: lsp::Range::new(buffer_start, buffer_end),
4364                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4365                    work_done_progress_params: Default::default(),
4366                })
4367                .await?
4368        } else {
4369            None
4370        };
4371
4372        if let Some(lsp_edits) = lsp_edits {
4373            this.update(cx, |this, cx| {
4374                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4375            })
4376            .await
4377        } else {
4378            Ok(Vec::new())
4379        }
4380    }
4381
4382    async fn format_via_external_command(
4383        buffer: &ModelHandle<Buffer>,
4384        buffer_abs_path: &Path,
4385        command: &str,
4386        arguments: &[String],
4387        cx: &mut AsyncAppContext,
4388    ) -> Result<Option<Diff>> {
4389        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
4390            let file = File::from_dyn(buffer.file())?;
4391            let worktree = file.worktree.read(cx).as_local()?;
4392            let mut worktree_path = worktree.abs_path().to_path_buf();
4393            if worktree.root_entry()?.is_file() {
4394                worktree_path.pop();
4395            }
4396            Some(worktree_path)
4397        });
4398
4399        if let Some(working_dir_path) = working_dir_path {
4400            let mut child =
4401                smol::process::Command::new(command)
4402                    .args(arguments.iter().map(|arg| {
4403                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4404                    }))
4405                    .current_dir(&working_dir_path)
4406                    .stdin(smol::process::Stdio::piped())
4407                    .stdout(smol::process::Stdio::piped())
4408                    .stderr(smol::process::Stdio::piped())
4409                    .spawn()?;
4410            let stdin = child
4411                .stdin
4412                .as_mut()
4413                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4414            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
4415            for chunk in text.chunks() {
4416                stdin.write_all(chunk.as_bytes()).await?;
4417            }
4418            stdin.flush().await?;
4419
4420            let output = child.output().await?;
4421            if !output.status.success() {
4422                return Err(anyhow!(
4423                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4424                    output.status.code(),
4425                    String::from_utf8_lossy(&output.stdout),
4426                    String::from_utf8_lossy(&output.stderr),
4427                ));
4428            }
4429
4430            let stdout = String::from_utf8(output.stdout)?;
4431            Ok(Some(
4432                buffer
4433                    .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
4434                    .await,
4435            ))
4436        } else {
4437            Ok(None)
4438        }
4439    }
4440
4441    pub fn definition<T: ToPointUtf16>(
4442        &self,
4443        buffer: &ModelHandle<Buffer>,
4444        position: T,
4445        cx: &mut ModelContext<Self>,
4446    ) -> Task<Result<Vec<LocationLink>>> {
4447        let position = position.to_point_utf16(buffer.read(cx));
4448        self.request_lsp(
4449            buffer.clone(),
4450            LanguageServerToQuery::Primary,
4451            GetDefinition { position },
4452            cx,
4453        )
4454    }
4455
4456    pub fn type_definition<T: ToPointUtf16>(
4457        &self,
4458        buffer: &ModelHandle<Buffer>,
4459        position: T,
4460        cx: &mut ModelContext<Self>,
4461    ) -> Task<Result<Vec<LocationLink>>> {
4462        let position = position.to_point_utf16(buffer.read(cx));
4463        self.request_lsp(
4464            buffer.clone(),
4465            LanguageServerToQuery::Primary,
4466            GetTypeDefinition { position },
4467            cx,
4468        )
4469    }
4470
4471    pub fn references<T: ToPointUtf16>(
4472        &self,
4473        buffer: &ModelHandle<Buffer>,
4474        position: T,
4475        cx: &mut ModelContext<Self>,
4476    ) -> Task<Result<Vec<Location>>> {
4477        let position = position.to_point_utf16(buffer.read(cx));
4478        self.request_lsp(
4479            buffer.clone(),
4480            LanguageServerToQuery::Primary,
4481            GetReferences { position },
4482            cx,
4483        )
4484    }
4485
4486    pub fn document_highlights<T: ToPointUtf16>(
4487        &self,
4488        buffer: &ModelHandle<Buffer>,
4489        position: T,
4490        cx: &mut ModelContext<Self>,
4491    ) -> Task<Result<Vec<DocumentHighlight>>> {
4492        let position = position.to_point_utf16(buffer.read(cx));
4493        self.request_lsp(
4494            buffer.clone(),
4495            LanguageServerToQuery::Primary,
4496            GetDocumentHighlights { position },
4497            cx,
4498        )
4499    }
4500
4501    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4502        if self.is_local() {
4503            let mut requests = Vec::new();
4504            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4505                let worktree_id = *worktree_id;
4506                let worktree_handle = self.worktree_for_id(worktree_id, cx);
4507                let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4508                    Some(worktree) => worktree,
4509                    None => continue,
4510                };
4511                let worktree_abs_path = worktree.abs_path().clone();
4512
4513                let (adapter, language, server) = match self.language_servers.get(server_id) {
4514                    Some(LanguageServerState::Running {
4515                        adapter,
4516                        language,
4517                        server,
4518                        ..
4519                    }) => (adapter.clone(), language.clone(), server),
4520
4521                    _ => continue,
4522                };
4523
4524                requests.push(
4525                    server
4526                        .request::<lsp::request::WorkspaceSymbolRequest>(
4527                            lsp::WorkspaceSymbolParams {
4528                                query: query.to_string(),
4529                                ..Default::default()
4530                            },
4531                        )
4532                        .log_err()
4533                        .map(move |response| {
4534                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4535                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4536                                    flat_responses.into_iter().map(|lsp_symbol| {
4537                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4538                                    }).collect::<Vec<_>>()
4539                                }
4540                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4541                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
4542                                        let location = match lsp_symbol.location {
4543                                            OneOf::Left(location) => location,
4544                                            OneOf::Right(_) => {
4545                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4546                                                return None
4547                                            }
4548                                        };
4549                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
4550                                    }).collect::<Vec<_>>()
4551                                }
4552                            }).unwrap_or_default();
4553
4554                            (
4555                                adapter,
4556                                language,
4557                                worktree_id,
4558                                worktree_abs_path,
4559                                lsp_symbols,
4560                            )
4561                        }),
4562                );
4563            }
4564
4565            cx.spawn_weak(|this, cx| async move {
4566                let responses = futures::future::join_all(requests).await;
4567                let this = match this.upgrade(&cx) {
4568                    Some(this) => this,
4569                    None => return Ok(Vec::new()),
4570                };
4571
4572                let symbols = this.read_with(&cx, |this, cx| {
4573                    let mut symbols = Vec::new();
4574                    for (
4575                        adapter,
4576                        adapter_language,
4577                        source_worktree_id,
4578                        worktree_abs_path,
4579                        lsp_symbols,
4580                    ) in responses
4581                    {
4582                        symbols.extend(lsp_symbols.into_iter().filter_map(
4583                            |(symbol_name, symbol_kind, symbol_location)| {
4584                                let abs_path = symbol_location.uri.to_file_path().ok()?;
4585                                let mut worktree_id = source_worktree_id;
4586                                let path;
4587                                if let Some((worktree, rel_path)) =
4588                                    this.find_local_worktree(&abs_path, cx)
4589                                {
4590                                    worktree_id = worktree.read(cx).id();
4591                                    path = rel_path;
4592                                } else {
4593                                    path = relativize_path(&worktree_abs_path, &abs_path);
4594                                }
4595
4596                                let project_path = ProjectPath {
4597                                    worktree_id,
4598                                    path: path.into(),
4599                                };
4600                                let signature = this.symbol_signature(&project_path);
4601                                let adapter_language = adapter_language.clone();
4602                                let language = this
4603                                    .languages
4604                                    .language_for_file(&project_path.path, None)
4605                                    .unwrap_or_else(move |_| adapter_language);
4606                                let language_server_name = adapter.name.clone();
4607                                Some(async move {
4608                                    let language = language.await;
4609                                    let label =
4610                                        language.label_for_symbol(&symbol_name, symbol_kind).await;
4611
4612                                    Symbol {
4613                                        language_server_name,
4614                                        source_worktree_id,
4615                                        path: project_path,
4616                                        label: label.unwrap_or_else(|| {
4617                                            CodeLabel::plain(symbol_name.clone(), None)
4618                                        }),
4619                                        kind: symbol_kind,
4620                                        name: symbol_name,
4621                                        range: range_from_lsp(symbol_location.range),
4622                                        signature,
4623                                    }
4624                                })
4625                            },
4626                        ));
4627                    }
4628
4629                    symbols
4630                });
4631
4632                Ok(futures::future::join_all(symbols).await)
4633            })
4634        } else if let Some(project_id) = self.remote_id() {
4635            let request = self.client.request(proto::GetProjectSymbols {
4636                project_id,
4637                query: query.to_string(),
4638            });
4639            cx.spawn_weak(|this, cx| async move {
4640                let response = request.await?;
4641                let mut symbols = Vec::new();
4642                if let Some(this) = this.upgrade(&cx) {
4643                    let new_symbols = this.read_with(&cx, |this, _| {
4644                        response
4645                            .symbols
4646                            .into_iter()
4647                            .map(|symbol| this.deserialize_symbol(symbol))
4648                            .collect::<Vec<_>>()
4649                    });
4650                    symbols = futures::future::join_all(new_symbols)
4651                        .await
4652                        .into_iter()
4653                        .filter_map(|symbol| symbol.log_err())
4654                        .collect::<Vec<_>>();
4655                }
4656                Ok(symbols)
4657            })
4658        } else {
4659            Task::ready(Ok(Default::default()))
4660        }
4661    }
4662
4663    pub fn open_buffer_for_symbol(
4664        &mut self,
4665        symbol: &Symbol,
4666        cx: &mut ModelContext<Self>,
4667    ) -> Task<Result<ModelHandle<Buffer>>> {
4668        if self.is_local() {
4669            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4670                symbol.source_worktree_id,
4671                symbol.language_server_name.clone(),
4672            )) {
4673                *id
4674            } else {
4675                return Task::ready(Err(anyhow!(
4676                    "language server for worktree and language not found"
4677                )));
4678            };
4679
4680            let worktree_abs_path = if let Some(worktree_abs_path) = self
4681                .worktree_for_id(symbol.path.worktree_id, cx)
4682                .and_then(|worktree| worktree.read(cx).as_local())
4683                .map(|local_worktree| local_worktree.abs_path())
4684            {
4685                worktree_abs_path
4686            } else {
4687                return Task::ready(Err(anyhow!("worktree not found for symbol")));
4688            };
4689            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
4690            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4691                uri
4692            } else {
4693                return Task::ready(Err(anyhow!("invalid symbol path")));
4694            };
4695
4696            self.open_local_buffer_via_lsp(
4697                symbol_uri,
4698                language_server_id,
4699                symbol.language_server_name.clone(),
4700                cx,
4701            )
4702        } else if let Some(project_id) = self.remote_id() {
4703            let request = self.client.request(proto::OpenBufferForSymbol {
4704                project_id,
4705                symbol: Some(serialize_symbol(symbol)),
4706            });
4707            cx.spawn(|this, mut cx| async move {
4708                let response = request.await?;
4709                this.update(&mut cx, |this, cx| {
4710                    this.wait_for_remote_buffer(response.buffer_id, cx)
4711                })
4712                .await
4713            })
4714        } else {
4715            Task::ready(Err(anyhow!("project does not have a remote id")))
4716        }
4717    }
4718
4719    pub fn hover<T: ToPointUtf16>(
4720        &self,
4721        buffer: &ModelHandle<Buffer>,
4722        position: T,
4723        cx: &mut ModelContext<Self>,
4724    ) -> Task<Result<Option<Hover>>> {
4725        let position = position.to_point_utf16(buffer.read(cx));
4726        self.request_lsp(
4727            buffer.clone(),
4728            LanguageServerToQuery::Primary,
4729            GetHover { position },
4730            cx,
4731        )
4732    }
4733
4734    pub fn completions<T: ToOffset + ToPointUtf16>(
4735        &self,
4736        buffer: &ModelHandle<Buffer>,
4737        position: T,
4738        cx: &mut ModelContext<Self>,
4739    ) -> Task<Result<Vec<Completion>>> {
4740        let position = position.to_point_utf16(buffer.read(cx));
4741        if self.is_local() {
4742            let snapshot = buffer.read(cx).snapshot();
4743            let offset = position.to_offset(&snapshot);
4744            let scope = snapshot.language_scope_at(offset);
4745
4746            let server_ids: Vec<_> = self
4747                .language_servers_for_buffer(buffer.read(cx), cx)
4748                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4749                .filter(|(adapter, _)| {
4750                    scope
4751                        .as_ref()
4752                        .map(|scope| scope.language_allowed(&adapter.name))
4753                        .unwrap_or(true)
4754                })
4755                .map(|(_, server)| server.server_id())
4756                .collect();
4757
4758            let buffer = buffer.clone();
4759            cx.spawn(|this, mut cx| async move {
4760                let mut tasks = Vec::with_capacity(server_ids.len());
4761                this.update(&mut cx, |this, cx| {
4762                    for server_id in server_ids {
4763                        tasks.push(this.request_lsp(
4764                            buffer.clone(),
4765                            LanguageServerToQuery::Other(server_id),
4766                            GetCompletions { position },
4767                            cx,
4768                        ));
4769                    }
4770                });
4771
4772                let mut completions = Vec::new();
4773                for task in tasks {
4774                    if let Ok(new_completions) = task.await {
4775                        completions.extend_from_slice(&new_completions);
4776                    }
4777                }
4778
4779                Ok(completions)
4780            })
4781        } else if let Some(project_id) = self.remote_id() {
4782            self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4783        } else {
4784            Task::ready(Ok(Default::default()))
4785        }
4786    }
4787
4788    pub fn apply_additional_edits_for_completion(
4789        &self,
4790        buffer_handle: ModelHandle<Buffer>,
4791        completion: Completion,
4792        push_to_history: bool,
4793        cx: &mut ModelContext<Self>,
4794    ) -> Task<Result<Option<Transaction>>> {
4795        let buffer = buffer_handle.read(cx);
4796        let buffer_id = buffer.remote_id();
4797
4798        if self.is_local() {
4799            let server_id = completion.server_id;
4800            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
4801                Some((_, server)) => server.clone(),
4802                _ => return Task::ready(Ok(Default::default())),
4803            };
4804
4805            cx.spawn(|this, mut cx| async move {
4806                let can_resolve = lang_server
4807                    .capabilities()
4808                    .completion_provider
4809                    .as_ref()
4810                    .and_then(|options| options.resolve_provider)
4811                    .unwrap_or(false);
4812                let additional_text_edits = if can_resolve {
4813                    lang_server
4814                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4815                        .await?
4816                        .additional_text_edits
4817                } else {
4818                    completion.lsp_completion.additional_text_edits
4819                };
4820                if let Some(edits) = additional_text_edits {
4821                    let edits = this
4822                        .update(&mut cx, |this, cx| {
4823                            this.edits_from_lsp(
4824                                &buffer_handle,
4825                                edits,
4826                                lang_server.server_id(),
4827                                None,
4828                                cx,
4829                            )
4830                        })
4831                        .await?;
4832
4833                    buffer_handle.update(&mut cx, |buffer, cx| {
4834                        buffer.finalize_last_transaction();
4835                        buffer.start_transaction();
4836
4837                        for (range, text) in edits {
4838                            let primary = &completion.old_range;
4839                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
4840                                && primary.end.cmp(&range.start, buffer).is_ge();
4841                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
4842                                && range.end.cmp(&primary.end, buffer).is_ge();
4843
4844                            //Skip additional edits which overlap with the primary completion edit
4845                            //https://github.com/zed-industries/zed/pull/1871
4846                            if !start_within && !end_within {
4847                                buffer.edit([(range, text)], None, cx);
4848                            }
4849                        }
4850
4851                        let transaction = if buffer.end_transaction(cx).is_some() {
4852                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4853                            if !push_to_history {
4854                                buffer.forget_transaction(transaction.id);
4855                            }
4856                            Some(transaction)
4857                        } else {
4858                            None
4859                        };
4860                        Ok(transaction)
4861                    })
4862                } else {
4863                    Ok(None)
4864                }
4865            })
4866        } else if let Some(project_id) = self.remote_id() {
4867            let client = self.client.clone();
4868            cx.spawn(|_, mut cx| async move {
4869                let response = client
4870                    .request(proto::ApplyCompletionAdditionalEdits {
4871                        project_id,
4872                        buffer_id,
4873                        completion: Some(language::proto::serialize_completion(&completion)),
4874                    })
4875                    .await?;
4876
4877                if let Some(transaction) = response.transaction {
4878                    let transaction = language::proto::deserialize_transaction(transaction)?;
4879                    buffer_handle
4880                        .update(&mut cx, |buffer, _| {
4881                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4882                        })
4883                        .await?;
4884                    if push_to_history {
4885                        buffer_handle.update(&mut cx, |buffer, _| {
4886                            buffer.push_transaction(transaction.clone(), Instant::now());
4887                        });
4888                    }
4889                    Ok(Some(transaction))
4890                } else {
4891                    Ok(None)
4892                }
4893            })
4894        } else {
4895            Task::ready(Err(anyhow!("project does not have a remote id")))
4896        }
4897    }
4898
4899    pub fn code_actions<T: Clone + ToOffset>(
4900        &self,
4901        buffer_handle: &ModelHandle<Buffer>,
4902        range: Range<T>,
4903        cx: &mut ModelContext<Self>,
4904    ) -> Task<Result<Vec<CodeAction>>> {
4905        let buffer = buffer_handle.read(cx);
4906        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4907        self.request_lsp(
4908            buffer_handle.clone(),
4909            LanguageServerToQuery::Primary,
4910            GetCodeActions { range },
4911            cx,
4912        )
4913    }
4914
4915    pub fn apply_code_action(
4916        &self,
4917        buffer_handle: ModelHandle<Buffer>,
4918        mut action: CodeAction,
4919        push_to_history: bool,
4920        cx: &mut ModelContext<Self>,
4921    ) -> Task<Result<ProjectTransaction>> {
4922        if self.is_local() {
4923            let buffer = buffer_handle.read(cx);
4924            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4925                self.language_server_for_buffer(buffer, action.server_id, cx)
4926            {
4927                (adapter.clone(), server.clone())
4928            } else {
4929                return Task::ready(Ok(Default::default()));
4930            };
4931            let range = action.range.to_point_utf16(buffer);
4932
4933            cx.spawn(|this, mut cx| async move {
4934                if let Some(lsp_range) = action
4935                    .lsp_action
4936                    .data
4937                    .as_mut()
4938                    .and_then(|d| d.get_mut("codeActionParams"))
4939                    .and_then(|d| d.get_mut("range"))
4940                {
4941                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4942                    action.lsp_action = lang_server
4943                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4944                        .await?;
4945                } else {
4946                    let actions = this
4947                        .update(&mut cx, |this, cx| {
4948                            this.code_actions(&buffer_handle, action.range, cx)
4949                        })
4950                        .await?;
4951                    action.lsp_action = actions
4952                        .into_iter()
4953                        .find(|a| a.lsp_action.title == action.lsp_action.title)
4954                        .ok_or_else(|| anyhow!("code action is outdated"))?
4955                        .lsp_action;
4956                }
4957
4958                if let Some(edit) = action.lsp_action.edit {
4959                    if edit.changes.is_some() || edit.document_changes.is_some() {
4960                        return Self::deserialize_workspace_edit(
4961                            this,
4962                            edit,
4963                            push_to_history,
4964                            lsp_adapter.clone(),
4965                            lang_server.clone(),
4966                            &mut cx,
4967                        )
4968                        .await;
4969                    }
4970                }
4971
4972                if let Some(command) = action.lsp_action.command {
4973                    this.update(&mut cx, |this, _| {
4974                        this.last_workspace_edits_by_language_server
4975                            .remove(&lang_server.server_id());
4976                    });
4977
4978                    let result = lang_server
4979                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4980                            command: command.command,
4981                            arguments: command.arguments.unwrap_or_default(),
4982                            ..Default::default()
4983                        })
4984                        .await;
4985
4986                    if let Err(err) = result {
4987                        // TODO: LSP ERROR
4988                        return Err(err);
4989                    }
4990
4991                    return Ok(this.update(&mut cx, |this, _| {
4992                        this.last_workspace_edits_by_language_server
4993                            .remove(&lang_server.server_id())
4994                            .unwrap_or_default()
4995                    }));
4996                }
4997
4998                Ok(ProjectTransaction::default())
4999            })
5000        } else if let Some(project_id) = self.remote_id() {
5001            let client = self.client.clone();
5002            let request = proto::ApplyCodeAction {
5003                project_id,
5004                buffer_id: buffer_handle.read(cx).remote_id(),
5005                action: Some(language::proto::serialize_code_action(&action)),
5006            };
5007            cx.spawn(|this, mut cx| async move {
5008                let response = client
5009                    .request(request)
5010                    .await?
5011                    .transaction
5012                    .ok_or_else(|| anyhow!("missing transaction"))?;
5013                this.update(&mut cx, |this, cx| {
5014                    this.deserialize_project_transaction(response, push_to_history, cx)
5015                })
5016                .await
5017            })
5018        } else {
5019            Task::ready(Err(anyhow!("project does not have a remote id")))
5020        }
5021    }
5022
5023    fn apply_on_type_formatting(
5024        &self,
5025        buffer: ModelHandle<Buffer>,
5026        position: Anchor,
5027        trigger: String,
5028        cx: &mut ModelContext<Self>,
5029    ) -> Task<Result<Option<Transaction>>> {
5030        if self.is_local() {
5031            cx.spawn(|this, mut cx| async move {
5032                // Do not allow multiple concurrent formatting requests for the
5033                // same buffer.
5034                this.update(&mut cx, |this, cx| {
5035                    this.buffers_being_formatted
5036                        .insert(buffer.read(cx).remote_id())
5037                });
5038
5039                let _cleanup = defer({
5040                    let this = this.clone();
5041                    let mut cx = cx.clone();
5042                    let closure_buffer = buffer.clone();
5043                    move || {
5044                        this.update(&mut cx, |this, cx| {
5045                            this.buffers_being_formatted
5046                                .remove(&closure_buffer.read(cx).remote_id());
5047                        });
5048                    }
5049                });
5050
5051                buffer
5052                    .update(&mut cx, |buffer, _| {
5053                        buffer.wait_for_edits(Some(position.timestamp))
5054                    })
5055                    .await?;
5056                this.update(&mut cx, |this, cx| {
5057                    let position = position.to_point_utf16(buffer.read(cx));
5058                    this.on_type_format(buffer, position, trigger, false, cx)
5059                })
5060                .await
5061            })
5062        } else if let Some(project_id) = self.remote_id() {
5063            let client = self.client.clone();
5064            let request = proto::OnTypeFormatting {
5065                project_id,
5066                buffer_id: buffer.read(cx).remote_id(),
5067                position: Some(serialize_anchor(&position)),
5068                trigger,
5069                version: serialize_version(&buffer.read(cx).version()),
5070            };
5071            cx.spawn(|_, _| async move {
5072                client
5073                    .request(request)
5074                    .await?
5075                    .transaction
5076                    .map(language::proto::deserialize_transaction)
5077                    .transpose()
5078            })
5079        } else {
5080            Task::ready(Err(anyhow!("project does not have a remote id")))
5081        }
5082    }
5083
5084    async fn deserialize_edits(
5085        this: ModelHandle<Self>,
5086        buffer_to_edit: ModelHandle<Buffer>,
5087        edits: Vec<lsp::TextEdit>,
5088        push_to_history: bool,
5089        _: Arc<CachedLspAdapter>,
5090        language_server: Arc<LanguageServer>,
5091        cx: &mut AsyncAppContext,
5092    ) -> Result<Option<Transaction>> {
5093        let edits = this
5094            .update(cx, |this, cx| {
5095                this.edits_from_lsp(
5096                    &buffer_to_edit,
5097                    edits,
5098                    language_server.server_id(),
5099                    None,
5100                    cx,
5101                )
5102            })
5103            .await?;
5104
5105        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5106            buffer.finalize_last_transaction();
5107            buffer.start_transaction();
5108            for (range, text) in edits {
5109                buffer.edit([(range, text)], None, cx);
5110            }
5111
5112            if buffer.end_transaction(cx).is_some() {
5113                let transaction = buffer.finalize_last_transaction().unwrap().clone();
5114                if !push_to_history {
5115                    buffer.forget_transaction(transaction.id);
5116                }
5117                Some(transaction)
5118            } else {
5119                None
5120            }
5121        });
5122
5123        Ok(transaction)
5124    }
5125
5126    async fn deserialize_workspace_edit(
5127        this: ModelHandle<Self>,
5128        edit: lsp::WorkspaceEdit,
5129        push_to_history: bool,
5130        lsp_adapter: Arc<CachedLspAdapter>,
5131        language_server: Arc<LanguageServer>,
5132        cx: &mut AsyncAppContext,
5133    ) -> Result<ProjectTransaction> {
5134        let fs = this.read_with(cx, |this, _| this.fs.clone());
5135        let mut operations = Vec::new();
5136        if let Some(document_changes) = edit.document_changes {
5137            match document_changes {
5138                lsp::DocumentChanges::Edits(edits) => {
5139                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5140                }
5141                lsp::DocumentChanges::Operations(ops) => operations = ops,
5142            }
5143        } else if let Some(changes) = edit.changes {
5144            operations.extend(changes.into_iter().map(|(uri, edits)| {
5145                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5146                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5147                        uri,
5148                        version: None,
5149                    },
5150                    edits: edits.into_iter().map(OneOf::Left).collect(),
5151                })
5152            }));
5153        }
5154
5155        let mut project_transaction = ProjectTransaction::default();
5156        for operation in operations {
5157            match operation {
5158                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5159                    let abs_path = op
5160                        .uri
5161                        .to_file_path()
5162                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5163
5164                    if let Some(parent_path) = abs_path.parent() {
5165                        fs.create_dir(parent_path).await?;
5166                    }
5167                    if abs_path.ends_with("/") {
5168                        fs.create_dir(&abs_path).await?;
5169                    } else {
5170                        fs.create_file(
5171                            &abs_path,
5172                            op.options
5173                                .map(|options| fs::CreateOptions {
5174                                    overwrite: options.overwrite.unwrap_or(false),
5175                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5176                                })
5177                                .unwrap_or_default(),
5178                        )
5179                        .await?;
5180                    }
5181                }
5182
5183                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5184                    let source_abs_path = op
5185                        .old_uri
5186                        .to_file_path()
5187                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5188                    let target_abs_path = op
5189                        .new_uri
5190                        .to_file_path()
5191                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5192                    fs.rename(
5193                        &source_abs_path,
5194                        &target_abs_path,
5195                        op.options
5196                            .map(|options| fs::RenameOptions {
5197                                overwrite: options.overwrite.unwrap_or(false),
5198                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5199                            })
5200                            .unwrap_or_default(),
5201                    )
5202                    .await?;
5203                }
5204
5205                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5206                    let abs_path = op
5207                        .uri
5208                        .to_file_path()
5209                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5210                    let options = op
5211                        .options
5212                        .map(|options| fs::RemoveOptions {
5213                            recursive: options.recursive.unwrap_or(false),
5214                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5215                        })
5216                        .unwrap_or_default();
5217                    if abs_path.ends_with("/") {
5218                        fs.remove_dir(&abs_path, options).await?;
5219                    } else {
5220                        fs.remove_file(&abs_path, options).await?;
5221                    }
5222                }
5223
5224                lsp::DocumentChangeOperation::Edit(op) => {
5225                    let buffer_to_edit = this
5226                        .update(cx, |this, cx| {
5227                            this.open_local_buffer_via_lsp(
5228                                op.text_document.uri,
5229                                language_server.server_id(),
5230                                lsp_adapter.name.clone(),
5231                                cx,
5232                            )
5233                        })
5234                        .await?;
5235
5236                    let edits = this
5237                        .update(cx, |this, cx| {
5238                            let edits = op.edits.into_iter().map(|edit| match edit {
5239                                OneOf::Left(edit) => edit,
5240                                OneOf::Right(edit) => edit.text_edit,
5241                            });
5242                            this.edits_from_lsp(
5243                                &buffer_to_edit,
5244                                edits,
5245                                language_server.server_id(),
5246                                op.text_document.version,
5247                                cx,
5248                            )
5249                        })
5250                        .await?;
5251
5252                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5253                        buffer.finalize_last_transaction();
5254                        buffer.start_transaction();
5255                        for (range, text) in edits {
5256                            buffer.edit([(range, text)], None, cx);
5257                        }
5258                        let transaction = if buffer.end_transaction(cx).is_some() {
5259                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5260                            if !push_to_history {
5261                                buffer.forget_transaction(transaction.id);
5262                            }
5263                            Some(transaction)
5264                        } else {
5265                            None
5266                        };
5267
5268                        transaction
5269                    });
5270                    if let Some(transaction) = transaction {
5271                        project_transaction.0.insert(buffer_to_edit, transaction);
5272                    }
5273                }
5274            }
5275        }
5276
5277        Ok(project_transaction)
5278    }
5279
5280    pub fn prepare_rename<T: ToPointUtf16>(
5281        &self,
5282        buffer: ModelHandle<Buffer>,
5283        position: T,
5284        cx: &mut ModelContext<Self>,
5285    ) -> Task<Result<Option<Range<Anchor>>>> {
5286        let position = position.to_point_utf16(buffer.read(cx));
5287        self.request_lsp(
5288            buffer,
5289            LanguageServerToQuery::Primary,
5290            PrepareRename { position },
5291            cx,
5292        )
5293    }
5294
5295    pub fn perform_rename<T: ToPointUtf16>(
5296        &self,
5297        buffer: ModelHandle<Buffer>,
5298        position: T,
5299        new_name: String,
5300        push_to_history: bool,
5301        cx: &mut ModelContext<Self>,
5302    ) -> Task<Result<ProjectTransaction>> {
5303        let position = position.to_point_utf16(buffer.read(cx));
5304        self.request_lsp(
5305            buffer,
5306            LanguageServerToQuery::Primary,
5307            PerformRename {
5308                position,
5309                new_name,
5310                push_to_history,
5311            },
5312            cx,
5313        )
5314    }
5315
5316    pub fn on_type_format<T: ToPointUtf16>(
5317        &self,
5318        buffer: ModelHandle<Buffer>,
5319        position: T,
5320        trigger: String,
5321        push_to_history: bool,
5322        cx: &mut ModelContext<Self>,
5323    ) -> Task<Result<Option<Transaction>>> {
5324        let (position, tab_size) = buffer.read_with(cx, |buffer, cx| {
5325            let position = position.to_point_utf16(buffer);
5326            (
5327                position,
5328                language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
5329                    .tab_size,
5330            )
5331        });
5332        self.request_lsp(
5333            buffer.clone(),
5334            LanguageServerToQuery::Primary,
5335            OnTypeFormatting {
5336                position,
5337                trigger,
5338                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5339                push_to_history,
5340            },
5341            cx,
5342        )
5343    }
5344
5345    pub fn inlay_hints<T: ToOffset>(
5346        &self,
5347        buffer_handle: ModelHandle<Buffer>,
5348        range: Range<T>,
5349        cx: &mut ModelContext<Self>,
5350    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5351        let buffer = buffer_handle.read(cx);
5352        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5353        let range_start = range.start;
5354        let range_end = range.end;
5355        let buffer_id = buffer.remote_id();
5356        let buffer_version = buffer.version().clone();
5357        let lsp_request = InlayHints { range };
5358
5359        if self.is_local() {
5360            let lsp_request_task = self.request_lsp(
5361                buffer_handle.clone(),
5362                LanguageServerToQuery::Primary,
5363                lsp_request,
5364                cx,
5365            );
5366            cx.spawn(|_, mut cx| async move {
5367                buffer_handle
5368                    .update(&mut cx, |buffer, _| {
5369                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5370                    })
5371                    .await
5372                    .context("waiting for inlay hint request range edits")?;
5373                lsp_request_task.await.context("inlay hints LSP request")
5374            })
5375        } else if let Some(project_id) = self.remote_id() {
5376            let client = self.client.clone();
5377            let request = proto::InlayHints {
5378                project_id,
5379                buffer_id,
5380                start: Some(serialize_anchor(&range_start)),
5381                end: Some(serialize_anchor(&range_end)),
5382                version: serialize_version(&buffer_version),
5383            };
5384            cx.spawn(|project, cx| async move {
5385                let response = client
5386                    .request(request)
5387                    .await
5388                    .context("inlay hints proto request")?;
5389                let hints_request_result = LspCommand::response_from_proto(
5390                    lsp_request,
5391                    response,
5392                    project,
5393                    buffer_handle.clone(),
5394                    cx,
5395                )
5396                .await;
5397
5398                hints_request_result.context("inlay hints proto response conversion")
5399            })
5400        } else {
5401            Task::ready(Err(anyhow!("project does not have a remote id")))
5402        }
5403    }
5404
5405    pub fn resolve_inlay_hint(
5406        &self,
5407        hint: InlayHint,
5408        buffer_handle: ModelHandle<Buffer>,
5409        server_id: LanguageServerId,
5410        cx: &mut ModelContext<Self>,
5411    ) -> Task<anyhow::Result<InlayHint>> {
5412        if self.is_local() {
5413            let buffer = buffer_handle.read(cx);
5414            let (_, lang_server) = if let Some((adapter, server)) =
5415                self.language_server_for_buffer(buffer, server_id, cx)
5416            {
5417                (adapter.clone(), server.clone())
5418            } else {
5419                return Task::ready(Ok(hint));
5420            };
5421            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5422                return Task::ready(Ok(hint));
5423            }
5424
5425            let buffer_snapshot = buffer.snapshot();
5426            cx.spawn(|_, mut cx| async move {
5427                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5428                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5429                );
5430                let resolved_hint = resolve_task
5431                    .await
5432                    .context("inlay hint resolve LSP request")?;
5433                let resolved_hint = InlayHints::lsp_to_project_hint(
5434                    resolved_hint,
5435                    &buffer_handle,
5436                    server_id,
5437                    ResolveState::Resolved,
5438                    false,
5439                    &mut cx,
5440                )
5441                .await?;
5442                Ok(resolved_hint)
5443            })
5444        } else if let Some(project_id) = self.remote_id() {
5445            let client = self.client.clone();
5446            let request = proto::ResolveInlayHint {
5447                project_id,
5448                buffer_id: buffer_handle.read(cx).remote_id(),
5449                language_server_id: server_id.0 as u64,
5450                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5451            };
5452            cx.spawn(|_, _| async move {
5453                let response = client
5454                    .request(request)
5455                    .await
5456                    .context("inlay hints proto request")?;
5457                match response.hint {
5458                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5459                        .context("inlay hints proto resolve response conversion"),
5460                    None => Ok(hint),
5461                }
5462            })
5463        } else {
5464            Task::ready(Err(anyhow!("project does not have a remote id")))
5465        }
5466    }
5467
5468    #[allow(clippy::type_complexity)]
5469    pub fn search(
5470        &self,
5471        query: SearchQuery,
5472        cx: &mut ModelContext<Self>,
5473    ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5474        if self.is_local() {
5475            self.search_local(query, cx)
5476        } else if let Some(project_id) = self.remote_id() {
5477            let (tx, rx) = smol::channel::unbounded();
5478            let request = self.client.request(query.to_proto(project_id));
5479            cx.spawn(|this, mut cx| async move {
5480                let response = request.await?;
5481                let mut result = HashMap::default();
5482                for location in response.locations {
5483                    let target_buffer = this
5484                        .update(&mut cx, |this, cx| {
5485                            this.wait_for_remote_buffer(location.buffer_id, cx)
5486                        })
5487                        .await?;
5488                    let start = location
5489                        .start
5490                        .and_then(deserialize_anchor)
5491                        .ok_or_else(|| anyhow!("missing target start"))?;
5492                    let end = location
5493                        .end
5494                        .and_then(deserialize_anchor)
5495                        .ok_or_else(|| anyhow!("missing target end"))?;
5496                    result
5497                        .entry(target_buffer)
5498                        .or_insert(Vec::new())
5499                        .push(start..end)
5500                }
5501                for (buffer, ranges) in result {
5502                    let _ = tx.send((buffer, ranges)).await;
5503                }
5504                Result::<(), anyhow::Error>::Ok(())
5505            })
5506            .detach_and_log_err(cx);
5507            rx
5508        } else {
5509            unimplemented!();
5510        }
5511    }
5512
5513    pub fn search_local(
5514        &self,
5515        query: SearchQuery,
5516        cx: &mut ModelContext<Self>,
5517    ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5518        // Local search is split into several phases.
5519        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5520        // and the second phase that finds positions of all the matches found in the candidate files.
5521        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5522        //
5523        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5524        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5525        //
5526        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5527        //    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
5528        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5529        // 2. At this point, we have a list of all potentially matching buffers/files.
5530        //    We sort that list by buffer path - this list is retained for later use.
5531        //    We ensure that all buffers are now opened and available in project.
5532        // 3. We run a scan over all the candidate buffers on multiple background threads.
5533        //    We cannot assume that there will even be a match - while at least one match
5534        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5535        //    There is also an auxilliary background thread responsible for result gathering.
5536        //    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),
5537        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5538        //    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
5539        //    entry - which might already be available thanks to out-of-order processing.
5540        //
5541        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5542        // 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.
5543        // 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
5544        // in face of constantly updating list of sorted matches.
5545        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5546        let snapshots = self
5547            .visible_worktrees(cx)
5548            .filter_map(|tree| {
5549                let tree = tree.read(cx).as_local()?;
5550                Some(tree.snapshot())
5551            })
5552            .collect::<Vec<_>>();
5553
5554        let background = cx.background().clone();
5555        let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
5556        if path_count == 0 {
5557            let (_, rx) = smol::channel::bounded(1024);
5558            return rx;
5559        }
5560        let workers = background.num_cpus().min(path_count);
5561        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5562        let mut unnamed_files = vec![];
5563        let opened_buffers = self
5564            .opened_buffers
5565            .iter()
5566            .filter_map(|(_, b)| {
5567                let buffer = b.upgrade(cx)?;
5568                let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
5569                if let Some(path) = snapshot.file().map(|file| file.path()) {
5570                    Some((path.clone(), (buffer, snapshot)))
5571                } else {
5572                    unnamed_files.push(buffer);
5573                    None
5574                }
5575            })
5576            .collect();
5577        cx.background()
5578            .spawn(Self::background_search(
5579                unnamed_files,
5580                opened_buffers,
5581                cx.background().clone(),
5582                self.fs.clone(),
5583                workers,
5584                query.clone(),
5585                path_count,
5586                snapshots,
5587                matching_paths_tx,
5588            ))
5589            .detach();
5590
5591        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5592        let background = cx.background().clone();
5593        let (result_tx, result_rx) = smol::channel::bounded(1024);
5594        cx.background()
5595            .spawn(async move {
5596                let Ok(buffers) = buffers.await else {
5597                    return;
5598                };
5599
5600                let buffers_len = buffers.len();
5601                if buffers_len == 0 {
5602                    return;
5603                }
5604                let query = &query;
5605                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5606                background
5607                    .scoped(|scope| {
5608                        #[derive(Clone)]
5609                        struct FinishedStatus {
5610                            entry: Option<(ModelHandle<Buffer>, Vec<Range<Anchor>>)>,
5611                            buffer_index: SearchMatchCandidateIndex,
5612                        }
5613
5614                        for _ in 0..workers {
5615                            let finished_tx = finished_tx.clone();
5616                            let mut buffers_rx = buffers_rx.clone();
5617                            scope.spawn(async move {
5618                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
5619                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5620                                    {
5621                                        if query.file_matches(
5622                                            snapshot.file().map(|file| file.path().as_ref()),
5623                                        ) {
5624                                            query
5625                                                .search(&snapshot, None)
5626                                                .await
5627                                                .iter()
5628                                                .map(|range| {
5629                                                    snapshot.anchor_before(range.start)
5630                                                        ..snapshot.anchor_after(range.end)
5631                                                })
5632                                                .collect()
5633                                        } else {
5634                                            Vec::new()
5635                                        }
5636                                    } else {
5637                                        Vec::new()
5638                                    };
5639
5640                                    let status = if !buffer_matches.is_empty() {
5641                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
5642                                            Some((buffer.clone(), buffer_matches))
5643                                        } else {
5644                                            None
5645                                        };
5646                                        FinishedStatus {
5647                                            entry,
5648                                            buffer_index,
5649                                        }
5650                                    } else {
5651                                        FinishedStatus {
5652                                            entry: None,
5653                                            buffer_index,
5654                                        }
5655                                    };
5656                                    if finished_tx.send(status).await.is_err() {
5657                                        break;
5658                                    }
5659                                }
5660                            });
5661                        }
5662                        // Report sorted matches
5663                        scope.spawn(async move {
5664                            let mut current_index = 0;
5665                            let mut scratch = vec![None; buffers_len];
5666                            while let Some(status) = finished_rx.next().await {
5667                                debug_assert!(
5668                                    scratch[status.buffer_index].is_none(),
5669                                    "Got match status of position {} twice",
5670                                    status.buffer_index
5671                                );
5672                                let index = status.buffer_index;
5673                                scratch[index] = Some(status);
5674                                while current_index < buffers_len {
5675                                    let Some(current_entry) = scratch[current_index].take() else {
5676                                        // We intentionally **do not** increment `current_index` here. When next element arrives
5677                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5678                                        // this time.
5679                                        break;
5680                                    };
5681                                    if let Some(entry) = current_entry.entry {
5682                                        result_tx.send(entry).await.log_err();
5683                                    }
5684                                    current_index += 1;
5685                                }
5686                                if current_index == buffers_len {
5687                                    break;
5688                                }
5689                            }
5690                        });
5691                    })
5692                    .await;
5693            })
5694            .detach();
5695        result_rx
5696    }
5697    /// Pick paths that might potentially contain a match of a given search query.
5698    async fn background_search(
5699        unnamed_buffers: Vec<ModelHandle<Buffer>>,
5700        opened_buffers: HashMap<Arc<Path>, (ModelHandle<Buffer>, BufferSnapshot)>,
5701        background: Arc<Background>,
5702        fs: Arc<dyn Fs>,
5703        workers: usize,
5704        query: SearchQuery,
5705        path_count: usize,
5706        snapshots: Vec<LocalSnapshot>,
5707        matching_paths_tx: Sender<SearchMatchCandidate>,
5708    ) {
5709        let fs = &fs;
5710        let query = &query;
5711        let matching_paths_tx = &matching_paths_tx;
5712        let snapshots = &snapshots;
5713        let paths_per_worker = (path_count + workers - 1) / workers;
5714        for buffer in unnamed_buffers {
5715            matching_paths_tx
5716                .send(SearchMatchCandidate::OpenBuffer {
5717                    buffer: buffer.clone(),
5718                    path: None,
5719                })
5720                .await
5721                .log_err();
5722        }
5723        for (path, (buffer, _)) in opened_buffers.iter() {
5724            matching_paths_tx
5725                .send(SearchMatchCandidate::OpenBuffer {
5726                    buffer: buffer.clone(),
5727                    path: Some(path.clone()),
5728                })
5729                .await
5730                .log_err();
5731        }
5732        background
5733            .scoped(|scope| {
5734                for worker_ix in 0..workers {
5735                    let worker_start_ix = worker_ix * paths_per_worker;
5736                    let worker_end_ix = worker_start_ix + paths_per_worker;
5737                    let unnamed_buffers = opened_buffers.clone();
5738                    scope.spawn(async move {
5739                        let mut snapshot_start_ix = 0;
5740                        let mut abs_path = PathBuf::new();
5741                        for snapshot in snapshots {
5742                            let snapshot_end_ix = snapshot_start_ix + snapshot.visible_file_count();
5743                            if worker_end_ix <= snapshot_start_ix {
5744                                break;
5745                            } else if worker_start_ix > snapshot_end_ix {
5746                                snapshot_start_ix = snapshot_end_ix;
5747                                continue;
5748                            } else {
5749                                let start_in_snapshot =
5750                                    worker_start_ix.saturating_sub(snapshot_start_ix);
5751                                let end_in_snapshot =
5752                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5753
5754                                for entry in snapshot
5755                                    .files(false, start_in_snapshot)
5756                                    .take(end_in_snapshot - start_in_snapshot)
5757                                {
5758                                    if matching_paths_tx.is_closed() {
5759                                        break;
5760                                    }
5761                                    if unnamed_buffers.contains_key(&entry.path) {
5762                                        continue;
5763                                    }
5764                                    let matches = if query.file_matches(Some(&entry.path)) {
5765                                        abs_path.clear();
5766                                        abs_path.push(&snapshot.abs_path());
5767                                        abs_path.push(&entry.path);
5768                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
5769                                        {
5770                                            query.detect(file).unwrap_or(false)
5771                                        } else {
5772                                            false
5773                                        }
5774                                    } else {
5775                                        false
5776                                    };
5777
5778                                    if matches {
5779                                        let project_path = SearchMatchCandidate::Path {
5780                                            worktree_id: snapshot.id(),
5781                                            path: entry.path.clone(),
5782                                        };
5783                                        if matching_paths_tx.send(project_path).await.is_err() {
5784                                            break;
5785                                        }
5786                                    }
5787                                }
5788
5789                                snapshot_start_ix = snapshot_end_ix;
5790                            }
5791                        }
5792                    });
5793                }
5794            })
5795            .await;
5796    }
5797
5798    fn request_lsp<R: LspCommand>(
5799        &self,
5800        buffer_handle: ModelHandle<Buffer>,
5801        server: LanguageServerToQuery,
5802        request: R,
5803        cx: &mut ModelContext<Self>,
5804    ) -> Task<Result<R::Response>>
5805    where
5806        <R::LspRequest as lsp::request::Request>::Result: Send,
5807    {
5808        let buffer = buffer_handle.read(cx);
5809        if self.is_local() {
5810            let language_server = match server {
5811                LanguageServerToQuery::Primary => {
5812                    match self.primary_language_server_for_buffer(buffer, cx) {
5813                        Some((_, server)) => Some(Arc::clone(server)),
5814                        None => return Task::ready(Ok(Default::default())),
5815                    }
5816                }
5817                LanguageServerToQuery::Other(id) => self
5818                    .language_server_for_buffer(buffer, id, cx)
5819                    .map(|(_, server)| Arc::clone(server)),
5820            };
5821            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5822            if let (Some(file), Some(language_server)) = (file, language_server) {
5823                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5824                return cx.spawn(|this, cx| async move {
5825                    if !request.check_capabilities(language_server.capabilities()) {
5826                        return Ok(Default::default());
5827                    }
5828
5829                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
5830                    let response = match result {
5831                        Ok(response) => response,
5832
5833                        Err(err) => {
5834                            log::warn!(
5835                                "Generic lsp request to {} failed: {}",
5836                                language_server.name(),
5837                                err
5838                            );
5839                            return Err(err);
5840                        }
5841                    };
5842
5843                    request
5844                        .response_from_lsp(
5845                            response,
5846                            this,
5847                            buffer_handle,
5848                            language_server.server_id(),
5849                            cx,
5850                        )
5851                        .await
5852                });
5853            }
5854        } else if let Some(project_id) = self.remote_id() {
5855            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
5856        }
5857
5858        Task::ready(Ok(Default::default()))
5859    }
5860
5861    fn send_lsp_proto_request<R: LspCommand>(
5862        &self,
5863        buffer: ModelHandle<Buffer>,
5864        project_id: u64,
5865        request: R,
5866        cx: &mut ModelContext<'_, Project>,
5867    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
5868        let rpc = self.client.clone();
5869        let message = request.to_proto(project_id, buffer.read(cx));
5870        cx.spawn_weak(|this, cx| async move {
5871            // Ensure the project is still alive by the time the task
5872            // is scheduled.
5873            this.upgrade(&cx)
5874                .ok_or_else(|| anyhow!("project dropped"))?;
5875            let response = rpc.request(message).await?;
5876            let this = this
5877                .upgrade(&cx)
5878                .ok_or_else(|| anyhow!("project dropped"))?;
5879            if this.read_with(&cx, |this, _| this.is_read_only()) {
5880                Err(anyhow!("disconnected before completing request"))
5881            } else {
5882                request
5883                    .response_from_proto(response, this, buffer, cx)
5884                    .await
5885            }
5886        })
5887    }
5888
5889    fn sort_candidates_and_open_buffers(
5890        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
5891        cx: &mut ModelContext<Self>,
5892    ) -> (
5893        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
5894        Receiver<(
5895            Option<(ModelHandle<Buffer>, BufferSnapshot)>,
5896            SearchMatchCandidateIndex,
5897        )>,
5898    ) {
5899        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
5900        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
5901        cx.spawn(|this, cx| async move {
5902            let mut buffers = vec![];
5903            while let Some(entry) = matching_paths_rx.next().await {
5904                buffers.push(entry);
5905            }
5906            buffers.sort_by_key(|candidate| candidate.path());
5907            let matching_paths = buffers.clone();
5908            let _ = sorted_buffers_tx.send(buffers);
5909            for (index, candidate) in matching_paths.into_iter().enumerate() {
5910                if buffers_tx.is_closed() {
5911                    break;
5912                }
5913                let this = this.clone();
5914                let buffers_tx = buffers_tx.clone();
5915                cx.spawn(|mut cx| async move {
5916                    let buffer = match candidate {
5917                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
5918                        SearchMatchCandidate::Path { worktree_id, path } => this
5919                            .update(&mut cx, |this, cx| {
5920                                this.open_buffer((worktree_id, path), cx)
5921                            })
5922                            .await
5923                            .log_err(),
5924                    };
5925                    if let Some(buffer) = buffer {
5926                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5927                        buffers_tx
5928                            .send((Some((buffer, snapshot)), index))
5929                            .await
5930                            .log_err();
5931                    } else {
5932                        buffers_tx.send((None, index)).await.log_err();
5933                    }
5934
5935                    Ok::<_, anyhow::Error>(())
5936                })
5937                .detach();
5938            }
5939        })
5940        .detach();
5941        (sorted_buffers_rx, buffers_rx)
5942    }
5943
5944    pub fn find_or_create_local_worktree(
5945        &mut self,
5946        abs_path: impl AsRef<Path>,
5947        visible: bool,
5948        cx: &mut ModelContext<Self>,
5949    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
5950        let abs_path = abs_path.as_ref();
5951        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
5952            Task::ready(Ok((tree, relative_path)))
5953        } else {
5954            let worktree = self.create_local_worktree(abs_path, visible, cx);
5955            cx.foreground()
5956                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
5957        }
5958    }
5959
5960    pub fn find_local_worktree(
5961        &self,
5962        abs_path: &Path,
5963        cx: &AppContext,
5964    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
5965        for tree in &self.worktrees {
5966            if let Some(tree) = tree.upgrade(cx) {
5967                if let Some(relative_path) = tree
5968                    .read(cx)
5969                    .as_local()
5970                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
5971                {
5972                    return Some((tree.clone(), relative_path.into()));
5973                }
5974            }
5975        }
5976        None
5977    }
5978
5979    pub fn is_shared(&self) -> bool {
5980        match &self.client_state {
5981            Some(ProjectClientState::Local { .. }) => true,
5982            _ => false,
5983        }
5984    }
5985
5986    fn create_local_worktree(
5987        &mut self,
5988        abs_path: impl AsRef<Path>,
5989        visible: bool,
5990        cx: &mut ModelContext<Self>,
5991    ) -> Task<Result<ModelHandle<Worktree>>> {
5992        let fs = self.fs.clone();
5993        let client = self.client.clone();
5994        let next_entry_id = self.next_entry_id.clone();
5995        let path: Arc<Path> = abs_path.as_ref().into();
5996        let task = self
5997            .loading_local_worktrees
5998            .entry(path.clone())
5999            .or_insert_with(|| {
6000                cx.spawn(|project, mut cx| {
6001                    async move {
6002                        let worktree = Worktree::local(
6003                            client.clone(),
6004                            path.clone(),
6005                            visible,
6006                            fs,
6007                            next_entry_id,
6008                            &mut cx,
6009                        )
6010                        .await;
6011
6012                        project.update(&mut cx, |project, _| {
6013                            project.loading_local_worktrees.remove(&path);
6014                        });
6015
6016                        let worktree = worktree?;
6017                        project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
6018                        Ok(worktree)
6019                    }
6020                    .map_err(Arc::new)
6021                })
6022                .shared()
6023            })
6024            .clone();
6025        cx.foreground().spawn(async move {
6026            match task.await {
6027                Ok(worktree) => Ok(worktree),
6028                Err(err) => Err(anyhow!("{}", err)),
6029            }
6030        })
6031    }
6032
6033    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6034        self.worktrees.retain(|worktree| {
6035            if let Some(worktree) = worktree.upgrade(cx) {
6036                let id = worktree.read(cx).id();
6037                if id == id_to_remove {
6038                    cx.emit(Event::WorktreeRemoved(id));
6039                    false
6040                } else {
6041                    true
6042                }
6043            } else {
6044                false
6045            }
6046        });
6047        self.metadata_changed(cx);
6048    }
6049
6050    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
6051        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6052        if worktree.read(cx).is_local() {
6053            cx.subscribe(worktree, |this, worktree, event, cx| match event {
6054                worktree::Event::UpdatedEntries(changes) => {
6055                    this.update_local_worktree_buffers(&worktree, changes, cx);
6056                    this.update_local_worktree_language_servers(&worktree, changes, cx);
6057                    this.update_local_worktree_settings(&worktree, changes, cx);
6058                    this.update_prettier_settings(&worktree, changes, cx);
6059                    cx.emit(Event::WorktreeUpdatedEntries(
6060                        worktree.read(cx).id(),
6061                        changes.clone(),
6062                    ));
6063                }
6064                worktree::Event::UpdatedGitRepositories(updated_repos) => {
6065                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6066                }
6067            })
6068            .detach();
6069        }
6070
6071        let push_strong_handle = {
6072            let worktree = worktree.read(cx);
6073            self.is_shared() || worktree.is_visible() || worktree.is_remote()
6074        };
6075        if push_strong_handle {
6076            self.worktrees
6077                .push(WorktreeHandle::Strong(worktree.clone()));
6078        } else {
6079            self.worktrees
6080                .push(WorktreeHandle::Weak(worktree.downgrade()));
6081        }
6082
6083        let handle_id = worktree.id();
6084        cx.observe_release(worktree, move |this, worktree, cx| {
6085            let _ = this.remove_worktree(worktree.id(), cx);
6086            cx.update_global::<SettingsStore, _, _>(|store, cx| {
6087                store.clear_local_settings(handle_id, cx).log_err()
6088            });
6089        })
6090        .detach();
6091
6092        cx.emit(Event::WorktreeAdded);
6093        self.metadata_changed(cx);
6094    }
6095
6096    fn update_local_worktree_buffers(
6097        &mut self,
6098        worktree_handle: &ModelHandle<Worktree>,
6099        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6100        cx: &mut ModelContext<Self>,
6101    ) {
6102        let snapshot = worktree_handle.read(cx).snapshot();
6103
6104        let mut renamed_buffers = Vec::new();
6105        for (path, entry_id, _) in changes {
6106            let worktree_id = worktree_handle.read(cx).id();
6107            let project_path = ProjectPath {
6108                worktree_id,
6109                path: path.clone(),
6110            };
6111
6112            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6113                Some(&buffer_id) => buffer_id,
6114                None => match self.local_buffer_ids_by_path.get(&project_path) {
6115                    Some(&buffer_id) => buffer_id,
6116                    None => {
6117                        continue;
6118                    }
6119                },
6120            };
6121
6122            let open_buffer = self.opened_buffers.get(&buffer_id);
6123            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
6124                buffer
6125            } else {
6126                self.opened_buffers.remove(&buffer_id);
6127                self.local_buffer_ids_by_path.remove(&project_path);
6128                self.local_buffer_ids_by_entry_id.remove(entry_id);
6129                continue;
6130            };
6131
6132            buffer.update(cx, |buffer, cx| {
6133                if let Some(old_file) = File::from_dyn(buffer.file()) {
6134                    if old_file.worktree != *worktree_handle {
6135                        return;
6136                    }
6137
6138                    let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
6139                        File {
6140                            is_local: true,
6141                            entry_id: entry.id,
6142                            mtime: entry.mtime,
6143                            path: entry.path.clone(),
6144                            worktree: worktree_handle.clone(),
6145                            is_deleted: false,
6146                        }
6147                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6148                        File {
6149                            is_local: true,
6150                            entry_id: entry.id,
6151                            mtime: entry.mtime,
6152                            path: entry.path.clone(),
6153                            worktree: worktree_handle.clone(),
6154                            is_deleted: false,
6155                        }
6156                    } else {
6157                        File {
6158                            is_local: true,
6159                            entry_id: old_file.entry_id,
6160                            path: old_file.path().clone(),
6161                            mtime: old_file.mtime(),
6162                            worktree: worktree_handle.clone(),
6163                            is_deleted: true,
6164                        }
6165                    };
6166
6167                    let old_path = old_file.abs_path(cx);
6168                    if new_file.abs_path(cx) != old_path {
6169                        renamed_buffers.push((cx.handle(), old_file.clone()));
6170                        self.local_buffer_ids_by_path.remove(&project_path);
6171                        self.local_buffer_ids_by_path.insert(
6172                            ProjectPath {
6173                                worktree_id,
6174                                path: path.clone(),
6175                            },
6176                            buffer_id,
6177                        );
6178                    }
6179
6180                    if new_file.entry_id != *entry_id {
6181                        self.local_buffer_ids_by_entry_id.remove(entry_id);
6182                        self.local_buffer_ids_by_entry_id
6183                            .insert(new_file.entry_id, buffer_id);
6184                    }
6185
6186                    if new_file != *old_file {
6187                        if let Some(project_id) = self.remote_id() {
6188                            self.client
6189                                .send(proto::UpdateBufferFile {
6190                                    project_id,
6191                                    buffer_id: buffer_id as u64,
6192                                    file: Some(new_file.to_proto()),
6193                                })
6194                                .log_err();
6195                        }
6196
6197                        buffer.file_updated(Arc::new(new_file), cx).detach();
6198                    }
6199                }
6200            });
6201        }
6202
6203        for (buffer, old_file) in renamed_buffers {
6204            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6205            self.detect_language_for_buffer(&buffer, cx);
6206            self.register_buffer_with_language_servers(&buffer, cx);
6207        }
6208    }
6209
6210    fn update_local_worktree_language_servers(
6211        &mut self,
6212        worktree_handle: &ModelHandle<Worktree>,
6213        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6214        cx: &mut ModelContext<Self>,
6215    ) {
6216        if changes.is_empty() {
6217            return;
6218        }
6219
6220        let worktree_id = worktree_handle.read(cx).id();
6221        let mut language_server_ids = self
6222            .language_server_ids
6223            .iter()
6224            .filter_map(|((server_worktree_id, _), server_id)| {
6225                (*server_worktree_id == worktree_id).then_some(*server_id)
6226            })
6227            .collect::<Vec<_>>();
6228        language_server_ids.sort();
6229        language_server_ids.dedup();
6230
6231        let abs_path = worktree_handle.read(cx).abs_path();
6232        for server_id in &language_server_ids {
6233            if let Some(LanguageServerState::Running {
6234                server,
6235                watched_paths,
6236                ..
6237            }) = self.language_servers.get(server_id)
6238            {
6239                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6240                    let params = lsp::DidChangeWatchedFilesParams {
6241                        changes: changes
6242                            .iter()
6243                            .filter_map(|(path, _, change)| {
6244                                if !watched_paths.is_match(&path) {
6245                                    return None;
6246                                }
6247                                let typ = match change {
6248                                    PathChange::Loaded => return None,
6249                                    PathChange::Added => lsp::FileChangeType::CREATED,
6250                                    PathChange::Removed => lsp::FileChangeType::DELETED,
6251                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
6252                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6253                                };
6254                                Some(lsp::FileEvent {
6255                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6256                                    typ,
6257                                })
6258                            })
6259                            .collect(),
6260                    };
6261
6262                    if !params.changes.is_empty() {
6263                        server
6264                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6265                            .log_err();
6266                    }
6267                }
6268            }
6269        }
6270    }
6271
6272    fn update_local_worktree_buffers_git_repos(
6273        &mut self,
6274        worktree_handle: ModelHandle<Worktree>,
6275        changed_repos: &UpdatedGitRepositoriesSet,
6276        cx: &mut ModelContext<Self>,
6277    ) {
6278        debug_assert!(worktree_handle.read(cx).is_local());
6279
6280        // Identify the loading buffers whose containing repository that has changed.
6281        let future_buffers = self
6282            .loading_buffers_by_path
6283            .iter()
6284            .filter_map(|(project_path, receiver)| {
6285                if project_path.worktree_id != worktree_handle.read(cx).id() {
6286                    return None;
6287                }
6288                let path = &project_path.path;
6289                changed_repos
6290                    .iter()
6291                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6292                let receiver = receiver.clone();
6293                let path = path.clone();
6294                Some(async move {
6295                    wait_for_loading_buffer(receiver)
6296                        .await
6297                        .ok()
6298                        .map(|buffer| (buffer, path))
6299                })
6300            })
6301            .collect::<FuturesUnordered<_>>();
6302
6303        // Identify the current buffers whose containing repository has changed.
6304        let current_buffers = self
6305            .opened_buffers
6306            .values()
6307            .filter_map(|buffer| {
6308                let buffer = buffer.upgrade(cx)?;
6309                let file = File::from_dyn(buffer.read(cx).file())?;
6310                if file.worktree != worktree_handle {
6311                    return None;
6312                }
6313                let path = file.path();
6314                changed_repos
6315                    .iter()
6316                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6317                Some((buffer, path.clone()))
6318            })
6319            .collect::<Vec<_>>();
6320
6321        if future_buffers.len() + current_buffers.len() == 0 {
6322            return;
6323        }
6324
6325        let remote_id = self.remote_id();
6326        let client = self.client.clone();
6327        cx.spawn_weak(move |_, mut cx| async move {
6328            // Wait for all of the buffers to load.
6329            let future_buffers = future_buffers.collect::<Vec<_>>().await;
6330
6331            // Reload the diff base for every buffer whose containing git repository has changed.
6332            let snapshot =
6333                worktree_handle.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
6334            let diff_bases_by_buffer = cx
6335                .background()
6336                .spawn(async move {
6337                    future_buffers
6338                        .into_iter()
6339                        .filter_map(|e| e)
6340                        .chain(current_buffers)
6341                        .filter_map(|(buffer, path)| {
6342                            let (work_directory, repo) =
6343                                snapshot.repository_and_work_directory_for_path(&path)?;
6344                            let repo = snapshot.get_local_repo(&repo)?;
6345                            let relative_path = path.strip_prefix(&work_directory).ok()?;
6346                            let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
6347                            Some((buffer, base_text))
6348                        })
6349                        .collect::<Vec<_>>()
6350                })
6351                .await;
6352
6353            // Assign the new diff bases on all of the buffers.
6354            for (buffer, diff_base) in diff_bases_by_buffer {
6355                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6356                    buffer.set_diff_base(diff_base.clone(), cx);
6357                    buffer.remote_id()
6358                });
6359                if let Some(project_id) = remote_id {
6360                    client
6361                        .send(proto::UpdateDiffBase {
6362                            project_id,
6363                            buffer_id,
6364                            diff_base,
6365                        })
6366                        .log_err();
6367                }
6368            }
6369        })
6370        .detach();
6371    }
6372
6373    fn update_local_worktree_settings(
6374        &mut self,
6375        worktree: &ModelHandle<Worktree>,
6376        changes: &UpdatedEntriesSet,
6377        cx: &mut ModelContext<Self>,
6378    ) {
6379        let project_id = self.remote_id();
6380        let worktree_id = worktree.id();
6381        let worktree = worktree.read(cx).as_local().unwrap();
6382        let remote_worktree_id = worktree.id();
6383
6384        let mut settings_contents = Vec::new();
6385        for (path, _, change) in changes.iter() {
6386            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6387                let settings_dir = Arc::from(
6388                    path.ancestors()
6389                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6390                        .unwrap(),
6391                );
6392                let fs = self.fs.clone();
6393                let removed = *change == PathChange::Removed;
6394                let abs_path = worktree.absolutize(path);
6395                settings_contents.push(async move {
6396                    (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
6397                });
6398            }
6399        }
6400
6401        if settings_contents.is_empty() {
6402            return;
6403        }
6404
6405        let client = self.client.clone();
6406        cx.spawn_weak(move |_, mut cx| async move {
6407            let settings_contents: Vec<(Arc<Path>, _)> =
6408                futures::future::join_all(settings_contents).await;
6409            cx.update(|cx| {
6410                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6411                    for (directory, file_content) in settings_contents {
6412                        let file_content = file_content.and_then(|content| content.log_err());
6413                        store
6414                            .set_local_settings(
6415                                worktree_id,
6416                                directory.clone(),
6417                                file_content.as_ref().map(String::as_str),
6418                                cx,
6419                            )
6420                            .log_err();
6421                        if let Some(remote_id) = project_id {
6422                            client
6423                                .send(proto::UpdateWorktreeSettings {
6424                                    project_id: remote_id,
6425                                    worktree_id: remote_worktree_id.to_proto(),
6426                                    path: directory.to_string_lossy().into_owned(),
6427                                    content: file_content,
6428                                })
6429                                .log_err();
6430                        }
6431                    }
6432                });
6433            });
6434        })
6435        .detach();
6436    }
6437
6438    fn update_prettier_settings(
6439        &self,
6440        worktree: &ModelHandle<Worktree>,
6441        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6442        cx: &mut ModelContext<'_, Project>,
6443    ) {
6444        let prettier_config_files = Prettier::CONFIG_FILE_NAMES
6445            .iter()
6446            .map(Path::new)
6447            .collect::<HashSet<_>>();
6448
6449        let prettier_config_file_changed = changes
6450            .iter()
6451            .filter(|(_, _, change)| !matches!(change, PathChange::Loaded))
6452            .filter(|(path, _, _)| {
6453                !path
6454                    .components()
6455                    .any(|component| component.as_os_str().to_string_lossy() == "node_modules")
6456            })
6457            .find(|(path, _, _)| prettier_config_files.contains(path.as_ref()));
6458        let current_worktree_id = worktree.read(cx).id();
6459        if let Some((config_path, _, _)) = prettier_config_file_changed {
6460            log::info!(
6461                "Prettier config file {config_path:?} changed, reloading prettier instances for worktree {current_worktree_id}"
6462            );
6463            let prettiers_to_reload = self
6464                .prettiers_per_worktree
6465                .get(&current_worktree_id)
6466                .iter()
6467                .flat_map(|prettier_paths| prettier_paths.iter())
6468                .flatten()
6469                .filter_map(|prettier_path| {
6470                    Some((
6471                        current_worktree_id,
6472                        Some(prettier_path.clone()),
6473                        self.prettier_instances.get(prettier_path)?.clone(),
6474                    ))
6475                })
6476                .chain(self.default_prettier.iter().filter_map(|default_prettier| {
6477                    Some((
6478                        current_worktree_id,
6479                        None,
6480                        default_prettier.instance.clone()?,
6481                    ))
6482                }))
6483                .collect::<Vec<_>>();
6484
6485            cx.background()
6486                .spawn(async move {
6487                    for task_result in future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_task)| {
6488                        async move {
6489                            prettier_task.await?
6490                                .clear_cache()
6491                                .await
6492                                .with_context(|| {
6493                                    match prettier_path {
6494                                        Some(prettier_path) => format!(
6495                                            "clearing prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update"
6496                                        ),
6497                                        None => format!(
6498                                            "clearing default prettier cache for worktree {worktree_id:?} on prettier settings update"
6499                                        ),
6500                                    }
6501
6502                                })
6503                                .map_err(Arc::new)
6504                        }
6505                    }))
6506                    .await
6507                    {
6508                        if let Err(e) = task_result {
6509                            log::error!("Failed to clear cache for prettier: {e:#}");
6510                        }
6511                    }
6512                })
6513                .detach();
6514        }
6515    }
6516
6517    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6518        let new_active_entry = entry.and_then(|project_path| {
6519            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6520            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6521            Some(entry.id)
6522        });
6523        if new_active_entry != self.active_entry {
6524            self.active_entry = new_active_entry;
6525            cx.emit(Event::ActiveEntryChanged(new_active_entry));
6526        }
6527    }
6528
6529    pub fn language_servers_running_disk_based_diagnostics(
6530        &self,
6531    ) -> impl Iterator<Item = LanguageServerId> + '_ {
6532        self.language_server_statuses
6533            .iter()
6534            .filter_map(|(id, status)| {
6535                if status.has_pending_diagnostic_updates {
6536                    Some(*id)
6537                } else {
6538                    None
6539                }
6540            })
6541    }
6542
6543    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
6544        let mut summary = DiagnosticSummary::default();
6545        for (_, _, path_summary) in self.diagnostic_summaries(cx) {
6546            summary.error_count += path_summary.error_count;
6547            summary.warning_count += path_summary.warning_count;
6548        }
6549        summary
6550    }
6551
6552    pub fn diagnostic_summaries<'a>(
6553        &'a self,
6554        cx: &'a AppContext,
6555    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6556        self.visible_worktrees(cx).flat_map(move |worktree| {
6557            let worktree = worktree.read(cx);
6558            let worktree_id = worktree.id();
6559            worktree
6560                .diagnostic_summaries()
6561                .map(move |(path, server_id, summary)| {
6562                    (ProjectPath { worktree_id, path }, server_id, summary)
6563                })
6564        })
6565    }
6566
6567    pub fn disk_based_diagnostics_started(
6568        &mut self,
6569        language_server_id: LanguageServerId,
6570        cx: &mut ModelContext<Self>,
6571    ) {
6572        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6573    }
6574
6575    pub fn disk_based_diagnostics_finished(
6576        &mut self,
6577        language_server_id: LanguageServerId,
6578        cx: &mut ModelContext<Self>,
6579    ) {
6580        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6581    }
6582
6583    pub fn active_entry(&self) -> Option<ProjectEntryId> {
6584        self.active_entry
6585    }
6586
6587    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6588        self.worktree_for_id(path.worktree_id, cx)?
6589            .read(cx)
6590            .entry_for_path(&path.path)
6591            .cloned()
6592    }
6593
6594    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6595        let worktree = self.worktree_for_entry(entry_id, cx)?;
6596        let worktree = worktree.read(cx);
6597        let worktree_id = worktree.id();
6598        let path = worktree.entry_for_id(entry_id)?.path.clone();
6599        Some(ProjectPath { worktree_id, path })
6600    }
6601
6602    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6603        let workspace_root = self
6604            .worktree_for_id(project_path.worktree_id, cx)?
6605            .read(cx)
6606            .abs_path();
6607        let project_path = project_path.path.as_ref();
6608
6609        Some(if project_path == Path::new("") {
6610            workspace_root.to_path_buf()
6611        } else {
6612            workspace_root.join(project_path)
6613        })
6614    }
6615
6616    // RPC message handlers
6617
6618    async fn handle_unshare_project(
6619        this: ModelHandle<Self>,
6620        _: TypedEnvelope<proto::UnshareProject>,
6621        _: Arc<Client>,
6622        mut cx: AsyncAppContext,
6623    ) -> Result<()> {
6624        this.update(&mut cx, |this, cx| {
6625            if this.is_local() {
6626                this.unshare(cx)?;
6627            } else {
6628                this.disconnected_from_host(cx);
6629            }
6630            Ok(())
6631        })
6632    }
6633
6634    async fn handle_add_collaborator(
6635        this: ModelHandle<Self>,
6636        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6637        _: Arc<Client>,
6638        mut cx: AsyncAppContext,
6639    ) -> Result<()> {
6640        let collaborator = envelope
6641            .payload
6642            .collaborator
6643            .take()
6644            .ok_or_else(|| anyhow!("empty collaborator"))?;
6645
6646        let collaborator = Collaborator::from_proto(collaborator)?;
6647        this.update(&mut cx, |this, cx| {
6648            this.shared_buffers.remove(&collaborator.peer_id);
6649            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6650            this.collaborators
6651                .insert(collaborator.peer_id, collaborator);
6652            cx.notify();
6653        });
6654
6655        Ok(())
6656    }
6657
6658    async fn handle_update_project_collaborator(
6659        this: ModelHandle<Self>,
6660        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6661        _: Arc<Client>,
6662        mut cx: AsyncAppContext,
6663    ) -> Result<()> {
6664        let old_peer_id = envelope
6665            .payload
6666            .old_peer_id
6667            .ok_or_else(|| anyhow!("missing old peer id"))?;
6668        let new_peer_id = envelope
6669            .payload
6670            .new_peer_id
6671            .ok_or_else(|| anyhow!("missing new peer id"))?;
6672        this.update(&mut cx, |this, cx| {
6673            let collaborator = this
6674                .collaborators
6675                .remove(&old_peer_id)
6676                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
6677            let is_host = collaborator.replica_id == 0;
6678            this.collaborators.insert(new_peer_id, collaborator);
6679
6680            let buffers = this.shared_buffers.remove(&old_peer_id);
6681            log::info!(
6682                "peer {} became {}. moving buffers {:?}",
6683                old_peer_id,
6684                new_peer_id,
6685                &buffers
6686            );
6687            if let Some(buffers) = buffers {
6688                this.shared_buffers.insert(new_peer_id, buffers);
6689            }
6690
6691            if is_host {
6692                this.opened_buffers
6693                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
6694                this.buffer_ordered_messages_tx
6695                    .unbounded_send(BufferOrderedMessage::Resync)
6696                    .unwrap();
6697            }
6698
6699            cx.emit(Event::CollaboratorUpdated {
6700                old_peer_id,
6701                new_peer_id,
6702            });
6703            cx.notify();
6704            Ok(())
6705        })
6706    }
6707
6708    async fn handle_remove_collaborator(
6709        this: ModelHandle<Self>,
6710        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
6711        _: Arc<Client>,
6712        mut cx: AsyncAppContext,
6713    ) -> Result<()> {
6714        this.update(&mut cx, |this, cx| {
6715            let peer_id = envelope
6716                .payload
6717                .peer_id
6718                .ok_or_else(|| anyhow!("invalid peer id"))?;
6719            let replica_id = this
6720                .collaborators
6721                .remove(&peer_id)
6722                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
6723                .replica_id;
6724            for buffer in this.opened_buffers.values() {
6725                if let Some(buffer) = buffer.upgrade(cx) {
6726                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
6727                }
6728            }
6729            this.shared_buffers.remove(&peer_id);
6730
6731            cx.emit(Event::CollaboratorLeft(peer_id));
6732            cx.notify();
6733            Ok(())
6734        })
6735    }
6736
6737    async fn handle_update_project(
6738        this: ModelHandle<Self>,
6739        envelope: TypedEnvelope<proto::UpdateProject>,
6740        _: Arc<Client>,
6741        mut cx: AsyncAppContext,
6742    ) -> Result<()> {
6743        this.update(&mut cx, |this, cx| {
6744            // Don't handle messages that were sent before the response to us joining the project
6745            if envelope.message_id > this.join_project_response_message_id {
6746                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
6747            }
6748            Ok(())
6749        })
6750    }
6751
6752    async fn handle_update_worktree(
6753        this: ModelHandle<Self>,
6754        envelope: TypedEnvelope<proto::UpdateWorktree>,
6755        _: Arc<Client>,
6756        mut cx: AsyncAppContext,
6757    ) -> Result<()> {
6758        this.update(&mut cx, |this, cx| {
6759            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6760            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6761                worktree.update(cx, |worktree, _| {
6762                    let worktree = worktree.as_remote_mut().unwrap();
6763                    worktree.update_from_remote(envelope.payload);
6764                });
6765            }
6766            Ok(())
6767        })
6768    }
6769
6770    async fn handle_update_worktree_settings(
6771        this: ModelHandle<Self>,
6772        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6773        _: Arc<Client>,
6774        mut cx: AsyncAppContext,
6775    ) -> Result<()> {
6776        this.update(&mut cx, |this, cx| {
6777            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6778            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6779                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6780                    store
6781                        .set_local_settings(
6782                            worktree.id(),
6783                            PathBuf::from(&envelope.payload.path).into(),
6784                            envelope.payload.content.as_ref().map(String::as_str),
6785                            cx,
6786                        )
6787                        .log_err();
6788                });
6789            }
6790            Ok(())
6791        })
6792    }
6793
6794    async fn handle_create_project_entry(
6795        this: ModelHandle<Self>,
6796        envelope: TypedEnvelope<proto::CreateProjectEntry>,
6797        _: Arc<Client>,
6798        mut cx: AsyncAppContext,
6799    ) -> Result<proto::ProjectEntryResponse> {
6800        let worktree = this.update(&mut cx, |this, cx| {
6801            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6802            this.worktree_for_id(worktree_id, cx)
6803                .ok_or_else(|| anyhow!("worktree not found"))
6804        })?;
6805        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6806        let entry = worktree
6807            .update(&mut cx, |worktree, cx| {
6808                let worktree = worktree.as_local_mut().unwrap();
6809                let path = PathBuf::from(envelope.payload.path);
6810                worktree.create_entry(path, envelope.payload.is_directory, cx)
6811            })
6812            .await?;
6813        Ok(proto::ProjectEntryResponse {
6814            entry: Some((&entry).into()),
6815            worktree_scan_id: worktree_scan_id as u64,
6816        })
6817    }
6818
6819    async fn handle_rename_project_entry(
6820        this: ModelHandle<Self>,
6821        envelope: TypedEnvelope<proto::RenameProjectEntry>,
6822        _: Arc<Client>,
6823        mut cx: AsyncAppContext,
6824    ) -> Result<proto::ProjectEntryResponse> {
6825        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6826        let worktree = this.read_with(&cx, |this, cx| {
6827            this.worktree_for_entry(entry_id, cx)
6828                .ok_or_else(|| anyhow!("worktree not found"))
6829        })?;
6830        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6831        let entry = worktree
6832            .update(&mut cx, |worktree, cx| {
6833                let new_path = PathBuf::from(envelope.payload.new_path);
6834                worktree
6835                    .as_local_mut()
6836                    .unwrap()
6837                    .rename_entry(entry_id, new_path, cx)
6838                    .ok_or_else(|| anyhow!("invalid entry"))
6839            })?
6840            .await?;
6841        Ok(proto::ProjectEntryResponse {
6842            entry: Some((&entry).into()),
6843            worktree_scan_id: worktree_scan_id as u64,
6844        })
6845    }
6846
6847    async fn handle_copy_project_entry(
6848        this: ModelHandle<Self>,
6849        envelope: TypedEnvelope<proto::CopyProjectEntry>,
6850        _: Arc<Client>,
6851        mut cx: AsyncAppContext,
6852    ) -> Result<proto::ProjectEntryResponse> {
6853        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6854        let worktree = this.read_with(&cx, |this, cx| {
6855            this.worktree_for_entry(entry_id, cx)
6856                .ok_or_else(|| anyhow!("worktree not found"))
6857        })?;
6858        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6859        let entry = worktree
6860            .update(&mut cx, |worktree, cx| {
6861                let new_path = PathBuf::from(envelope.payload.new_path);
6862                worktree
6863                    .as_local_mut()
6864                    .unwrap()
6865                    .copy_entry(entry_id, new_path, cx)
6866                    .ok_or_else(|| anyhow!("invalid entry"))
6867            })?
6868            .await?;
6869        Ok(proto::ProjectEntryResponse {
6870            entry: Some((&entry).into()),
6871            worktree_scan_id: worktree_scan_id as u64,
6872        })
6873    }
6874
6875    async fn handle_delete_project_entry(
6876        this: ModelHandle<Self>,
6877        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6878        _: Arc<Client>,
6879        mut cx: AsyncAppContext,
6880    ) -> Result<proto::ProjectEntryResponse> {
6881        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6882
6883        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
6884
6885        let worktree = this.read_with(&cx, |this, cx| {
6886            this.worktree_for_entry(entry_id, cx)
6887                .ok_or_else(|| anyhow!("worktree not found"))
6888        })?;
6889        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6890        worktree
6891            .update(&mut cx, |worktree, cx| {
6892                worktree
6893                    .as_local_mut()
6894                    .unwrap()
6895                    .delete_entry(entry_id, cx)
6896                    .ok_or_else(|| anyhow!("invalid entry"))
6897            })?
6898            .await?;
6899        Ok(proto::ProjectEntryResponse {
6900            entry: None,
6901            worktree_scan_id: worktree_scan_id as u64,
6902        })
6903    }
6904
6905    async fn handle_expand_project_entry(
6906        this: ModelHandle<Self>,
6907        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
6908        _: Arc<Client>,
6909        mut cx: AsyncAppContext,
6910    ) -> Result<proto::ExpandProjectEntryResponse> {
6911        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6912        let worktree = this
6913            .read_with(&cx, |this, cx| this.worktree_for_entry(entry_id, cx))
6914            .ok_or_else(|| anyhow!("invalid request"))?;
6915        worktree
6916            .update(&mut cx, |worktree, cx| {
6917                worktree
6918                    .as_local_mut()
6919                    .unwrap()
6920                    .expand_entry(entry_id, cx)
6921                    .ok_or_else(|| anyhow!("invalid entry"))
6922            })?
6923            .await?;
6924        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id()) as u64;
6925        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
6926    }
6927
6928    async fn handle_update_diagnostic_summary(
6929        this: ModelHandle<Self>,
6930        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
6931        _: Arc<Client>,
6932        mut cx: AsyncAppContext,
6933    ) -> Result<()> {
6934        this.update(&mut cx, |this, cx| {
6935            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6936            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6937                if let Some(summary) = envelope.payload.summary {
6938                    let project_path = ProjectPath {
6939                        worktree_id,
6940                        path: Path::new(&summary.path).into(),
6941                    };
6942                    worktree.update(cx, |worktree, _| {
6943                        worktree
6944                            .as_remote_mut()
6945                            .unwrap()
6946                            .update_diagnostic_summary(project_path.path.clone(), &summary);
6947                    });
6948                    cx.emit(Event::DiagnosticsUpdated {
6949                        language_server_id: LanguageServerId(summary.language_server_id as usize),
6950                        path: project_path,
6951                    });
6952                }
6953            }
6954            Ok(())
6955        })
6956    }
6957
6958    async fn handle_start_language_server(
6959        this: ModelHandle<Self>,
6960        envelope: TypedEnvelope<proto::StartLanguageServer>,
6961        _: Arc<Client>,
6962        mut cx: AsyncAppContext,
6963    ) -> Result<()> {
6964        let server = envelope
6965            .payload
6966            .server
6967            .ok_or_else(|| anyhow!("invalid server"))?;
6968        this.update(&mut cx, |this, cx| {
6969            this.language_server_statuses.insert(
6970                LanguageServerId(server.id as usize),
6971                LanguageServerStatus {
6972                    name: server.name,
6973                    pending_work: Default::default(),
6974                    has_pending_diagnostic_updates: false,
6975                    progress_tokens: Default::default(),
6976                },
6977            );
6978            cx.notify();
6979        });
6980        Ok(())
6981    }
6982
6983    async fn handle_update_language_server(
6984        this: ModelHandle<Self>,
6985        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
6986        _: Arc<Client>,
6987        mut cx: AsyncAppContext,
6988    ) -> Result<()> {
6989        this.update(&mut cx, |this, cx| {
6990            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
6991
6992            match envelope
6993                .payload
6994                .variant
6995                .ok_or_else(|| anyhow!("invalid variant"))?
6996            {
6997                proto::update_language_server::Variant::WorkStart(payload) => {
6998                    this.on_lsp_work_start(
6999                        language_server_id,
7000                        payload.token,
7001                        LanguageServerProgress {
7002                            message: payload.message,
7003                            percentage: payload.percentage.map(|p| p as usize),
7004                            last_update_at: Instant::now(),
7005                        },
7006                        cx,
7007                    );
7008                }
7009
7010                proto::update_language_server::Variant::WorkProgress(payload) => {
7011                    this.on_lsp_work_progress(
7012                        language_server_id,
7013                        payload.token,
7014                        LanguageServerProgress {
7015                            message: payload.message,
7016                            percentage: payload.percentage.map(|p| p as usize),
7017                            last_update_at: Instant::now(),
7018                        },
7019                        cx,
7020                    );
7021                }
7022
7023                proto::update_language_server::Variant::WorkEnd(payload) => {
7024                    this.on_lsp_work_end(language_server_id, payload.token, cx);
7025                }
7026
7027                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7028                    this.disk_based_diagnostics_started(language_server_id, cx);
7029                }
7030
7031                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7032                    this.disk_based_diagnostics_finished(language_server_id, cx)
7033                }
7034            }
7035
7036            Ok(())
7037        })
7038    }
7039
7040    async fn handle_update_buffer(
7041        this: ModelHandle<Self>,
7042        envelope: TypedEnvelope<proto::UpdateBuffer>,
7043        _: Arc<Client>,
7044        mut cx: AsyncAppContext,
7045    ) -> Result<proto::Ack> {
7046        this.update(&mut cx, |this, cx| {
7047            let payload = envelope.payload.clone();
7048            let buffer_id = payload.buffer_id;
7049            let ops = payload
7050                .operations
7051                .into_iter()
7052                .map(language::proto::deserialize_operation)
7053                .collect::<Result<Vec<_>, _>>()?;
7054            let is_remote = this.is_remote();
7055            match this.opened_buffers.entry(buffer_id) {
7056                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7057                    OpenBuffer::Strong(buffer) => {
7058                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7059                    }
7060                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7061                    OpenBuffer::Weak(_) => {}
7062                },
7063                hash_map::Entry::Vacant(e) => {
7064                    assert!(
7065                        is_remote,
7066                        "received buffer update from {:?}",
7067                        envelope.original_sender_id
7068                    );
7069                    e.insert(OpenBuffer::Operations(ops));
7070                }
7071            }
7072            Ok(proto::Ack {})
7073        })
7074    }
7075
7076    async fn handle_create_buffer_for_peer(
7077        this: ModelHandle<Self>,
7078        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7079        _: Arc<Client>,
7080        mut cx: AsyncAppContext,
7081    ) -> Result<()> {
7082        this.update(&mut cx, |this, cx| {
7083            match envelope
7084                .payload
7085                .variant
7086                .ok_or_else(|| anyhow!("missing variant"))?
7087            {
7088                proto::create_buffer_for_peer::Variant::State(mut state) => {
7089                    let mut buffer_file = None;
7090                    if let Some(file) = state.file.take() {
7091                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
7092                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7093                            anyhow!("no worktree found for id {}", file.worktree_id)
7094                        })?;
7095                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7096                            as Arc<dyn language::File>);
7097                    }
7098
7099                    let buffer_id = state.id;
7100                    let buffer = cx.add_model(|_| {
7101                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
7102                    });
7103                    this.incomplete_remote_buffers
7104                        .insert(buffer_id, Some(buffer));
7105                }
7106                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7107                    let buffer = this
7108                        .incomplete_remote_buffers
7109                        .get(&chunk.buffer_id)
7110                        .cloned()
7111                        .flatten()
7112                        .ok_or_else(|| {
7113                            anyhow!(
7114                                "received chunk for buffer {} without initial state",
7115                                chunk.buffer_id
7116                            )
7117                        })?;
7118                    let operations = chunk
7119                        .operations
7120                        .into_iter()
7121                        .map(language::proto::deserialize_operation)
7122                        .collect::<Result<Vec<_>>>()?;
7123                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7124
7125                    if chunk.is_last {
7126                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
7127                        this.register_buffer(&buffer, cx)?;
7128                    }
7129                }
7130            }
7131
7132            Ok(())
7133        })
7134    }
7135
7136    async fn handle_update_diff_base(
7137        this: ModelHandle<Self>,
7138        envelope: TypedEnvelope<proto::UpdateDiffBase>,
7139        _: Arc<Client>,
7140        mut cx: AsyncAppContext,
7141    ) -> Result<()> {
7142        this.update(&mut cx, |this, cx| {
7143            let buffer_id = envelope.payload.buffer_id;
7144            let diff_base = envelope.payload.diff_base;
7145            if let Some(buffer) = this
7146                .opened_buffers
7147                .get_mut(&buffer_id)
7148                .and_then(|b| b.upgrade(cx))
7149                .or_else(|| {
7150                    this.incomplete_remote_buffers
7151                        .get(&buffer_id)
7152                        .cloned()
7153                        .flatten()
7154                })
7155            {
7156                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7157            }
7158            Ok(())
7159        })
7160    }
7161
7162    async fn handle_update_buffer_file(
7163        this: ModelHandle<Self>,
7164        envelope: TypedEnvelope<proto::UpdateBufferFile>,
7165        _: Arc<Client>,
7166        mut cx: AsyncAppContext,
7167    ) -> Result<()> {
7168        let buffer_id = envelope.payload.buffer_id;
7169
7170        this.update(&mut cx, |this, cx| {
7171            let payload = envelope.payload.clone();
7172            if let Some(buffer) = this
7173                .opened_buffers
7174                .get(&buffer_id)
7175                .and_then(|b| b.upgrade(cx))
7176                .or_else(|| {
7177                    this.incomplete_remote_buffers
7178                        .get(&buffer_id)
7179                        .cloned()
7180                        .flatten()
7181                })
7182            {
7183                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7184                let worktree = this
7185                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7186                    .ok_or_else(|| anyhow!("no such worktree"))?;
7187                let file = File::from_proto(file, worktree, cx)?;
7188                buffer.update(cx, |buffer, cx| {
7189                    buffer.file_updated(Arc::new(file), cx).detach();
7190                });
7191                this.detect_language_for_buffer(&buffer, cx);
7192            }
7193            Ok(())
7194        })
7195    }
7196
7197    async fn handle_save_buffer(
7198        this: ModelHandle<Self>,
7199        envelope: TypedEnvelope<proto::SaveBuffer>,
7200        _: Arc<Client>,
7201        mut cx: AsyncAppContext,
7202    ) -> Result<proto::BufferSaved> {
7203        let buffer_id = envelope.payload.buffer_id;
7204        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
7205            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7206            let buffer = this
7207                .opened_buffers
7208                .get(&buffer_id)
7209                .and_then(|buffer| buffer.upgrade(cx))
7210                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7211            anyhow::Ok((project_id, buffer))
7212        })?;
7213        buffer
7214            .update(&mut cx, |buffer, _| {
7215                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7216            })
7217            .await?;
7218        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
7219
7220        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
7221            .await?;
7222        Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
7223            project_id,
7224            buffer_id,
7225            version: serialize_version(buffer.saved_version()),
7226            mtime: Some(buffer.saved_mtime().into()),
7227            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7228        }))
7229    }
7230
7231    async fn handle_reload_buffers(
7232        this: ModelHandle<Self>,
7233        envelope: TypedEnvelope<proto::ReloadBuffers>,
7234        _: Arc<Client>,
7235        mut cx: AsyncAppContext,
7236    ) -> Result<proto::ReloadBuffersResponse> {
7237        let sender_id = envelope.original_sender_id()?;
7238        let reload = this.update(&mut cx, |this, cx| {
7239            let mut buffers = HashSet::default();
7240            for buffer_id in &envelope.payload.buffer_ids {
7241                buffers.insert(
7242                    this.opened_buffers
7243                        .get(buffer_id)
7244                        .and_then(|buffer| buffer.upgrade(cx))
7245                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7246                );
7247            }
7248            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7249        })?;
7250
7251        let project_transaction = reload.await?;
7252        let project_transaction = this.update(&mut cx, |this, cx| {
7253            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7254        });
7255        Ok(proto::ReloadBuffersResponse {
7256            transaction: Some(project_transaction),
7257        })
7258    }
7259
7260    async fn handle_synchronize_buffers(
7261        this: ModelHandle<Self>,
7262        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7263        _: Arc<Client>,
7264        mut cx: AsyncAppContext,
7265    ) -> Result<proto::SynchronizeBuffersResponse> {
7266        let project_id = envelope.payload.project_id;
7267        let mut response = proto::SynchronizeBuffersResponse {
7268            buffers: Default::default(),
7269        };
7270
7271        this.update(&mut cx, |this, cx| {
7272            let Some(guest_id) = envelope.original_sender_id else {
7273                error!("missing original_sender_id on SynchronizeBuffers request");
7274                return;
7275            };
7276
7277            this.shared_buffers.entry(guest_id).or_default().clear();
7278            for buffer in envelope.payload.buffers {
7279                let buffer_id = buffer.id;
7280                let remote_version = language::proto::deserialize_version(&buffer.version);
7281                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7282                    this.shared_buffers
7283                        .entry(guest_id)
7284                        .or_default()
7285                        .insert(buffer_id);
7286
7287                    let buffer = buffer.read(cx);
7288                    response.buffers.push(proto::BufferVersion {
7289                        id: buffer_id,
7290                        version: language::proto::serialize_version(&buffer.version),
7291                    });
7292
7293                    let operations = buffer.serialize_ops(Some(remote_version), cx);
7294                    let client = this.client.clone();
7295                    if let Some(file) = buffer.file() {
7296                        client
7297                            .send(proto::UpdateBufferFile {
7298                                project_id,
7299                                buffer_id: buffer_id as u64,
7300                                file: Some(file.to_proto()),
7301                            })
7302                            .log_err();
7303                    }
7304
7305                    client
7306                        .send(proto::UpdateDiffBase {
7307                            project_id,
7308                            buffer_id: buffer_id as u64,
7309                            diff_base: buffer.diff_base().map(Into::into),
7310                        })
7311                        .log_err();
7312
7313                    client
7314                        .send(proto::BufferReloaded {
7315                            project_id,
7316                            buffer_id,
7317                            version: language::proto::serialize_version(buffer.saved_version()),
7318                            mtime: Some(buffer.saved_mtime().into()),
7319                            fingerprint: language::proto::serialize_fingerprint(
7320                                buffer.saved_version_fingerprint(),
7321                            ),
7322                            line_ending: language::proto::serialize_line_ending(
7323                                buffer.line_ending(),
7324                            ) as i32,
7325                        })
7326                        .log_err();
7327
7328                    cx.background()
7329                        .spawn(
7330                            async move {
7331                                let operations = operations.await;
7332                                for chunk in split_operations(operations) {
7333                                    client
7334                                        .request(proto::UpdateBuffer {
7335                                            project_id,
7336                                            buffer_id,
7337                                            operations: chunk,
7338                                        })
7339                                        .await?;
7340                                }
7341                                anyhow::Ok(())
7342                            }
7343                            .log_err(),
7344                        )
7345                        .detach();
7346                }
7347            }
7348        });
7349
7350        Ok(response)
7351    }
7352
7353    async fn handle_format_buffers(
7354        this: ModelHandle<Self>,
7355        envelope: TypedEnvelope<proto::FormatBuffers>,
7356        _: Arc<Client>,
7357        mut cx: AsyncAppContext,
7358    ) -> Result<proto::FormatBuffersResponse> {
7359        let sender_id = envelope.original_sender_id()?;
7360        let format = this.update(&mut cx, |this, cx| {
7361            let mut buffers = HashSet::default();
7362            for buffer_id in &envelope.payload.buffer_ids {
7363                buffers.insert(
7364                    this.opened_buffers
7365                        .get(buffer_id)
7366                        .and_then(|buffer| buffer.upgrade(cx))
7367                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7368                );
7369            }
7370            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7371            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7372        })?;
7373
7374        let project_transaction = format.await?;
7375        let project_transaction = this.update(&mut cx, |this, cx| {
7376            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7377        });
7378        Ok(proto::FormatBuffersResponse {
7379            transaction: Some(project_transaction),
7380        })
7381    }
7382
7383    async fn handle_apply_additional_edits_for_completion(
7384        this: ModelHandle<Self>,
7385        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7386        _: Arc<Client>,
7387        mut cx: AsyncAppContext,
7388    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7389        let (buffer, completion) = this.update(&mut cx, |this, cx| {
7390            let buffer = this
7391                .opened_buffers
7392                .get(&envelope.payload.buffer_id)
7393                .and_then(|buffer| buffer.upgrade(cx))
7394                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7395            let language = buffer.read(cx).language();
7396            let completion = language::proto::deserialize_completion(
7397                envelope
7398                    .payload
7399                    .completion
7400                    .ok_or_else(|| anyhow!("invalid completion"))?,
7401                language.cloned(),
7402            );
7403            Ok::<_, anyhow::Error>((buffer, completion))
7404        })?;
7405
7406        let completion = completion.await?;
7407
7408        let apply_additional_edits = this.update(&mut cx, |this, cx| {
7409            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7410        });
7411
7412        Ok(proto::ApplyCompletionAdditionalEditsResponse {
7413            transaction: apply_additional_edits
7414                .await?
7415                .as_ref()
7416                .map(language::proto::serialize_transaction),
7417        })
7418    }
7419
7420    async fn handle_resolve_completion_documentation(
7421        this: ModelHandle<Self>,
7422        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
7423        _: Arc<Client>,
7424        mut cx: AsyncAppContext,
7425    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
7426        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
7427
7428        let completion = this
7429            .read_with(&mut cx, |this, _| {
7430                let id = LanguageServerId(envelope.payload.language_server_id as usize);
7431                let Some(server) = this.language_server_for_id(id) else {
7432                    return Err(anyhow!("No language server {id}"));
7433                };
7434
7435                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
7436            })?
7437            .await?;
7438
7439        let mut is_markdown = false;
7440        let text = match completion.documentation {
7441            Some(lsp::Documentation::String(text)) => text,
7442
7443            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
7444                is_markdown = kind == lsp::MarkupKind::Markdown;
7445                value
7446            }
7447
7448            _ => String::new(),
7449        };
7450
7451        Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
7452    }
7453
7454    async fn handle_apply_code_action(
7455        this: ModelHandle<Self>,
7456        envelope: TypedEnvelope<proto::ApplyCodeAction>,
7457        _: Arc<Client>,
7458        mut cx: AsyncAppContext,
7459    ) -> Result<proto::ApplyCodeActionResponse> {
7460        let sender_id = envelope.original_sender_id()?;
7461        let action = language::proto::deserialize_code_action(
7462            envelope
7463                .payload
7464                .action
7465                .ok_or_else(|| anyhow!("invalid action"))?,
7466        )?;
7467        let apply_code_action = this.update(&mut cx, |this, cx| {
7468            let buffer = this
7469                .opened_buffers
7470                .get(&envelope.payload.buffer_id)
7471                .and_then(|buffer| buffer.upgrade(cx))
7472                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7473            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7474        })?;
7475
7476        let project_transaction = apply_code_action.await?;
7477        let project_transaction = this.update(&mut cx, |this, cx| {
7478            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7479        });
7480        Ok(proto::ApplyCodeActionResponse {
7481            transaction: Some(project_transaction),
7482        })
7483    }
7484
7485    async fn handle_on_type_formatting(
7486        this: ModelHandle<Self>,
7487        envelope: TypedEnvelope<proto::OnTypeFormatting>,
7488        _: Arc<Client>,
7489        mut cx: AsyncAppContext,
7490    ) -> Result<proto::OnTypeFormattingResponse> {
7491        let on_type_formatting = this.update(&mut cx, |this, cx| {
7492            let buffer = this
7493                .opened_buffers
7494                .get(&envelope.payload.buffer_id)
7495                .and_then(|buffer| buffer.upgrade(cx))
7496                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7497            let position = envelope
7498                .payload
7499                .position
7500                .and_then(deserialize_anchor)
7501                .ok_or_else(|| anyhow!("invalid position"))?;
7502            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7503                buffer,
7504                position,
7505                envelope.payload.trigger.clone(),
7506                cx,
7507            ))
7508        })?;
7509
7510        let transaction = on_type_formatting
7511            .await?
7512            .as_ref()
7513            .map(language::proto::serialize_transaction);
7514        Ok(proto::OnTypeFormattingResponse { transaction })
7515    }
7516
7517    async fn handle_inlay_hints(
7518        this: ModelHandle<Self>,
7519        envelope: TypedEnvelope<proto::InlayHints>,
7520        _: Arc<Client>,
7521        mut cx: AsyncAppContext,
7522    ) -> Result<proto::InlayHintsResponse> {
7523        let sender_id = envelope.original_sender_id()?;
7524        let buffer = this.update(&mut cx, |this, cx| {
7525            this.opened_buffers
7526                .get(&envelope.payload.buffer_id)
7527                .and_then(|buffer| buffer.upgrade(cx))
7528                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7529        })?;
7530        let buffer_version = deserialize_version(&envelope.payload.version);
7531
7532        buffer
7533            .update(&mut cx, |buffer, _| {
7534                buffer.wait_for_version(buffer_version.clone())
7535            })
7536            .await
7537            .with_context(|| {
7538                format!(
7539                    "waiting for version {:?} for buffer {}",
7540                    buffer_version,
7541                    buffer.id()
7542                )
7543            })?;
7544
7545        let start = envelope
7546            .payload
7547            .start
7548            .and_then(deserialize_anchor)
7549            .context("missing range start")?;
7550        let end = envelope
7551            .payload
7552            .end
7553            .and_then(deserialize_anchor)
7554            .context("missing range end")?;
7555        let buffer_hints = this
7556            .update(&mut cx, |project, cx| {
7557                project.inlay_hints(buffer, start..end, cx)
7558            })
7559            .await
7560            .context("inlay hints fetch")?;
7561
7562        Ok(this.update(&mut cx, |project, cx| {
7563            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7564        }))
7565    }
7566
7567    async fn handle_resolve_inlay_hint(
7568        this: ModelHandle<Self>,
7569        envelope: TypedEnvelope<proto::ResolveInlayHint>,
7570        _: Arc<Client>,
7571        mut cx: AsyncAppContext,
7572    ) -> Result<proto::ResolveInlayHintResponse> {
7573        let proto_hint = envelope
7574            .payload
7575            .hint
7576            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7577        let hint = InlayHints::proto_to_project_hint(proto_hint)
7578            .context("resolved proto inlay hint conversion")?;
7579        let buffer = this.update(&mut cx, |this, cx| {
7580            this.opened_buffers
7581                .get(&envelope.payload.buffer_id)
7582                .and_then(|buffer| buffer.upgrade(cx))
7583                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7584        })?;
7585        let response_hint = this
7586            .update(&mut cx, |project, cx| {
7587                project.resolve_inlay_hint(
7588                    hint,
7589                    buffer,
7590                    LanguageServerId(envelope.payload.language_server_id as usize),
7591                    cx,
7592                )
7593            })
7594            .await
7595            .context("inlay hints fetch")?;
7596        Ok(proto::ResolveInlayHintResponse {
7597            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7598        })
7599    }
7600
7601    async fn handle_refresh_inlay_hints(
7602        this: ModelHandle<Self>,
7603        _: TypedEnvelope<proto::RefreshInlayHints>,
7604        _: Arc<Client>,
7605        mut cx: AsyncAppContext,
7606    ) -> Result<proto::Ack> {
7607        this.update(&mut cx, |_, cx| {
7608            cx.emit(Event::RefreshInlayHints);
7609        });
7610        Ok(proto::Ack {})
7611    }
7612
7613    async fn handle_lsp_command<T: LspCommand>(
7614        this: ModelHandle<Self>,
7615        envelope: TypedEnvelope<T::ProtoRequest>,
7616        _: Arc<Client>,
7617        mut cx: AsyncAppContext,
7618    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7619    where
7620        <T::LspRequest as lsp::request::Request>::Result: Send,
7621    {
7622        let sender_id = envelope.original_sender_id()?;
7623        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
7624        let buffer_handle = this.read_with(&cx, |this, _| {
7625            this.opened_buffers
7626                .get(&buffer_id)
7627                .and_then(|buffer| buffer.upgrade(&cx))
7628                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7629        })?;
7630        let request = T::from_proto(
7631            envelope.payload,
7632            this.clone(),
7633            buffer_handle.clone(),
7634            cx.clone(),
7635        )
7636        .await?;
7637        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
7638        let response = this
7639            .update(&mut cx, |this, cx| {
7640                this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
7641            })
7642            .await?;
7643        this.update(&mut cx, |this, cx| {
7644            Ok(T::response_to_proto(
7645                response,
7646                this,
7647                sender_id,
7648                &buffer_version,
7649                cx,
7650            ))
7651        })
7652    }
7653
7654    async fn handle_get_project_symbols(
7655        this: ModelHandle<Self>,
7656        envelope: TypedEnvelope<proto::GetProjectSymbols>,
7657        _: Arc<Client>,
7658        mut cx: AsyncAppContext,
7659    ) -> Result<proto::GetProjectSymbolsResponse> {
7660        let symbols = this
7661            .update(&mut cx, |this, cx| {
7662                this.symbols(&envelope.payload.query, cx)
7663            })
7664            .await?;
7665
7666        Ok(proto::GetProjectSymbolsResponse {
7667            symbols: symbols.iter().map(serialize_symbol).collect(),
7668        })
7669    }
7670
7671    async fn handle_search_project(
7672        this: ModelHandle<Self>,
7673        envelope: TypedEnvelope<proto::SearchProject>,
7674        _: Arc<Client>,
7675        mut cx: AsyncAppContext,
7676    ) -> Result<proto::SearchProjectResponse> {
7677        let peer_id = envelope.original_sender_id()?;
7678        let query = SearchQuery::from_proto(envelope.payload)?;
7679        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx));
7680
7681        cx.spawn(|mut cx| async move {
7682            let mut locations = Vec::new();
7683            while let Some((buffer, ranges)) = result.next().await {
7684                for range in ranges {
7685                    let start = serialize_anchor(&range.start);
7686                    let end = serialize_anchor(&range.end);
7687                    let buffer_id = this.update(&mut cx, |this, cx| {
7688                        this.create_buffer_for_peer(&buffer, peer_id, cx)
7689                    });
7690                    locations.push(proto::Location {
7691                        buffer_id,
7692                        start: Some(start),
7693                        end: Some(end),
7694                    });
7695                }
7696            }
7697            Ok(proto::SearchProjectResponse { locations })
7698        })
7699        .await
7700    }
7701
7702    async fn handle_open_buffer_for_symbol(
7703        this: ModelHandle<Self>,
7704        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7705        _: Arc<Client>,
7706        mut cx: AsyncAppContext,
7707    ) -> Result<proto::OpenBufferForSymbolResponse> {
7708        let peer_id = envelope.original_sender_id()?;
7709        let symbol = envelope
7710            .payload
7711            .symbol
7712            .ok_or_else(|| anyhow!("invalid symbol"))?;
7713        let symbol = this
7714            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
7715            .await?;
7716        let symbol = this.read_with(&cx, |this, _| {
7717            let signature = this.symbol_signature(&symbol.path);
7718            if signature == symbol.signature {
7719                Ok(symbol)
7720            } else {
7721                Err(anyhow!("invalid symbol signature"))
7722            }
7723        })?;
7724        let buffer = this
7725            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
7726            .await?;
7727
7728        Ok(proto::OpenBufferForSymbolResponse {
7729            buffer_id: this.update(&mut cx, |this, cx| {
7730                this.create_buffer_for_peer(&buffer, peer_id, cx)
7731            }),
7732        })
7733    }
7734
7735    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7736        let mut hasher = Sha256::new();
7737        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7738        hasher.update(project_path.path.to_string_lossy().as_bytes());
7739        hasher.update(self.nonce.to_be_bytes());
7740        hasher.finalize().as_slice().try_into().unwrap()
7741    }
7742
7743    async fn handle_open_buffer_by_id(
7744        this: ModelHandle<Self>,
7745        envelope: TypedEnvelope<proto::OpenBufferById>,
7746        _: Arc<Client>,
7747        mut cx: AsyncAppContext,
7748    ) -> Result<proto::OpenBufferResponse> {
7749        let peer_id = envelope.original_sender_id()?;
7750        let buffer = this
7751            .update(&mut cx, |this, cx| {
7752                this.open_buffer_by_id(envelope.payload.id, cx)
7753            })
7754            .await?;
7755        this.update(&mut cx, |this, cx| {
7756            Ok(proto::OpenBufferResponse {
7757                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7758            })
7759        })
7760    }
7761
7762    async fn handle_open_buffer_by_path(
7763        this: ModelHandle<Self>,
7764        envelope: TypedEnvelope<proto::OpenBufferByPath>,
7765        _: Arc<Client>,
7766        mut cx: AsyncAppContext,
7767    ) -> Result<proto::OpenBufferResponse> {
7768        let peer_id = envelope.original_sender_id()?;
7769        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7770        let open_buffer = this.update(&mut cx, |this, cx| {
7771            this.open_buffer(
7772                ProjectPath {
7773                    worktree_id,
7774                    path: PathBuf::from(envelope.payload.path).into(),
7775                },
7776                cx,
7777            )
7778        });
7779
7780        let buffer = open_buffer.await?;
7781        this.update(&mut cx, |this, cx| {
7782            Ok(proto::OpenBufferResponse {
7783                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7784            })
7785        })
7786    }
7787
7788    fn serialize_project_transaction_for_peer(
7789        &mut self,
7790        project_transaction: ProjectTransaction,
7791        peer_id: proto::PeerId,
7792        cx: &mut AppContext,
7793    ) -> proto::ProjectTransaction {
7794        let mut serialized_transaction = proto::ProjectTransaction {
7795            buffer_ids: Default::default(),
7796            transactions: Default::default(),
7797        };
7798        for (buffer, transaction) in project_transaction.0 {
7799            serialized_transaction
7800                .buffer_ids
7801                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
7802            serialized_transaction
7803                .transactions
7804                .push(language::proto::serialize_transaction(&transaction));
7805        }
7806        serialized_transaction
7807    }
7808
7809    fn deserialize_project_transaction(
7810        &mut self,
7811        message: proto::ProjectTransaction,
7812        push_to_history: bool,
7813        cx: &mut ModelContext<Self>,
7814    ) -> Task<Result<ProjectTransaction>> {
7815        cx.spawn(|this, mut cx| async move {
7816            let mut project_transaction = ProjectTransaction::default();
7817            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
7818            {
7819                let buffer = this
7820                    .update(&mut cx, |this, cx| {
7821                        this.wait_for_remote_buffer(buffer_id, cx)
7822                    })
7823                    .await?;
7824                let transaction = language::proto::deserialize_transaction(transaction)?;
7825                project_transaction.0.insert(buffer, transaction);
7826            }
7827
7828            for (buffer, transaction) in &project_transaction.0 {
7829                buffer
7830                    .update(&mut cx, |buffer, _| {
7831                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7832                    })
7833                    .await?;
7834
7835                if push_to_history {
7836                    buffer.update(&mut cx, |buffer, _| {
7837                        buffer.push_transaction(transaction.clone(), Instant::now());
7838                    });
7839                }
7840            }
7841
7842            Ok(project_transaction)
7843        })
7844    }
7845
7846    fn create_buffer_for_peer(
7847        &mut self,
7848        buffer: &ModelHandle<Buffer>,
7849        peer_id: proto::PeerId,
7850        cx: &mut AppContext,
7851    ) -> u64 {
7852        let buffer_id = buffer.read(cx).remote_id();
7853        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7854            updates_tx
7855                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7856                .ok();
7857        }
7858        buffer_id
7859    }
7860
7861    fn wait_for_remote_buffer(
7862        &mut self,
7863        id: u64,
7864        cx: &mut ModelContext<Self>,
7865    ) -> Task<Result<ModelHandle<Buffer>>> {
7866        let mut opened_buffer_rx = self.opened_buffer.1.clone();
7867
7868        cx.spawn_weak(|this, mut cx| async move {
7869            let buffer = loop {
7870                let Some(this) = this.upgrade(&cx) else {
7871                    return Err(anyhow!("project dropped"));
7872                };
7873
7874                let buffer = this.read_with(&cx, |this, cx| {
7875                    this.opened_buffers
7876                        .get(&id)
7877                        .and_then(|buffer| buffer.upgrade(cx))
7878                });
7879
7880                if let Some(buffer) = buffer {
7881                    break buffer;
7882                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
7883                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
7884                }
7885
7886                this.update(&mut cx, |this, _| {
7887                    this.incomplete_remote_buffers.entry(id).or_default();
7888                });
7889                drop(this);
7890
7891                opened_buffer_rx
7892                    .next()
7893                    .await
7894                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7895            };
7896
7897            Ok(buffer)
7898        })
7899    }
7900
7901    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7902        let project_id = match self.client_state.as_ref() {
7903            Some(ProjectClientState::Remote {
7904                sharing_has_stopped,
7905                remote_id,
7906                ..
7907            }) => {
7908                if *sharing_has_stopped {
7909                    return Task::ready(Err(anyhow!(
7910                        "can't synchronize remote buffers on a readonly project"
7911                    )));
7912                } else {
7913                    *remote_id
7914                }
7915            }
7916            Some(ProjectClientState::Local { .. }) | None => {
7917                return Task::ready(Err(anyhow!(
7918                    "can't synchronize remote buffers on a local project"
7919                )))
7920            }
7921        };
7922
7923        let client = self.client.clone();
7924        cx.spawn(|this, cx| async move {
7925            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
7926                let buffers = this
7927                    .opened_buffers
7928                    .iter()
7929                    .filter_map(|(id, buffer)| {
7930                        let buffer = buffer.upgrade(cx)?;
7931                        Some(proto::BufferVersion {
7932                            id: *id,
7933                            version: language::proto::serialize_version(&buffer.read(cx).version),
7934                        })
7935                    })
7936                    .collect();
7937                let incomplete_buffer_ids = this
7938                    .incomplete_remote_buffers
7939                    .keys()
7940                    .copied()
7941                    .collect::<Vec<_>>();
7942
7943                (buffers, incomplete_buffer_ids)
7944            });
7945            let response = client
7946                .request(proto::SynchronizeBuffers {
7947                    project_id,
7948                    buffers,
7949                })
7950                .await?;
7951
7952            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
7953                let client = client.clone();
7954                let buffer_id = buffer.id;
7955                let remote_version = language::proto::deserialize_version(&buffer.version);
7956                this.read_with(&cx, |this, cx| {
7957                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7958                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
7959                        cx.background().spawn(async move {
7960                            let operations = operations.await;
7961                            for chunk in split_operations(operations) {
7962                                client
7963                                    .request(proto::UpdateBuffer {
7964                                        project_id,
7965                                        buffer_id,
7966                                        operations: chunk,
7967                                    })
7968                                    .await?;
7969                            }
7970                            anyhow::Ok(())
7971                        })
7972                    } else {
7973                        Task::ready(Ok(()))
7974                    }
7975                })
7976            });
7977
7978            // Any incomplete buffers have open requests waiting. Request that the host sends
7979            // creates these buffers for us again to unblock any waiting futures.
7980            for id in incomplete_buffer_ids {
7981                cx.background()
7982                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
7983                    .detach();
7984            }
7985
7986            futures::future::join_all(send_updates_for_buffers)
7987                .await
7988                .into_iter()
7989                .collect()
7990        })
7991    }
7992
7993    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
7994        self.worktrees(cx)
7995            .map(|worktree| {
7996                let worktree = worktree.read(cx);
7997                proto::WorktreeMetadata {
7998                    id: worktree.id().to_proto(),
7999                    root_name: worktree.root_name().into(),
8000                    visible: worktree.is_visible(),
8001                    abs_path: worktree.abs_path().to_string_lossy().into(),
8002                }
8003            })
8004            .collect()
8005    }
8006
8007    fn set_worktrees_from_proto(
8008        &mut self,
8009        worktrees: Vec<proto::WorktreeMetadata>,
8010        cx: &mut ModelContext<Project>,
8011    ) -> Result<()> {
8012        let replica_id = self.replica_id();
8013        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8014
8015        let mut old_worktrees_by_id = self
8016            .worktrees
8017            .drain(..)
8018            .filter_map(|worktree| {
8019                let worktree = worktree.upgrade(cx)?;
8020                Some((worktree.read(cx).id(), worktree))
8021            })
8022            .collect::<HashMap<_, _>>();
8023
8024        for worktree in worktrees {
8025            if let Some(old_worktree) =
8026                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8027            {
8028                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8029            } else {
8030                let worktree =
8031                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8032                let _ = self.add_worktree(&worktree, cx);
8033            }
8034        }
8035
8036        self.metadata_changed(cx);
8037        for id in old_worktrees_by_id.keys() {
8038            cx.emit(Event::WorktreeRemoved(*id));
8039        }
8040
8041        Ok(())
8042    }
8043
8044    fn set_collaborators_from_proto(
8045        &mut self,
8046        messages: Vec<proto::Collaborator>,
8047        cx: &mut ModelContext<Self>,
8048    ) -> Result<()> {
8049        let mut collaborators = HashMap::default();
8050        for message in messages {
8051            let collaborator = Collaborator::from_proto(message)?;
8052            collaborators.insert(collaborator.peer_id, collaborator);
8053        }
8054        for old_peer_id in self.collaborators.keys() {
8055            if !collaborators.contains_key(old_peer_id) {
8056                cx.emit(Event::CollaboratorLeft(*old_peer_id));
8057            }
8058        }
8059        self.collaborators = collaborators;
8060        Ok(())
8061    }
8062
8063    fn deserialize_symbol(
8064        &self,
8065        serialized_symbol: proto::Symbol,
8066    ) -> impl Future<Output = Result<Symbol>> {
8067        let languages = self.languages.clone();
8068        async move {
8069            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8070            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8071            let start = serialized_symbol
8072                .start
8073                .ok_or_else(|| anyhow!("invalid start"))?;
8074            let end = serialized_symbol
8075                .end
8076                .ok_or_else(|| anyhow!("invalid end"))?;
8077            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8078            let path = ProjectPath {
8079                worktree_id,
8080                path: PathBuf::from(serialized_symbol.path).into(),
8081            };
8082            let language = languages
8083                .language_for_file(&path.path, None)
8084                .await
8085                .log_err();
8086            Ok(Symbol {
8087                language_server_name: LanguageServerName(
8088                    serialized_symbol.language_server_name.into(),
8089                ),
8090                source_worktree_id,
8091                path,
8092                label: {
8093                    match language {
8094                        Some(language) => {
8095                            language
8096                                .label_for_symbol(&serialized_symbol.name, kind)
8097                                .await
8098                        }
8099                        None => None,
8100                    }
8101                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8102                },
8103
8104                name: serialized_symbol.name,
8105                range: Unclipped(PointUtf16::new(start.row, start.column))
8106                    ..Unclipped(PointUtf16::new(end.row, end.column)),
8107                kind,
8108                signature: serialized_symbol
8109                    .signature
8110                    .try_into()
8111                    .map_err(|_| anyhow!("invalid signature"))?,
8112            })
8113        }
8114    }
8115
8116    async fn handle_buffer_saved(
8117        this: ModelHandle<Self>,
8118        envelope: TypedEnvelope<proto::BufferSaved>,
8119        _: Arc<Client>,
8120        mut cx: AsyncAppContext,
8121    ) -> Result<()> {
8122        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8123        let version = deserialize_version(&envelope.payload.version);
8124        let mtime = envelope
8125            .payload
8126            .mtime
8127            .ok_or_else(|| anyhow!("missing mtime"))?
8128            .into();
8129
8130        this.update(&mut cx, |this, cx| {
8131            let buffer = this
8132                .opened_buffers
8133                .get(&envelope.payload.buffer_id)
8134                .and_then(|buffer| buffer.upgrade(cx))
8135                .or_else(|| {
8136                    this.incomplete_remote_buffers
8137                        .get(&envelope.payload.buffer_id)
8138                        .and_then(|b| b.clone())
8139                });
8140            if let Some(buffer) = buffer {
8141                buffer.update(cx, |buffer, cx| {
8142                    buffer.did_save(version, fingerprint, mtime, cx);
8143                });
8144            }
8145            Ok(())
8146        })
8147    }
8148
8149    async fn handle_buffer_reloaded(
8150        this: ModelHandle<Self>,
8151        envelope: TypedEnvelope<proto::BufferReloaded>,
8152        _: Arc<Client>,
8153        mut cx: AsyncAppContext,
8154    ) -> Result<()> {
8155        let payload = envelope.payload;
8156        let version = deserialize_version(&payload.version);
8157        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8158        let line_ending = deserialize_line_ending(
8159            proto::LineEnding::from_i32(payload.line_ending)
8160                .ok_or_else(|| anyhow!("missing line ending"))?,
8161        );
8162        let mtime = payload
8163            .mtime
8164            .ok_or_else(|| anyhow!("missing mtime"))?
8165            .into();
8166        this.update(&mut cx, |this, cx| {
8167            let buffer = this
8168                .opened_buffers
8169                .get(&payload.buffer_id)
8170                .and_then(|buffer| buffer.upgrade(cx))
8171                .or_else(|| {
8172                    this.incomplete_remote_buffers
8173                        .get(&payload.buffer_id)
8174                        .cloned()
8175                        .flatten()
8176                });
8177            if let Some(buffer) = buffer {
8178                buffer.update(cx, |buffer, cx| {
8179                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8180                });
8181            }
8182            Ok(())
8183        })
8184    }
8185
8186    #[allow(clippy::type_complexity)]
8187    fn edits_from_lsp(
8188        &mut self,
8189        buffer: &ModelHandle<Buffer>,
8190        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8191        server_id: LanguageServerId,
8192        version: Option<i32>,
8193        cx: &mut ModelContext<Self>,
8194    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8195        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8196        cx.background().spawn(async move {
8197            let snapshot = snapshot?;
8198            let mut lsp_edits = lsp_edits
8199                .into_iter()
8200                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8201                .collect::<Vec<_>>();
8202            lsp_edits.sort_by_key(|(range, _)| range.start);
8203
8204            let mut lsp_edits = lsp_edits.into_iter().peekable();
8205            let mut edits = Vec::new();
8206            while let Some((range, mut new_text)) = lsp_edits.next() {
8207                // Clip invalid ranges provided by the language server.
8208                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8209                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
8210
8211                // Combine any LSP edits that are adjacent.
8212                //
8213                // Also, combine LSP edits that are separated from each other by only
8214                // a newline. This is important because for some code actions,
8215                // Rust-analyzer rewrites the entire buffer via a series of edits that
8216                // are separated by unchanged newline characters.
8217                //
8218                // In order for the diffing logic below to work properly, any edits that
8219                // cancel each other out must be combined into one.
8220                while let Some((next_range, next_text)) = lsp_edits.peek() {
8221                    if next_range.start.0 > range.end {
8222                        if next_range.start.0.row > range.end.row + 1
8223                            || next_range.start.0.column > 0
8224                            || snapshot.clip_point_utf16(
8225                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8226                                Bias::Left,
8227                            ) > range.end
8228                        {
8229                            break;
8230                        }
8231                        new_text.push('\n');
8232                    }
8233                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8234                    new_text.push_str(next_text);
8235                    lsp_edits.next();
8236                }
8237
8238                // For multiline edits, perform a diff of the old and new text so that
8239                // we can identify the changes more precisely, preserving the locations
8240                // of any anchors positioned in the unchanged regions.
8241                if range.end.row > range.start.row {
8242                    let mut offset = range.start.to_offset(&snapshot);
8243                    let old_text = snapshot.text_for_range(range).collect::<String>();
8244
8245                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8246                    let mut moved_since_edit = true;
8247                    for change in diff.iter_all_changes() {
8248                        let tag = change.tag();
8249                        let value = change.value();
8250                        match tag {
8251                            ChangeTag::Equal => {
8252                                offset += value.len();
8253                                moved_since_edit = true;
8254                            }
8255                            ChangeTag::Delete => {
8256                                let start = snapshot.anchor_after(offset);
8257                                let end = snapshot.anchor_before(offset + value.len());
8258                                if moved_since_edit {
8259                                    edits.push((start..end, String::new()));
8260                                } else {
8261                                    edits.last_mut().unwrap().0.end = end;
8262                                }
8263                                offset += value.len();
8264                                moved_since_edit = false;
8265                            }
8266                            ChangeTag::Insert => {
8267                                if moved_since_edit {
8268                                    let anchor = snapshot.anchor_after(offset);
8269                                    edits.push((anchor..anchor, value.to_string()));
8270                                } else {
8271                                    edits.last_mut().unwrap().1.push_str(value);
8272                                }
8273                                moved_since_edit = false;
8274                            }
8275                        }
8276                    }
8277                } else if range.end == range.start {
8278                    let anchor = snapshot.anchor_after(range.start);
8279                    edits.push((anchor..anchor, new_text));
8280                } else {
8281                    let edit_start = snapshot.anchor_after(range.start);
8282                    let edit_end = snapshot.anchor_before(range.end);
8283                    edits.push((edit_start..edit_end, new_text));
8284                }
8285            }
8286
8287            Ok(edits)
8288        })
8289    }
8290
8291    fn buffer_snapshot_for_lsp_version(
8292        &mut self,
8293        buffer: &ModelHandle<Buffer>,
8294        server_id: LanguageServerId,
8295        version: Option<i32>,
8296        cx: &AppContext,
8297    ) -> Result<TextBufferSnapshot> {
8298        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8299
8300        if let Some(version) = version {
8301            let buffer_id = buffer.read(cx).remote_id();
8302            let snapshots = self
8303                .buffer_snapshots
8304                .get_mut(&buffer_id)
8305                .and_then(|m| m.get_mut(&server_id))
8306                .ok_or_else(|| {
8307                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
8308                })?;
8309
8310            let found_snapshot = snapshots
8311                .binary_search_by_key(&version, |e| e.version)
8312                .map(|ix| snapshots[ix].snapshot.clone())
8313                .map_err(|_| {
8314                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
8315                })?;
8316
8317            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
8318            Ok(found_snapshot)
8319        } else {
8320            Ok((buffer.read(cx)).text_snapshot())
8321        }
8322    }
8323
8324    pub fn language_servers(
8325        &self,
8326    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
8327        self.language_server_ids
8328            .iter()
8329            .map(|((worktree_id, server_name), server_id)| {
8330                (*server_id, server_name.clone(), *worktree_id)
8331            })
8332    }
8333
8334    pub fn supplementary_language_servers(
8335        &self,
8336    ) -> impl '_
8337           + Iterator<
8338        Item = (
8339            &LanguageServerId,
8340            &(LanguageServerName, Arc<LanguageServer>),
8341        ),
8342    > {
8343        self.supplementary_language_servers.iter()
8344    }
8345
8346    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8347        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
8348            Some(server.clone())
8349        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
8350            Some(Arc::clone(server))
8351        } else {
8352            None
8353        }
8354    }
8355
8356    pub fn language_servers_for_buffer(
8357        &self,
8358        buffer: &Buffer,
8359        cx: &AppContext,
8360    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8361        self.language_server_ids_for_buffer(buffer, cx)
8362            .into_iter()
8363            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
8364                LanguageServerState::Running {
8365                    adapter, server, ..
8366                } => Some((adapter, server)),
8367                _ => None,
8368            })
8369    }
8370
8371    fn primary_language_server_for_buffer(
8372        &self,
8373        buffer: &Buffer,
8374        cx: &AppContext,
8375    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8376        self.language_servers_for_buffer(buffer, cx).next()
8377    }
8378
8379    pub fn language_server_for_buffer(
8380        &self,
8381        buffer: &Buffer,
8382        server_id: LanguageServerId,
8383        cx: &AppContext,
8384    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8385        self.language_servers_for_buffer(buffer, cx)
8386            .find(|(_, s)| s.server_id() == server_id)
8387    }
8388
8389    fn language_server_ids_for_buffer(
8390        &self,
8391        buffer: &Buffer,
8392        cx: &AppContext,
8393    ) -> Vec<LanguageServerId> {
8394        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8395            let worktree_id = file.worktree_id(cx);
8396            language
8397                .lsp_adapters()
8398                .iter()
8399                .flat_map(|adapter| {
8400                    let key = (worktree_id, adapter.name.clone());
8401                    self.language_server_ids.get(&key).copied()
8402                })
8403                .collect()
8404        } else {
8405            Vec::new()
8406        }
8407    }
8408
8409    fn prettier_instance_for_buffer(
8410        &mut self,
8411        buffer: &ModelHandle<Buffer>,
8412        cx: &mut ModelContext<Self>,
8413    ) -> Task<
8414        Option<(
8415            Option<PathBuf>,
8416            Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>>,
8417        )>,
8418    > {
8419        let buffer = buffer.read(cx);
8420        let buffer_file = buffer.file();
8421        let Some(buffer_language) = buffer.language() else {
8422            return Task::ready(None);
8423        };
8424        if buffer_language.prettier_parser_name().is_none() {
8425            return Task::ready(None);
8426        }
8427
8428        if self.is_local() {
8429            let Some(node) = self.node.as_ref().map(Arc::clone) else {
8430                return Task::ready(None);
8431            };
8432            match File::from_dyn(buffer_file).map(|file| file.abs_path(cx)) {
8433                Some(buffer_path) => {
8434                    let fs = Arc::clone(&self.fs);
8435                    let installed_prettiers = self.prettier_instances.keys().cloned().collect();
8436                    return cx.spawn(|project, mut cx| async move {
8437                        match cx
8438                            .background()
8439                            .spawn(async move {
8440                                Prettier::locate_prettier_installation(
8441                                    fs.as_ref(),
8442                                    &installed_prettiers,
8443                                    &buffer_path,
8444                                )
8445                                .await
8446                            })
8447                            .await
8448                        {
8449                            Ok(None) => {
8450                                let new_task = project.update(&mut cx, |project, cx| {
8451                                    let new_task = spawn_default_prettier(node, cx);
8452                                    project
8453                                        .default_prettier
8454                                        .get_or_insert_with(|| DefaultPrettier {
8455                                            instance: None,
8456                                            #[cfg(not(any(test, feature = "test-support")))]
8457                                            installed_plugins: HashSet::default(),
8458                                        })
8459                                        .instance = Some(new_task.clone());
8460                                    new_task
8461                                });
8462                                return Some((None, new_task));
8463                            }
8464                            Err(e) => {
8465                                return Some((
8466                                    None,
8467                                    Task::ready(Err(Arc::new(
8468                                        e.context("determining prettier path"),
8469                                    )))
8470                                    .shared(),
8471                                ));
8472                            }
8473                            Ok(Some(prettier_dir)) => {
8474                                if let Some(existing_prettier) =
8475                                    project.update(&mut cx, |project, _| {
8476                                        project.prettier_instances.get(&prettier_dir).cloned()
8477                                    })
8478                                {
8479                                    return Some((Some(prettier_dir), existing_prettier));
8480                                }
8481
8482                                log::info!("Found prettier in {prettier_dir:?}, starting.");
8483                                let task_prettier_dir = prettier_dir.clone();
8484                                let task_project = project.clone();
8485                                let new_server_id = project.update(&mut cx, |this, _| {
8486                                    this.languages.next_language_server_id()
8487                                });
8488                                let new_prettier_task = cx
8489                                    .spawn(|mut cx| async move {
8490                                        let prettier = Prettier::start(
8491                                            new_server_id,
8492                                            task_prettier_dir,
8493                                            node,
8494                                            cx.clone(),
8495                                        )
8496                                        .await
8497                                        .context("prettier start")
8498                                        .map_err(Arc::new)?;
8499                                        register_new_prettier(
8500                                            &task_project,
8501                                            &prettier,
8502                                            new_server_id,
8503                                            &mut cx,
8504                                        );
8505                                        Ok(Arc::new(prettier)).map_err(Arc::new)
8506                                    })
8507                                    .shared();
8508                                project.update(&mut cx, |project, _| {
8509                                    project
8510                                        .prettier_instances
8511                                        .insert(prettier_dir.clone(), new_prettier_task.clone());
8512                                });
8513                                Some((Some(prettier_dir), new_prettier_task))
8514                            }
8515                        }
8516                    });
8517                }
8518                None => {
8519                    let new_task = spawn_default_prettier(node, cx);
8520                    self.default_prettier
8521                        .get_or_insert_with(|| DefaultPrettier {
8522                            instance: None,
8523                            #[cfg(not(any(test, feature = "test-support")))]
8524                            installed_plugins: HashSet::default(),
8525                        })
8526                        .instance = Some(new_task.clone());
8527                    return Task::ready(Some((None, new_task)));
8528                }
8529            }
8530        } else if self.remote_id().is_some() {
8531            return Task::ready(None);
8532        } else {
8533            Task::ready(Some((
8534                None,
8535                Task::ready(Err(Arc::new(anyhow!("project does not have a remote id")))).shared(),
8536            )))
8537        }
8538    }
8539
8540    #[cfg(any(test, feature = "test-support"))]
8541    fn install_default_formatters(
8542        &mut self,
8543        _worktree: Option<WorktreeId>,
8544        _new_language: &Language,
8545        _language_settings: &LanguageSettings,
8546        _cx: &mut ModelContext<Self>,
8547    ) -> Task<anyhow::Result<()>> {
8548        return Task::ready(Ok(()));
8549    }
8550
8551    #[cfg(not(any(test, feature = "test-support")))]
8552    fn install_default_formatters(
8553        &mut self,
8554        worktree: Option<WorktreeId>,
8555        new_language: &Language,
8556        language_settings: &LanguageSettings,
8557        cx: &mut ModelContext<Self>,
8558    ) -> Task<anyhow::Result<()>> {
8559        match &language_settings.formatter {
8560            Formatter::Prettier { .. } | Formatter::Auto => {}
8561            Formatter::LanguageServer | Formatter::External { .. } => return Task::ready(Ok(())),
8562        };
8563        let Some(node) = self.node.as_ref().cloned() else {
8564            return Task::ready(Ok(()));
8565        };
8566
8567        let mut prettier_plugins = None;
8568        if new_language.prettier_parser_name().is_some() {
8569            prettier_plugins
8570                .get_or_insert_with(|| HashSet::<&'static str>::default())
8571                .extend(
8572                    new_language
8573                        .lsp_adapters()
8574                        .iter()
8575                        .flat_map(|adapter| adapter.prettier_plugins()),
8576                )
8577        }
8578        let Some(prettier_plugins) = prettier_plugins else {
8579            return Task::ready(Ok(()));
8580        };
8581
8582        let fs = Arc::clone(&self.fs);
8583        let locate_prettier_installation = match worktree.and_then(|worktree_id| {
8584            self.worktree_for_id(worktree_id, cx)
8585                .map(|worktree| worktree.read(cx).abs_path())
8586        }) {
8587            Some(locate_from) => {
8588                let installed_prettiers = self.prettier_instances.keys().cloned().collect();
8589                cx.background().spawn(async move {
8590                    Prettier::locate_prettier_installation(
8591                        fs.as_ref(),
8592                        &installed_prettiers,
8593                        locate_from.as_ref(),
8594                    )
8595                    .await
8596                })
8597            }
8598            None => Task::ready(Ok(None)),
8599        };
8600        let mut plugins_to_install = prettier_plugins;
8601        let previous_installation_process =
8602            if let Some(default_prettier) = &mut self.default_prettier {
8603                plugins_to_install
8604                    .retain(|plugin| !default_prettier.installed_plugins.contains(plugin));
8605                if plugins_to_install.is_empty() {
8606                    return Task::ready(Ok(()));
8607                }
8608                default_prettier.instance.clone()
8609            } else {
8610                None
8611            };
8612        let fs = Arc::clone(&self.fs);
8613        cx.spawn(|this, mut cx| async move {
8614            match locate_prettier_installation
8615                .await
8616                .context("locate prettier installation")?
8617            {
8618                Some(_non_default_prettier) => return Ok(()),
8619                None => {
8620                    let mut needs_restart = match previous_installation_process {
8621                        Some(previous_installation_process) => {
8622                            previous_installation_process.await.is_err()
8623                        }
8624                        None => true,
8625                    };
8626                    this.update(&mut cx, |this, _| {
8627                        if let Some(default_prettier) = &mut this.default_prettier {
8628                            plugins_to_install.retain(|plugin| {
8629                                !default_prettier.installed_plugins.contains(plugin)
8630                            });
8631                            needs_restart |= !plugins_to_install.is_empty();
8632                        }
8633                    });
8634                    if needs_restart {
8635                        let installed_plugins = plugins_to_install.clone();
8636                        cx.background()
8637                            .spawn(async move {
8638                                install_default_prettier(plugins_to_install, node, fs).await
8639                            })
8640                            .await
8641                            .context("prettier & plugins install")?;
8642                        this.update(&mut cx, |this, _| {
8643                            let default_prettier =
8644                                this.default_prettier
8645                                    .get_or_insert_with(|| DefaultPrettier {
8646                                        instance: None,
8647                                        installed_plugins: HashSet::default(),
8648                                    });
8649                            default_prettier.instance = None;
8650                            default_prettier.installed_plugins.extend(installed_plugins);
8651                        });
8652                    }
8653                }
8654            }
8655            Ok(())
8656        })
8657    }
8658}
8659
8660fn register_new_prettier(
8661    project: &ModelHandle<Project>,
8662    prettier: &Prettier,
8663    new_server_id: LanguageServerId,
8664    cx: &mut AsyncAppContext,
8665) {
8666    log::info!("Started prettier in {:?}", prettier.prettier_dir());
8667    if let Some(prettier_server) = prettier.server() {
8668        project.update(cx, |project, cx| {
8669            let name = if prettier.is_default() {
8670                LanguageServerName(Arc::from("prettier (default)"))
8671            } else {
8672                LanguageServerName(Arc::from(format!(
8673                    "prettier ({})",
8674                    prettier.prettier_dir().display(),
8675                )))
8676            };
8677            project
8678                .supplementary_language_servers
8679                .insert(new_server_id, (name, Arc::clone(prettier_server)));
8680            cx.emit(Event::LanguageServerAdded(new_server_id));
8681        });
8682    }
8683}
8684
8685fn spawn_default_prettier(
8686    node: Arc<dyn NodeRuntime>,
8687    cx: &mut ModelContext<'_, Project>,
8688) -> Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>> {
8689    cx.spawn(|project, mut cx| async move {
8690        let new_server_id = project.update(&mut cx, |project, _| {
8691            project.languages.next_language_server_id()
8692        });
8693        let new_prettier = Prettier::start(
8694            new_server_id,
8695            DEFAULT_PRETTIER_DIR.clone(),
8696            node,
8697            cx.clone(),
8698        )
8699        .await
8700        .context("default prettier spawn")
8701        .map(Arc::new)
8702        .map_err(Arc::new)?;
8703
8704        register_new_prettier(&project, &new_prettier, new_server_id, &mut cx);
8705
8706        Ok(new_prettier)
8707    })
8708    .shared()
8709}
8710
8711#[cfg(not(any(test, feature = "test-support")))]
8712async fn install_default_prettier(
8713    plugins_to_install: HashSet<&'static str>,
8714    node: Arc<dyn NodeRuntime>,
8715    fs: Arc<dyn Fs>,
8716) -> anyhow::Result<()> {
8717    let prettier_wrapper_path = DEFAULT_PRETTIER_DIR.join(prettier::PRETTIER_SERVER_FILE);
8718    // method creates parent directory if it doesn't exist
8719    fs.save(
8720        &prettier_wrapper_path,
8721        &text::Rope::from(prettier::PRETTIER_SERVER_JS),
8722        text::LineEnding::Unix,
8723    )
8724    .await
8725    .with_context(|| {
8726        format!(
8727            "writing {} file at {prettier_wrapper_path:?}",
8728            prettier::PRETTIER_SERVER_FILE
8729        )
8730    })?;
8731
8732    let packages_to_versions =
8733        future::try_join_all(plugins_to_install.iter().chain(Some(&"prettier")).map(
8734            |package_name| async {
8735                let returned_package_name = package_name.to_string();
8736                let latest_version = node
8737                    .npm_package_latest_version(package_name)
8738                    .await
8739                    .with_context(|| {
8740                        format!("fetching latest npm version for package {returned_package_name}")
8741                    })?;
8742                anyhow::Ok((returned_package_name, latest_version))
8743            },
8744        ))
8745        .await
8746        .context("fetching latest npm versions")?;
8747
8748    log::info!("Fetching default prettier and plugins: {packages_to_versions:?}");
8749    let borrowed_packages = packages_to_versions
8750        .iter()
8751        .map(|(package, version)| (package.as_str(), version.as_str()))
8752        .collect::<Vec<_>>();
8753    node.npm_install_packages(DEFAULT_PRETTIER_DIR.as_path(), &borrowed_packages)
8754        .await
8755        .context("fetching formatter packages")?;
8756    anyhow::Ok(())
8757}
8758
8759fn subscribe_for_copilot_events(
8760    copilot: &ModelHandle<Copilot>,
8761    cx: &mut ModelContext<'_, Project>,
8762) -> gpui::Subscription {
8763    cx.subscribe(
8764        copilot,
8765        |project, copilot, copilot_event, cx| match copilot_event {
8766            copilot::Event::CopilotLanguageServerStarted => {
8767                match copilot.read(cx).language_server() {
8768                    Some((name, copilot_server)) => {
8769                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
8770                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
8771                            let new_server_id = copilot_server.server_id();
8772                            let weak_project = cx.weak_handle();
8773                            let copilot_log_subscription = copilot_server
8774                                .on_notification::<copilot::request::LogMessage, _>(
8775                                    move |params, mut cx| {
8776                                        if let Some(project) = weak_project.upgrade(&mut cx) {
8777                                            project.update(&mut cx, |_, cx| {
8778                                                cx.emit(Event::LanguageServerLog(
8779                                                    new_server_id,
8780                                                    params.message,
8781                                                ));
8782                                            })
8783                                        }
8784                                    },
8785                                );
8786                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
8787                            project.copilot_log_subscription = Some(copilot_log_subscription);
8788                            cx.emit(Event::LanguageServerAdded(new_server_id));
8789                        }
8790                    }
8791                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
8792                }
8793            }
8794        },
8795    )
8796}
8797
8798fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8799    let mut literal_end = 0;
8800    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8801        if part.contains(&['*', '?', '{', '}']) {
8802            break;
8803        } else {
8804            if i > 0 {
8805                // Acount for separator prior to this part
8806                literal_end += path::MAIN_SEPARATOR.len_utf8();
8807            }
8808            literal_end += part.len();
8809        }
8810    }
8811    &glob[..literal_end]
8812}
8813
8814impl WorktreeHandle {
8815    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
8816        match self {
8817            WorktreeHandle::Strong(handle) => Some(handle.clone()),
8818            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
8819        }
8820    }
8821
8822    pub fn handle_id(&self) -> usize {
8823        match self {
8824            WorktreeHandle::Strong(handle) => handle.id(),
8825            WorktreeHandle::Weak(handle) => handle.id(),
8826        }
8827    }
8828}
8829
8830impl OpenBuffer {
8831    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
8832        match self {
8833            OpenBuffer::Strong(handle) => Some(handle.clone()),
8834            OpenBuffer::Weak(handle) => handle.upgrade(cx),
8835            OpenBuffer::Operations(_) => None,
8836        }
8837    }
8838}
8839
8840pub struct PathMatchCandidateSet {
8841    pub snapshot: Snapshot,
8842    pub include_ignored: bool,
8843    pub include_root_name: bool,
8844}
8845
8846impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
8847    type Candidates = PathMatchCandidateSetIter<'a>;
8848
8849    fn id(&self) -> usize {
8850        self.snapshot.id().to_usize()
8851    }
8852
8853    fn len(&self) -> usize {
8854        if self.include_ignored {
8855            self.snapshot.file_count()
8856        } else {
8857            self.snapshot.visible_file_count()
8858        }
8859    }
8860
8861    fn prefix(&self) -> Arc<str> {
8862        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
8863            self.snapshot.root_name().into()
8864        } else if self.include_root_name {
8865            format!("{}/", self.snapshot.root_name()).into()
8866        } else {
8867            "".into()
8868        }
8869    }
8870
8871    fn candidates(&'a self, start: usize) -> Self::Candidates {
8872        PathMatchCandidateSetIter {
8873            traversal: self.snapshot.files(self.include_ignored, start),
8874        }
8875    }
8876}
8877
8878pub struct PathMatchCandidateSetIter<'a> {
8879    traversal: Traversal<'a>,
8880}
8881
8882impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8883    type Item = fuzzy::PathMatchCandidate<'a>;
8884
8885    fn next(&mut self) -> Option<Self::Item> {
8886        self.traversal.next().map(|entry| {
8887            if let EntryKind::File(char_bag) = entry.kind {
8888                fuzzy::PathMatchCandidate {
8889                    path: &entry.path,
8890                    char_bag,
8891                }
8892            } else {
8893                unreachable!()
8894            }
8895        })
8896    }
8897}
8898
8899impl Entity for Project {
8900    type Event = Event;
8901
8902    fn release(&mut self, cx: &mut gpui::AppContext) {
8903        match &self.client_state {
8904            Some(ProjectClientState::Local { .. }) => {
8905                let _ = self.unshare_internal(cx);
8906            }
8907            Some(ProjectClientState::Remote { remote_id, .. }) => {
8908                let _ = self.client.send(proto::LeaveProject {
8909                    project_id: *remote_id,
8910                });
8911                self.disconnected_from_host_internal(cx);
8912            }
8913            _ => {}
8914        }
8915    }
8916
8917    fn app_will_quit(
8918        &mut self,
8919        _: &mut AppContext,
8920    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
8921        let shutdown_futures = self
8922            .language_servers
8923            .drain()
8924            .map(|(_, server_state)| async {
8925                use LanguageServerState::*;
8926                match server_state {
8927                    Running { server, .. } => server.shutdown()?.await,
8928                    Starting(task) => task.await?.shutdown()?.await,
8929                }
8930            })
8931            .collect::<Vec<_>>();
8932
8933        Some(
8934            async move {
8935                futures::future::join_all(shutdown_futures).await;
8936            }
8937            .boxed(),
8938        )
8939    }
8940}
8941
8942impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8943    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8944        Self {
8945            worktree_id,
8946            path: path.as_ref().into(),
8947        }
8948    }
8949}
8950
8951impl ProjectLspAdapterDelegate {
8952    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8953        Arc::new(Self {
8954            project: cx.handle(),
8955            http_client: project.client.http_client(),
8956        })
8957    }
8958}
8959
8960impl LspAdapterDelegate for ProjectLspAdapterDelegate {
8961    fn show_notification(&self, message: &str, cx: &mut AppContext) {
8962        self.project
8963            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
8964    }
8965
8966    fn http_client(&self) -> Arc<dyn HttpClient> {
8967        self.http_client.clone()
8968    }
8969}
8970
8971fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
8972    proto::Symbol {
8973        language_server_name: symbol.language_server_name.0.to_string(),
8974        source_worktree_id: symbol.source_worktree_id.to_proto(),
8975        worktree_id: symbol.path.worktree_id.to_proto(),
8976        path: symbol.path.path.to_string_lossy().to_string(),
8977        name: symbol.name.clone(),
8978        kind: unsafe { mem::transmute(symbol.kind) },
8979        start: Some(proto::PointUtf16 {
8980            row: symbol.range.start.0.row,
8981            column: symbol.range.start.0.column,
8982        }),
8983        end: Some(proto::PointUtf16 {
8984            row: symbol.range.end.0.row,
8985            column: symbol.range.end.0.column,
8986        }),
8987        signature: symbol.signature.to_vec(),
8988    }
8989}
8990
8991fn relativize_path(base: &Path, path: &Path) -> PathBuf {
8992    let mut path_components = path.components();
8993    let mut base_components = base.components();
8994    let mut components: Vec<Component> = Vec::new();
8995    loop {
8996        match (path_components.next(), base_components.next()) {
8997            (None, None) => break,
8998            (Some(a), None) => {
8999                components.push(a);
9000                components.extend(path_components.by_ref());
9001                break;
9002            }
9003            (None, _) => components.push(Component::ParentDir),
9004            (Some(a), Some(b)) if components.is_empty() && a == b => (),
9005            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
9006            (Some(a), Some(_)) => {
9007                components.push(Component::ParentDir);
9008                for _ in base_components {
9009                    components.push(Component::ParentDir);
9010                }
9011                components.push(a);
9012                components.extend(path_components.by_ref());
9013                break;
9014            }
9015        }
9016    }
9017    components.iter().map(|c| c.as_os_str()).collect()
9018}
9019
9020impl Item for Buffer {
9021    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
9022        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
9023    }
9024
9025    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
9026        File::from_dyn(self.file()).map(|file| ProjectPath {
9027            worktree_id: file.worktree_id(cx),
9028            path: file.path().clone(),
9029        })
9030    }
9031}
9032
9033async fn wait_for_loading_buffer(
9034    mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
9035) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
9036    loop {
9037        if let Some(result) = receiver.borrow().as_ref() {
9038            match result {
9039                Ok(buffer) => return Ok(buffer.to_owned()),
9040                Err(e) => return Err(e.to_owned()),
9041            }
9042        }
9043        receiver.next().await;
9044    }
9045}
9046
9047fn include_text(server: &lsp::LanguageServer) -> bool {
9048    server
9049        .capabilities()
9050        .text_document_sync
9051        .as_ref()
9052        .and_then(|sync| match sync {
9053            lsp::TextDocumentSyncCapability::Kind(_) => None,
9054            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
9055        })
9056        .and_then(|save_options| match save_options {
9057            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
9058            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
9059        })
9060        .unwrap_or(false)
9061}