project.rs

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