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