project.rs

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