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