project.rs

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