project.rs

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