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