project.rs

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