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