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