project.rs

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