project.rs

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