project.rs

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