project.rs

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