project.rs

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