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