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