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