project2.rs

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