project.rs

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