project.rs

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