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 inlay_hints<T: ToOffset>(
4933        &self,
4934        buffer_handle: ModelHandle<Buffer>,
4935        range: Range<T>,
4936        cx: &mut ModelContext<Self>,
4937    ) -> Task<Result<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                lsp_request_task.await.context("inlay hints LSP request")
4956            })
4957        } else if let Some(project_id) = self.remote_id() {
4958            let client = self.client.clone();
4959            let request = proto::InlayHints {
4960                project_id,
4961                buffer_id,
4962                start: Some(serialize_anchor(&range_start)),
4963                end: Some(serialize_anchor(&range_end)),
4964                version: serialize_version(&buffer_version),
4965            };
4966            cx.spawn(|project, cx| async move {
4967                let response = client
4968                    .request(request)
4969                    .await
4970                    .context("inlay hints proto request")?;
4971                let hints_request_result = LspCommand::response_from_proto(
4972                    lsp_request,
4973                    response,
4974                    project,
4975                    buffer_handle.clone(),
4976                    cx,
4977                )
4978                .await;
4979
4980                hints_request_result.context("inlay hints proto response conversion")
4981            })
4982        } else {
4983            Task::ready(Err(anyhow!("project does not have a remote id")))
4984        }
4985    }
4986
4987    #[allow(clippy::type_complexity)]
4988    pub fn search(
4989        &self,
4990        query: SearchQuery,
4991        cx: &mut ModelContext<Self>,
4992    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4993        if self.is_local() {
4994            let snapshots = self
4995                .visible_worktrees(cx)
4996                .filter_map(|tree| {
4997                    let tree = tree.read(cx).as_local()?;
4998                    Some(tree.snapshot())
4999                })
5000                .collect::<Vec<_>>();
5001
5002            let background = cx.background().clone();
5003            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
5004            if path_count == 0 {
5005                return Task::ready(Ok(Default::default()));
5006            }
5007            let workers = background.num_cpus().min(path_count);
5008            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
5009            cx.background()
5010                .spawn({
5011                    let fs = self.fs.clone();
5012                    let background = cx.background().clone();
5013                    let query = query.clone();
5014                    async move {
5015                        let fs = &fs;
5016                        let query = &query;
5017                        let matching_paths_tx = &matching_paths_tx;
5018                        let paths_per_worker = (path_count + workers - 1) / workers;
5019                        let snapshots = &snapshots;
5020                        background
5021                            .scoped(|scope| {
5022                                for worker_ix in 0..workers {
5023                                    let worker_start_ix = worker_ix * paths_per_worker;
5024                                    let worker_end_ix = worker_start_ix + paths_per_worker;
5025                                    scope.spawn(async move {
5026                                        let mut snapshot_start_ix = 0;
5027                                        let mut abs_path = PathBuf::new();
5028                                        for snapshot in snapshots {
5029                                            let snapshot_end_ix =
5030                                                snapshot_start_ix + snapshot.visible_file_count();
5031                                            if worker_end_ix <= snapshot_start_ix {
5032                                                break;
5033                                            } else if worker_start_ix > snapshot_end_ix {
5034                                                snapshot_start_ix = snapshot_end_ix;
5035                                                continue;
5036                                            } else {
5037                                                let start_in_snapshot = worker_start_ix
5038                                                    .saturating_sub(snapshot_start_ix);
5039                                                let end_in_snapshot =
5040                                                    cmp::min(worker_end_ix, snapshot_end_ix)
5041                                                        - snapshot_start_ix;
5042
5043                                                for entry in snapshot
5044                                                    .files(false, start_in_snapshot)
5045                                                    .take(end_in_snapshot - start_in_snapshot)
5046                                                {
5047                                                    if matching_paths_tx.is_closed() {
5048                                                        break;
5049                                                    }
5050                                                    let matches = if query
5051                                                        .file_matches(Some(&entry.path))
5052                                                    {
5053                                                        abs_path.clear();
5054                                                        abs_path.push(&snapshot.abs_path());
5055                                                        abs_path.push(&entry.path);
5056                                                        if let Some(file) =
5057                                                            fs.open_sync(&abs_path).await.log_err()
5058                                                        {
5059                                                            query.detect(file).unwrap_or(false)
5060                                                        } else {
5061                                                            false
5062                                                        }
5063                                                    } else {
5064                                                        false
5065                                                    };
5066
5067                                                    if matches {
5068                                                        let project_path =
5069                                                            (snapshot.id(), entry.path.clone());
5070                                                        if matching_paths_tx
5071                                                            .send(project_path)
5072                                                            .await
5073                                                            .is_err()
5074                                                        {
5075                                                            break;
5076                                                        }
5077                                                    }
5078                                                }
5079
5080                                                snapshot_start_ix = snapshot_end_ix;
5081                                            }
5082                                        }
5083                                    });
5084                                }
5085                            })
5086                            .await;
5087                    }
5088                })
5089                .detach();
5090
5091            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
5092            let open_buffers = self
5093                .opened_buffers
5094                .values()
5095                .filter_map(|b| b.upgrade(cx))
5096                .collect::<HashSet<_>>();
5097            cx.spawn(|this, cx| async move {
5098                for buffer in &open_buffers {
5099                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5100                    buffers_tx.send((buffer.clone(), snapshot)).await?;
5101                }
5102
5103                let open_buffers = Rc::new(RefCell::new(open_buffers));
5104                while let Some(project_path) = matching_paths_rx.next().await {
5105                    if buffers_tx.is_closed() {
5106                        break;
5107                    }
5108
5109                    let this = this.clone();
5110                    let open_buffers = open_buffers.clone();
5111                    let buffers_tx = buffers_tx.clone();
5112                    cx.spawn(|mut cx| async move {
5113                        if let Some(buffer) = this
5114                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
5115                            .await
5116                            .log_err()
5117                        {
5118                            if open_buffers.borrow_mut().insert(buffer.clone()) {
5119                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5120                                buffers_tx.send((buffer, snapshot)).await?;
5121                            }
5122                        }
5123
5124                        Ok::<_, anyhow::Error>(())
5125                    })
5126                    .detach();
5127                }
5128
5129                Ok::<_, anyhow::Error>(())
5130            })
5131            .detach_and_log_err(cx);
5132
5133            let background = cx.background().clone();
5134            cx.background().spawn(async move {
5135                let query = &query;
5136                let mut matched_buffers = Vec::new();
5137                for _ in 0..workers {
5138                    matched_buffers.push(HashMap::default());
5139                }
5140                background
5141                    .scoped(|scope| {
5142                        for worker_matched_buffers in matched_buffers.iter_mut() {
5143                            let mut buffers_rx = buffers_rx.clone();
5144                            scope.spawn(async move {
5145                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
5146                                    let buffer_matches = if query.file_matches(
5147                                        snapshot.file().map(|file| file.path().as_ref()),
5148                                    ) {
5149                                        query
5150                                            .search(snapshot.as_rope())
5151                                            .await
5152                                            .iter()
5153                                            .map(|range| {
5154                                                snapshot.anchor_before(range.start)
5155                                                    ..snapshot.anchor_after(range.end)
5156                                            })
5157                                            .collect()
5158                                    } else {
5159                                        Vec::new()
5160                                    };
5161                                    if !buffer_matches.is_empty() {
5162                                        worker_matched_buffers
5163                                            .insert(buffer.clone(), buffer_matches);
5164                                    }
5165                                }
5166                            });
5167                        }
5168                    })
5169                    .await;
5170                Ok(matched_buffers.into_iter().flatten().collect())
5171            })
5172        } else if let Some(project_id) = self.remote_id() {
5173            let request = self.client.request(query.to_proto(project_id));
5174            cx.spawn(|this, mut cx| async move {
5175                let response = request.await?;
5176                let mut result = HashMap::default();
5177                for location in response.locations {
5178                    let target_buffer = this
5179                        .update(&mut cx, |this, cx| {
5180                            this.wait_for_remote_buffer(location.buffer_id, cx)
5181                        })
5182                        .await?;
5183                    let start = location
5184                        .start
5185                        .and_then(deserialize_anchor)
5186                        .ok_or_else(|| anyhow!("missing target start"))?;
5187                    let end = location
5188                        .end
5189                        .and_then(deserialize_anchor)
5190                        .ok_or_else(|| anyhow!("missing target end"))?;
5191                    result
5192                        .entry(target_buffer)
5193                        .or_insert(Vec::new())
5194                        .push(start..end)
5195                }
5196                Ok(result)
5197            })
5198        } else {
5199            Task::ready(Ok(Default::default()))
5200        }
5201    }
5202
5203    // TODO: Wire this up to allow selecting a server?
5204    fn request_lsp<R: LspCommand>(
5205        &self,
5206        buffer_handle: ModelHandle<Buffer>,
5207        request: R,
5208        cx: &mut ModelContext<Self>,
5209    ) -> Task<Result<R::Response>>
5210    where
5211        <R::LspRequest as lsp::request::Request>::Result: Send,
5212    {
5213        let buffer = buffer_handle.read(cx);
5214        if self.is_local() {
5215            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5216            if let Some((file, language_server)) = file.zip(
5217                self.primary_language_servers_for_buffer(buffer, cx)
5218                    .map(|(_, server)| server.clone()),
5219            ) {
5220                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5221                return cx.spawn(|this, cx| async move {
5222                    if !request.check_capabilities(language_server.capabilities()) {
5223                        return Ok(Default::default());
5224                    }
5225
5226                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
5227                    let response = match result {
5228                        Ok(response) => response,
5229
5230                        Err(err) => {
5231                            log::warn!(
5232                                "Generic lsp request to {} failed: {}",
5233                                language_server.name(),
5234                                err
5235                            );
5236                            return Err(err);
5237                        }
5238                    };
5239
5240                    request
5241                        .response_from_lsp(
5242                            response,
5243                            this,
5244                            buffer_handle,
5245                            language_server.server_id(),
5246                            cx,
5247                        )
5248                        .await
5249                });
5250            }
5251        } else if let Some(project_id) = self.remote_id() {
5252            let rpc = self.client.clone();
5253            let message = request.to_proto(project_id, buffer);
5254            return cx.spawn_weak(|this, cx| async move {
5255                // Ensure the project is still alive by the time the task
5256                // is scheduled.
5257                this.upgrade(&cx)
5258                    .ok_or_else(|| anyhow!("project dropped"))?;
5259
5260                let response = rpc.request(message).await?;
5261
5262                let this = this
5263                    .upgrade(&cx)
5264                    .ok_or_else(|| anyhow!("project dropped"))?;
5265                if this.read_with(&cx, |this, _| this.is_read_only()) {
5266                    Err(anyhow!("disconnected before completing request"))
5267                } else {
5268                    request
5269                        .response_from_proto(response, this, buffer_handle, cx)
5270                        .await
5271                }
5272            });
5273        }
5274        Task::ready(Ok(Default::default()))
5275    }
5276
5277    pub fn find_or_create_local_worktree(
5278        &mut self,
5279        abs_path: impl AsRef<Path>,
5280        visible: bool,
5281        cx: &mut ModelContext<Self>,
5282    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
5283        let abs_path = abs_path.as_ref();
5284        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
5285            Task::ready(Ok((tree, relative_path)))
5286        } else {
5287            let worktree = self.create_local_worktree(abs_path, visible, cx);
5288            cx.foreground()
5289                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
5290        }
5291    }
5292
5293    pub fn find_local_worktree(
5294        &self,
5295        abs_path: &Path,
5296        cx: &AppContext,
5297    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
5298        for tree in &self.worktrees {
5299            if let Some(tree) = tree.upgrade(cx) {
5300                if let Some(relative_path) = tree
5301                    .read(cx)
5302                    .as_local()
5303                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
5304                {
5305                    return Some((tree.clone(), relative_path.into()));
5306                }
5307            }
5308        }
5309        None
5310    }
5311
5312    pub fn is_shared(&self) -> bool {
5313        match &self.client_state {
5314            Some(ProjectClientState::Local { .. }) => true,
5315            _ => false,
5316        }
5317    }
5318
5319    fn create_local_worktree(
5320        &mut self,
5321        abs_path: impl AsRef<Path>,
5322        visible: bool,
5323        cx: &mut ModelContext<Self>,
5324    ) -> Task<Result<ModelHandle<Worktree>>> {
5325        let fs = self.fs.clone();
5326        let client = self.client.clone();
5327        let next_entry_id = self.next_entry_id.clone();
5328        let path: Arc<Path> = abs_path.as_ref().into();
5329        let task = self
5330            .loading_local_worktrees
5331            .entry(path.clone())
5332            .or_insert_with(|| {
5333                cx.spawn(|project, mut cx| {
5334                    async move {
5335                        let worktree = Worktree::local(
5336                            client.clone(),
5337                            path.clone(),
5338                            visible,
5339                            fs,
5340                            next_entry_id,
5341                            &mut cx,
5342                        )
5343                        .await;
5344
5345                        project.update(&mut cx, |project, _| {
5346                            project.loading_local_worktrees.remove(&path);
5347                        });
5348
5349                        let worktree = worktree?;
5350                        project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
5351                        Ok(worktree)
5352                    }
5353                    .map_err(Arc::new)
5354                })
5355                .shared()
5356            })
5357            .clone();
5358        cx.foreground().spawn(async move {
5359            match task.await {
5360                Ok(worktree) => Ok(worktree),
5361                Err(err) => Err(anyhow!("{}", err)),
5362            }
5363        })
5364    }
5365
5366    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
5367        self.worktrees.retain(|worktree| {
5368            if let Some(worktree) = worktree.upgrade(cx) {
5369                let id = worktree.read(cx).id();
5370                if id == id_to_remove {
5371                    cx.emit(Event::WorktreeRemoved(id));
5372                    false
5373                } else {
5374                    true
5375                }
5376            } else {
5377                false
5378            }
5379        });
5380        self.metadata_changed(cx);
5381    }
5382
5383    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
5384        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
5385        if worktree.read(cx).is_local() {
5386            cx.subscribe(worktree, |this, worktree, event, cx| match event {
5387                worktree::Event::UpdatedEntries(changes) => {
5388                    this.update_local_worktree_buffers(&worktree, changes, cx);
5389                    this.update_local_worktree_language_servers(&worktree, changes, cx);
5390                    this.update_local_worktree_settings(&worktree, changes, cx);
5391                }
5392                worktree::Event::UpdatedGitRepositories(updated_repos) => {
5393                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
5394                }
5395            })
5396            .detach();
5397        }
5398
5399        let push_strong_handle = {
5400            let worktree = worktree.read(cx);
5401            self.is_shared() || worktree.is_visible() || worktree.is_remote()
5402        };
5403        if push_strong_handle {
5404            self.worktrees
5405                .push(WorktreeHandle::Strong(worktree.clone()));
5406        } else {
5407            self.worktrees
5408                .push(WorktreeHandle::Weak(worktree.downgrade()));
5409        }
5410
5411        let handle_id = worktree.id();
5412        cx.observe_release(worktree, move |this, worktree, cx| {
5413            let _ = this.remove_worktree(worktree.id(), cx);
5414            cx.update_global::<SettingsStore, _, _>(|store, cx| {
5415                store.clear_local_settings(handle_id, cx).log_err()
5416            });
5417        })
5418        .detach();
5419
5420        cx.emit(Event::WorktreeAdded);
5421        self.metadata_changed(cx);
5422    }
5423
5424    fn update_local_worktree_buffers(
5425        &mut self,
5426        worktree_handle: &ModelHandle<Worktree>,
5427        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5428        cx: &mut ModelContext<Self>,
5429    ) {
5430        let snapshot = worktree_handle.read(cx).snapshot();
5431
5432        let mut renamed_buffers = Vec::new();
5433        for (path, entry_id, _) in changes {
5434            let worktree_id = worktree_handle.read(cx).id();
5435            let project_path = ProjectPath {
5436                worktree_id,
5437                path: path.clone(),
5438            };
5439
5440            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
5441                Some(&buffer_id) => buffer_id,
5442                None => match self.local_buffer_ids_by_path.get(&project_path) {
5443                    Some(&buffer_id) => buffer_id,
5444                    None => continue,
5445                },
5446            };
5447
5448            let open_buffer = self.opened_buffers.get(&buffer_id);
5449            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
5450                buffer
5451            } else {
5452                self.opened_buffers.remove(&buffer_id);
5453                self.local_buffer_ids_by_path.remove(&project_path);
5454                self.local_buffer_ids_by_entry_id.remove(entry_id);
5455                continue;
5456            };
5457
5458            buffer.update(cx, |buffer, cx| {
5459                if let Some(old_file) = File::from_dyn(buffer.file()) {
5460                    if old_file.worktree != *worktree_handle {
5461                        return;
5462                    }
5463
5464                    let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
5465                        File {
5466                            is_local: true,
5467                            entry_id: entry.id,
5468                            mtime: entry.mtime,
5469                            path: entry.path.clone(),
5470                            worktree: worktree_handle.clone(),
5471                            is_deleted: false,
5472                        }
5473                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
5474                        File {
5475                            is_local: true,
5476                            entry_id: entry.id,
5477                            mtime: entry.mtime,
5478                            path: entry.path.clone(),
5479                            worktree: worktree_handle.clone(),
5480                            is_deleted: false,
5481                        }
5482                    } else {
5483                        File {
5484                            is_local: true,
5485                            entry_id: old_file.entry_id,
5486                            path: old_file.path().clone(),
5487                            mtime: old_file.mtime(),
5488                            worktree: worktree_handle.clone(),
5489                            is_deleted: true,
5490                        }
5491                    };
5492
5493                    let old_path = old_file.abs_path(cx);
5494                    if new_file.abs_path(cx) != old_path {
5495                        renamed_buffers.push((cx.handle(), old_file.clone()));
5496                        self.local_buffer_ids_by_path.remove(&project_path);
5497                        self.local_buffer_ids_by_path.insert(
5498                            ProjectPath {
5499                                worktree_id,
5500                                path: path.clone(),
5501                            },
5502                            buffer_id,
5503                        );
5504                    }
5505
5506                    if new_file.entry_id != *entry_id {
5507                        self.local_buffer_ids_by_entry_id.remove(entry_id);
5508                        self.local_buffer_ids_by_entry_id
5509                            .insert(new_file.entry_id, buffer_id);
5510                    }
5511
5512                    if new_file != *old_file {
5513                        if let Some(project_id) = self.remote_id() {
5514                            self.client
5515                                .send(proto::UpdateBufferFile {
5516                                    project_id,
5517                                    buffer_id: buffer_id as u64,
5518                                    file: Some(new_file.to_proto()),
5519                                })
5520                                .log_err();
5521                        }
5522
5523                        buffer.file_updated(Arc::new(new_file), cx).detach();
5524                    }
5525                }
5526            });
5527        }
5528
5529        for (buffer, old_file) in renamed_buffers {
5530            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
5531            self.detect_language_for_buffer(&buffer, cx);
5532            self.register_buffer_with_language_servers(&buffer, cx);
5533        }
5534    }
5535
5536    fn update_local_worktree_language_servers(
5537        &mut self,
5538        worktree_handle: &ModelHandle<Worktree>,
5539        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5540        cx: &mut ModelContext<Self>,
5541    ) {
5542        if changes.is_empty() {
5543            return;
5544        }
5545
5546        let worktree_id = worktree_handle.read(cx).id();
5547        let mut language_server_ids = self
5548            .language_server_ids
5549            .iter()
5550            .filter_map(|((server_worktree_id, _), server_id)| {
5551                (*server_worktree_id == worktree_id).then_some(*server_id)
5552            })
5553            .collect::<Vec<_>>();
5554        language_server_ids.sort();
5555        language_server_ids.dedup();
5556
5557        let abs_path = worktree_handle.read(cx).abs_path();
5558        for server_id in &language_server_ids {
5559            if let Some(LanguageServerState::Running {
5560                server,
5561                watched_paths,
5562                ..
5563            }) = self.language_servers.get(server_id)
5564            {
5565                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
5566                    let params = lsp::DidChangeWatchedFilesParams {
5567                        changes: changes
5568                            .iter()
5569                            .filter_map(|(path, _, change)| {
5570                                if !watched_paths.is_match(&path) {
5571                                    return None;
5572                                }
5573                                let typ = match change {
5574                                    PathChange::Loaded => return None,
5575                                    PathChange::Added => lsp::FileChangeType::CREATED,
5576                                    PathChange::Removed => lsp::FileChangeType::DELETED,
5577                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
5578                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
5579                                };
5580                                Some(lsp::FileEvent {
5581                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
5582                                    typ,
5583                                })
5584                            })
5585                            .collect(),
5586                    };
5587
5588                    if !params.changes.is_empty() {
5589                        server
5590                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
5591                            .log_err();
5592                    }
5593                }
5594            }
5595        }
5596    }
5597
5598    fn update_local_worktree_buffers_git_repos(
5599        &mut self,
5600        worktree_handle: ModelHandle<Worktree>,
5601        changed_repos: &UpdatedGitRepositoriesSet,
5602        cx: &mut ModelContext<Self>,
5603    ) {
5604        debug_assert!(worktree_handle.read(cx).is_local());
5605
5606        // Identify the loading buffers whose containing repository that has changed.
5607        let future_buffers = self
5608            .loading_buffers_by_path
5609            .iter()
5610            .filter_map(|(project_path, receiver)| {
5611                if project_path.worktree_id != worktree_handle.read(cx).id() {
5612                    return None;
5613                }
5614                let path = &project_path.path;
5615                changed_repos
5616                    .iter()
5617                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
5618                let receiver = receiver.clone();
5619                let path = path.clone();
5620                Some(async move {
5621                    wait_for_loading_buffer(receiver)
5622                        .await
5623                        .ok()
5624                        .map(|buffer| (buffer, path))
5625                })
5626            })
5627            .collect::<FuturesUnordered<_>>();
5628
5629        // Identify the current buffers whose containing repository has changed.
5630        let current_buffers = self
5631            .opened_buffers
5632            .values()
5633            .filter_map(|buffer| {
5634                let buffer = buffer.upgrade(cx)?;
5635                let file = File::from_dyn(buffer.read(cx).file())?;
5636                if file.worktree != worktree_handle {
5637                    return None;
5638                }
5639                let path = file.path();
5640                changed_repos
5641                    .iter()
5642                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
5643                Some((buffer, path.clone()))
5644            })
5645            .collect::<Vec<_>>();
5646
5647        if future_buffers.len() + current_buffers.len() == 0 {
5648            return;
5649        }
5650
5651        let remote_id = self.remote_id();
5652        let client = self.client.clone();
5653        cx.spawn_weak(move |_, mut cx| async move {
5654            // Wait for all of the buffers to load.
5655            let future_buffers = future_buffers.collect::<Vec<_>>().await;
5656
5657            // Reload the diff base for every buffer whose containing git repository has changed.
5658            let snapshot =
5659                worktree_handle.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
5660            let diff_bases_by_buffer = cx
5661                .background()
5662                .spawn(async move {
5663                    future_buffers
5664                        .into_iter()
5665                        .filter_map(|e| e)
5666                        .chain(current_buffers)
5667                        .filter_map(|(buffer, path)| {
5668                            let (work_directory, repo) =
5669                                snapshot.repository_and_work_directory_for_path(&path)?;
5670                            let repo = snapshot.get_local_repo(&repo)?;
5671                            let relative_path = path.strip_prefix(&work_directory).ok()?;
5672                            let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
5673                            Some((buffer, base_text))
5674                        })
5675                        .collect::<Vec<_>>()
5676                })
5677                .await;
5678
5679            // Assign the new diff bases on all of the buffers.
5680            for (buffer, diff_base) in diff_bases_by_buffer {
5681                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
5682                    buffer.set_diff_base(diff_base.clone(), cx);
5683                    buffer.remote_id()
5684                });
5685                if let Some(project_id) = remote_id {
5686                    client
5687                        .send(proto::UpdateDiffBase {
5688                            project_id,
5689                            buffer_id,
5690                            diff_base,
5691                        })
5692                        .log_err();
5693                }
5694            }
5695        })
5696        .detach();
5697    }
5698
5699    fn update_local_worktree_settings(
5700        &mut self,
5701        worktree: &ModelHandle<Worktree>,
5702        changes: &UpdatedEntriesSet,
5703        cx: &mut ModelContext<Self>,
5704    ) {
5705        let project_id = self.remote_id();
5706        let worktree_id = worktree.id();
5707        let worktree = worktree.read(cx).as_local().unwrap();
5708        let remote_worktree_id = worktree.id();
5709
5710        let mut settings_contents = Vec::new();
5711        for (path, _, change) in changes.iter() {
5712            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
5713                let settings_dir = Arc::from(
5714                    path.ancestors()
5715                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
5716                        .unwrap(),
5717                );
5718                let fs = self.fs.clone();
5719                let removed = *change == PathChange::Removed;
5720                let abs_path = worktree.absolutize(path);
5721                settings_contents.push(async move {
5722                    (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
5723                });
5724            }
5725        }
5726
5727        if settings_contents.is_empty() {
5728            return;
5729        }
5730
5731        let client = self.client.clone();
5732        cx.spawn_weak(move |_, mut cx| async move {
5733            let settings_contents: Vec<(Arc<Path>, _)> =
5734                futures::future::join_all(settings_contents).await;
5735            cx.update(|cx| {
5736                cx.update_global::<SettingsStore, _, _>(|store, cx| {
5737                    for (directory, file_content) in settings_contents {
5738                        let file_content = file_content.and_then(|content| content.log_err());
5739                        store
5740                            .set_local_settings(
5741                                worktree_id,
5742                                directory.clone(),
5743                                file_content.as_ref().map(String::as_str),
5744                                cx,
5745                            )
5746                            .log_err();
5747                        if let Some(remote_id) = project_id {
5748                            client
5749                                .send(proto::UpdateWorktreeSettings {
5750                                    project_id: remote_id,
5751                                    worktree_id: remote_worktree_id.to_proto(),
5752                                    path: directory.to_string_lossy().into_owned(),
5753                                    content: file_content,
5754                                })
5755                                .log_err();
5756                        }
5757                    }
5758                });
5759            });
5760        })
5761        .detach();
5762    }
5763
5764    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
5765        let new_active_entry = entry.and_then(|project_path| {
5766            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
5767            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
5768            Some(entry.id)
5769        });
5770        if new_active_entry != self.active_entry {
5771            self.active_entry = new_active_entry;
5772            cx.emit(Event::ActiveEntryChanged(new_active_entry));
5773        }
5774    }
5775
5776    pub fn language_servers_running_disk_based_diagnostics(
5777        &self,
5778    ) -> impl Iterator<Item = LanguageServerId> + '_ {
5779        self.language_server_statuses
5780            .iter()
5781            .filter_map(|(id, status)| {
5782                if status.has_pending_diagnostic_updates {
5783                    Some(*id)
5784                } else {
5785                    None
5786                }
5787            })
5788    }
5789
5790    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
5791        let mut summary = DiagnosticSummary::default();
5792        for (_, _, path_summary) in self.diagnostic_summaries(cx) {
5793            summary.error_count += path_summary.error_count;
5794            summary.warning_count += path_summary.warning_count;
5795        }
5796        summary
5797    }
5798
5799    pub fn diagnostic_summaries<'a>(
5800        &'a self,
5801        cx: &'a AppContext,
5802    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
5803        self.visible_worktrees(cx).flat_map(move |worktree| {
5804            let worktree = worktree.read(cx);
5805            let worktree_id = worktree.id();
5806            worktree
5807                .diagnostic_summaries()
5808                .map(move |(path, server_id, summary)| {
5809                    (ProjectPath { worktree_id, path }, server_id, summary)
5810                })
5811        })
5812    }
5813
5814    pub fn disk_based_diagnostics_started(
5815        &mut self,
5816        language_server_id: LanguageServerId,
5817        cx: &mut ModelContext<Self>,
5818    ) {
5819        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
5820    }
5821
5822    pub fn disk_based_diagnostics_finished(
5823        &mut self,
5824        language_server_id: LanguageServerId,
5825        cx: &mut ModelContext<Self>,
5826    ) {
5827        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
5828    }
5829
5830    pub fn active_entry(&self) -> Option<ProjectEntryId> {
5831        self.active_entry
5832    }
5833
5834    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
5835        self.worktree_for_id(path.worktree_id, cx)?
5836            .read(cx)
5837            .entry_for_path(&path.path)
5838            .cloned()
5839    }
5840
5841    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
5842        let worktree = self.worktree_for_entry(entry_id, cx)?;
5843        let worktree = worktree.read(cx);
5844        let worktree_id = worktree.id();
5845        let path = worktree.entry_for_id(entry_id)?.path.clone();
5846        Some(ProjectPath { worktree_id, path })
5847    }
5848
5849    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
5850        let workspace_root = self
5851            .worktree_for_id(project_path.worktree_id, cx)?
5852            .read(cx)
5853            .abs_path();
5854        let project_path = project_path.path.as_ref();
5855
5856        Some(if project_path == Path::new("") {
5857            workspace_root.to_path_buf()
5858        } else {
5859            workspace_root.join(project_path)
5860        })
5861    }
5862
5863    // RPC message handlers
5864
5865    async fn handle_unshare_project(
5866        this: ModelHandle<Self>,
5867        _: TypedEnvelope<proto::UnshareProject>,
5868        _: Arc<Client>,
5869        mut cx: AsyncAppContext,
5870    ) -> Result<()> {
5871        this.update(&mut cx, |this, cx| {
5872            if this.is_local() {
5873                this.unshare(cx)?;
5874            } else {
5875                this.disconnected_from_host(cx);
5876            }
5877            Ok(())
5878        })
5879    }
5880
5881    async fn handle_add_collaborator(
5882        this: ModelHandle<Self>,
5883        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
5884        _: Arc<Client>,
5885        mut cx: AsyncAppContext,
5886    ) -> Result<()> {
5887        let collaborator = envelope
5888            .payload
5889            .collaborator
5890            .take()
5891            .ok_or_else(|| anyhow!("empty collaborator"))?;
5892
5893        let collaborator = Collaborator::from_proto(collaborator)?;
5894        this.update(&mut cx, |this, cx| {
5895            this.shared_buffers.remove(&collaborator.peer_id);
5896            this.collaborators
5897                .insert(collaborator.peer_id, collaborator);
5898            cx.notify();
5899        });
5900
5901        Ok(())
5902    }
5903
5904    async fn handle_update_project_collaborator(
5905        this: ModelHandle<Self>,
5906        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
5907        _: Arc<Client>,
5908        mut cx: AsyncAppContext,
5909    ) -> Result<()> {
5910        let old_peer_id = envelope
5911            .payload
5912            .old_peer_id
5913            .ok_or_else(|| anyhow!("missing old peer id"))?;
5914        let new_peer_id = envelope
5915            .payload
5916            .new_peer_id
5917            .ok_or_else(|| anyhow!("missing new peer id"))?;
5918        this.update(&mut cx, |this, cx| {
5919            let collaborator = this
5920                .collaborators
5921                .remove(&old_peer_id)
5922                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
5923            let is_host = collaborator.replica_id == 0;
5924            this.collaborators.insert(new_peer_id, collaborator);
5925
5926            let buffers = this.shared_buffers.remove(&old_peer_id);
5927            log::info!(
5928                "peer {} became {}. moving buffers {:?}",
5929                old_peer_id,
5930                new_peer_id,
5931                &buffers
5932            );
5933            if let Some(buffers) = buffers {
5934                this.shared_buffers.insert(new_peer_id, buffers);
5935            }
5936
5937            if is_host {
5938                this.opened_buffers
5939                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
5940                this.buffer_ordered_messages_tx
5941                    .unbounded_send(BufferOrderedMessage::Resync)
5942                    .unwrap();
5943            }
5944
5945            cx.emit(Event::CollaboratorUpdated {
5946                old_peer_id,
5947                new_peer_id,
5948            });
5949            cx.notify();
5950            Ok(())
5951        })
5952    }
5953
5954    async fn handle_remove_collaborator(
5955        this: ModelHandle<Self>,
5956        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5957        _: Arc<Client>,
5958        mut cx: AsyncAppContext,
5959    ) -> Result<()> {
5960        this.update(&mut cx, |this, cx| {
5961            let peer_id = envelope
5962                .payload
5963                .peer_id
5964                .ok_or_else(|| anyhow!("invalid peer id"))?;
5965            let replica_id = this
5966                .collaborators
5967                .remove(&peer_id)
5968                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
5969                .replica_id;
5970            for buffer in this.opened_buffers.values() {
5971                if let Some(buffer) = buffer.upgrade(cx) {
5972                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5973                }
5974            }
5975            this.shared_buffers.remove(&peer_id);
5976
5977            cx.emit(Event::CollaboratorLeft(peer_id));
5978            cx.notify();
5979            Ok(())
5980        })
5981    }
5982
5983    async fn handle_update_project(
5984        this: ModelHandle<Self>,
5985        envelope: TypedEnvelope<proto::UpdateProject>,
5986        _: Arc<Client>,
5987        mut cx: AsyncAppContext,
5988    ) -> Result<()> {
5989        this.update(&mut cx, |this, cx| {
5990            // Don't handle messages that were sent before the response to us joining the project
5991            if envelope.message_id > this.join_project_response_message_id {
5992                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5993            }
5994            Ok(())
5995        })
5996    }
5997
5998    async fn handle_update_worktree(
5999        this: ModelHandle<Self>,
6000        envelope: TypedEnvelope<proto::UpdateWorktree>,
6001        _: Arc<Client>,
6002        mut cx: AsyncAppContext,
6003    ) -> Result<()> {
6004        this.update(&mut cx, |this, cx| {
6005            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6006            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6007                worktree.update(cx, |worktree, _| {
6008                    let worktree = worktree.as_remote_mut().unwrap();
6009                    worktree.update_from_remote(envelope.payload);
6010                });
6011            }
6012            Ok(())
6013        })
6014    }
6015
6016    async fn handle_update_worktree_settings(
6017        this: ModelHandle<Self>,
6018        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6019        _: Arc<Client>,
6020        mut cx: AsyncAppContext,
6021    ) -> Result<()> {
6022        this.update(&mut cx, |this, cx| {
6023            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6024            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6025                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6026                    store
6027                        .set_local_settings(
6028                            worktree.id(),
6029                            PathBuf::from(&envelope.payload.path).into(),
6030                            envelope.payload.content.as_ref().map(String::as_str),
6031                            cx,
6032                        )
6033                        .log_err();
6034                });
6035            }
6036            Ok(())
6037        })
6038    }
6039
6040    async fn handle_create_project_entry(
6041        this: ModelHandle<Self>,
6042        envelope: TypedEnvelope<proto::CreateProjectEntry>,
6043        _: Arc<Client>,
6044        mut cx: AsyncAppContext,
6045    ) -> Result<proto::ProjectEntryResponse> {
6046        let worktree = this.update(&mut cx, |this, cx| {
6047            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6048            this.worktree_for_id(worktree_id, cx)
6049                .ok_or_else(|| anyhow!("worktree not found"))
6050        })?;
6051        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6052        let entry = worktree
6053            .update(&mut cx, |worktree, cx| {
6054                let worktree = worktree.as_local_mut().unwrap();
6055                let path = PathBuf::from(envelope.payload.path);
6056                worktree.create_entry(path, envelope.payload.is_directory, cx)
6057            })
6058            .await?;
6059        Ok(proto::ProjectEntryResponse {
6060            entry: Some((&entry).into()),
6061            worktree_scan_id: worktree_scan_id as u64,
6062        })
6063    }
6064
6065    async fn handle_rename_project_entry(
6066        this: ModelHandle<Self>,
6067        envelope: TypedEnvelope<proto::RenameProjectEntry>,
6068        _: Arc<Client>,
6069        mut cx: AsyncAppContext,
6070    ) -> Result<proto::ProjectEntryResponse> {
6071        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6072        let worktree = this.read_with(&cx, |this, cx| {
6073            this.worktree_for_entry(entry_id, cx)
6074                .ok_or_else(|| anyhow!("worktree not found"))
6075        })?;
6076        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6077        let entry = worktree
6078            .update(&mut cx, |worktree, cx| {
6079                let new_path = PathBuf::from(envelope.payload.new_path);
6080                worktree
6081                    .as_local_mut()
6082                    .unwrap()
6083                    .rename_entry(entry_id, new_path, cx)
6084                    .ok_or_else(|| anyhow!("invalid entry"))
6085            })?
6086            .await?;
6087        Ok(proto::ProjectEntryResponse {
6088            entry: Some((&entry).into()),
6089            worktree_scan_id: worktree_scan_id as u64,
6090        })
6091    }
6092
6093    async fn handle_copy_project_entry(
6094        this: ModelHandle<Self>,
6095        envelope: TypedEnvelope<proto::CopyProjectEntry>,
6096        _: Arc<Client>,
6097        mut cx: AsyncAppContext,
6098    ) -> Result<proto::ProjectEntryResponse> {
6099        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6100        let worktree = this.read_with(&cx, |this, cx| {
6101            this.worktree_for_entry(entry_id, cx)
6102                .ok_or_else(|| anyhow!("worktree not found"))
6103        })?;
6104        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6105        let entry = worktree
6106            .update(&mut cx, |worktree, cx| {
6107                let new_path = PathBuf::from(envelope.payload.new_path);
6108                worktree
6109                    .as_local_mut()
6110                    .unwrap()
6111                    .copy_entry(entry_id, new_path, cx)
6112                    .ok_or_else(|| anyhow!("invalid entry"))
6113            })?
6114            .await?;
6115        Ok(proto::ProjectEntryResponse {
6116            entry: Some((&entry).into()),
6117            worktree_scan_id: worktree_scan_id as u64,
6118        })
6119    }
6120
6121    async fn handle_delete_project_entry(
6122        this: ModelHandle<Self>,
6123        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6124        _: Arc<Client>,
6125        mut cx: AsyncAppContext,
6126    ) -> Result<proto::ProjectEntryResponse> {
6127        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6128
6129        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
6130
6131        let worktree = this.read_with(&cx, |this, cx| {
6132            this.worktree_for_entry(entry_id, cx)
6133                .ok_or_else(|| anyhow!("worktree not found"))
6134        })?;
6135        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6136        worktree
6137            .update(&mut cx, |worktree, cx| {
6138                worktree
6139                    .as_local_mut()
6140                    .unwrap()
6141                    .delete_entry(entry_id, cx)
6142                    .ok_or_else(|| anyhow!("invalid entry"))
6143            })?
6144            .await?;
6145        Ok(proto::ProjectEntryResponse {
6146            entry: None,
6147            worktree_scan_id: worktree_scan_id as u64,
6148        })
6149    }
6150
6151    async fn handle_expand_project_entry(
6152        this: ModelHandle<Self>,
6153        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
6154        _: Arc<Client>,
6155        mut cx: AsyncAppContext,
6156    ) -> Result<proto::ExpandProjectEntryResponse> {
6157        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6158        let worktree = this
6159            .read_with(&cx, |this, cx| this.worktree_for_entry(entry_id, cx))
6160            .ok_or_else(|| anyhow!("invalid request"))?;
6161        worktree
6162            .update(&mut cx, |worktree, cx| {
6163                worktree
6164                    .as_local_mut()
6165                    .unwrap()
6166                    .expand_entry(entry_id, cx)
6167                    .ok_or_else(|| anyhow!("invalid entry"))
6168            })?
6169            .await?;
6170        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id()) as u64;
6171        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
6172    }
6173
6174    async fn handle_update_diagnostic_summary(
6175        this: ModelHandle<Self>,
6176        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
6177        _: Arc<Client>,
6178        mut cx: AsyncAppContext,
6179    ) -> Result<()> {
6180        this.update(&mut cx, |this, cx| {
6181            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6182            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6183                if let Some(summary) = envelope.payload.summary {
6184                    let project_path = ProjectPath {
6185                        worktree_id,
6186                        path: Path::new(&summary.path).into(),
6187                    };
6188                    worktree.update(cx, |worktree, _| {
6189                        worktree
6190                            .as_remote_mut()
6191                            .unwrap()
6192                            .update_diagnostic_summary(project_path.path.clone(), &summary);
6193                    });
6194                    cx.emit(Event::DiagnosticsUpdated {
6195                        language_server_id: LanguageServerId(summary.language_server_id as usize),
6196                        path: project_path,
6197                    });
6198                }
6199            }
6200            Ok(())
6201        })
6202    }
6203
6204    async fn handle_start_language_server(
6205        this: ModelHandle<Self>,
6206        envelope: TypedEnvelope<proto::StartLanguageServer>,
6207        _: Arc<Client>,
6208        mut cx: AsyncAppContext,
6209    ) -> Result<()> {
6210        let server = envelope
6211            .payload
6212            .server
6213            .ok_or_else(|| anyhow!("invalid server"))?;
6214        this.update(&mut cx, |this, cx| {
6215            this.language_server_statuses.insert(
6216                LanguageServerId(server.id as usize),
6217                LanguageServerStatus {
6218                    name: server.name,
6219                    pending_work: Default::default(),
6220                    has_pending_diagnostic_updates: false,
6221                    progress_tokens: Default::default(),
6222                },
6223            );
6224            cx.notify();
6225        });
6226        Ok(())
6227    }
6228
6229    async fn handle_update_language_server(
6230        this: ModelHandle<Self>,
6231        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
6232        _: Arc<Client>,
6233        mut cx: AsyncAppContext,
6234    ) -> Result<()> {
6235        this.update(&mut cx, |this, cx| {
6236            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
6237
6238            match envelope
6239                .payload
6240                .variant
6241                .ok_or_else(|| anyhow!("invalid variant"))?
6242            {
6243                proto::update_language_server::Variant::WorkStart(payload) => {
6244                    this.on_lsp_work_start(
6245                        language_server_id,
6246                        payload.token,
6247                        LanguageServerProgress {
6248                            message: payload.message,
6249                            percentage: payload.percentage.map(|p| p as usize),
6250                            last_update_at: Instant::now(),
6251                        },
6252                        cx,
6253                    );
6254                }
6255
6256                proto::update_language_server::Variant::WorkProgress(payload) => {
6257                    this.on_lsp_work_progress(
6258                        language_server_id,
6259                        payload.token,
6260                        LanguageServerProgress {
6261                            message: payload.message,
6262                            percentage: payload.percentage.map(|p| p as usize),
6263                            last_update_at: Instant::now(),
6264                        },
6265                        cx,
6266                    );
6267                }
6268
6269                proto::update_language_server::Variant::WorkEnd(payload) => {
6270                    this.on_lsp_work_end(language_server_id, payload.token, cx);
6271                }
6272
6273                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
6274                    this.disk_based_diagnostics_started(language_server_id, cx);
6275                }
6276
6277                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
6278                    this.disk_based_diagnostics_finished(language_server_id, cx)
6279                }
6280            }
6281
6282            Ok(())
6283        })
6284    }
6285
6286    async fn handle_update_buffer(
6287        this: ModelHandle<Self>,
6288        envelope: TypedEnvelope<proto::UpdateBuffer>,
6289        _: Arc<Client>,
6290        mut cx: AsyncAppContext,
6291    ) -> Result<proto::Ack> {
6292        this.update(&mut cx, |this, cx| {
6293            let payload = envelope.payload.clone();
6294            let buffer_id = payload.buffer_id;
6295            let ops = payload
6296                .operations
6297                .into_iter()
6298                .map(language::proto::deserialize_operation)
6299                .collect::<Result<Vec<_>, _>>()?;
6300            let is_remote = this.is_remote();
6301            match this.opened_buffers.entry(buffer_id) {
6302                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
6303                    OpenBuffer::Strong(buffer) => {
6304                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
6305                    }
6306                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
6307                    OpenBuffer::Weak(_) => {}
6308                },
6309                hash_map::Entry::Vacant(e) => {
6310                    assert!(
6311                        is_remote,
6312                        "received buffer update from {:?}",
6313                        envelope.original_sender_id
6314                    );
6315                    e.insert(OpenBuffer::Operations(ops));
6316                }
6317            }
6318            Ok(proto::Ack {})
6319        })
6320    }
6321
6322    async fn handle_create_buffer_for_peer(
6323        this: ModelHandle<Self>,
6324        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
6325        _: Arc<Client>,
6326        mut cx: AsyncAppContext,
6327    ) -> Result<()> {
6328        this.update(&mut cx, |this, cx| {
6329            match envelope
6330                .payload
6331                .variant
6332                .ok_or_else(|| anyhow!("missing variant"))?
6333            {
6334                proto::create_buffer_for_peer::Variant::State(mut state) => {
6335                    let mut buffer_file = None;
6336                    if let Some(file) = state.file.take() {
6337                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
6338                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
6339                            anyhow!("no worktree found for id {}", file.worktree_id)
6340                        })?;
6341                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
6342                            as Arc<dyn language::File>);
6343                    }
6344
6345                    let buffer_id = state.id;
6346                    let buffer = cx.add_model(|_| {
6347                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
6348                    });
6349                    this.incomplete_remote_buffers
6350                        .insert(buffer_id, Some(buffer));
6351                }
6352                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
6353                    let buffer = this
6354                        .incomplete_remote_buffers
6355                        .get(&chunk.buffer_id)
6356                        .cloned()
6357                        .flatten()
6358                        .ok_or_else(|| {
6359                            anyhow!(
6360                                "received chunk for buffer {} without initial state",
6361                                chunk.buffer_id
6362                            )
6363                        })?;
6364                    let operations = chunk
6365                        .operations
6366                        .into_iter()
6367                        .map(language::proto::deserialize_operation)
6368                        .collect::<Result<Vec<_>>>()?;
6369                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
6370
6371                    if chunk.is_last {
6372                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
6373                        this.register_buffer(&buffer, cx)?;
6374                    }
6375                }
6376            }
6377
6378            Ok(())
6379        })
6380    }
6381
6382    async fn handle_update_diff_base(
6383        this: ModelHandle<Self>,
6384        envelope: TypedEnvelope<proto::UpdateDiffBase>,
6385        _: Arc<Client>,
6386        mut cx: AsyncAppContext,
6387    ) -> Result<()> {
6388        this.update(&mut cx, |this, cx| {
6389            let buffer_id = envelope.payload.buffer_id;
6390            let diff_base = envelope.payload.diff_base;
6391            if let Some(buffer) = this
6392                .opened_buffers
6393                .get_mut(&buffer_id)
6394                .and_then(|b| b.upgrade(cx))
6395                .or_else(|| {
6396                    this.incomplete_remote_buffers
6397                        .get(&buffer_id)
6398                        .cloned()
6399                        .flatten()
6400                })
6401            {
6402                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
6403            }
6404            Ok(())
6405        })
6406    }
6407
6408    async fn handle_update_buffer_file(
6409        this: ModelHandle<Self>,
6410        envelope: TypedEnvelope<proto::UpdateBufferFile>,
6411        _: Arc<Client>,
6412        mut cx: AsyncAppContext,
6413    ) -> Result<()> {
6414        let buffer_id = envelope.payload.buffer_id;
6415
6416        this.update(&mut cx, |this, cx| {
6417            let payload = envelope.payload.clone();
6418            if let Some(buffer) = this
6419                .opened_buffers
6420                .get(&buffer_id)
6421                .and_then(|b| b.upgrade(cx))
6422                .or_else(|| {
6423                    this.incomplete_remote_buffers
6424                        .get(&buffer_id)
6425                        .cloned()
6426                        .flatten()
6427                })
6428            {
6429                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
6430                let worktree = this
6431                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
6432                    .ok_or_else(|| anyhow!("no such worktree"))?;
6433                let file = File::from_proto(file, worktree, cx)?;
6434                buffer.update(cx, |buffer, cx| {
6435                    buffer.file_updated(Arc::new(file), cx).detach();
6436                });
6437                this.detect_language_for_buffer(&buffer, cx);
6438            }
6439            Ok(())
6440        })
6441    }
6442
6443    async fn handle_save_buffer(
6444        this: ModelHandle<Self>,
6445        envelope: TypedEnvelope<proto::SaveBuffer>,
6446        _: Arc<Client>,
6447        mut cx: AsyncAppContext,
6448    ) -> Result<proto::BufferSaved> {
6449        let buffer_id = envelope.payload.buffer_id;
6450        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
6451            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
6452            let buffer = this
6453                .opened_buffers
6454                .get(&buffer_id)
6455                .and_then(|buffer| buffer.upgrade(cx))
6456                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
6457            anyhow::Ok((project_id, buffer))
6458        })?;
6459        buffer
6460            .update(&mut cx, |buffer, _| {
6461                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
6462            })
6463            .await?;
6464        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
6465
6466        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
6467            .await?;
6468        Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
6469            project_id,
6470            buffer_id,
6471            version: serialize_version(buffer.saved_version()),
6472            mtime: Some(buffer.saved_mtime().into()),
6473            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
6474        }))
6475    }
6476
6477    async fn handle_reload_buffers(
6478        this: ModelHandle<Self>,
6479        envelope: TypedEnvelope<proto::ReloadBuffers>,
6480        _: Arc<Client>,
6481        mut cx: AsyncAppContext,
6482    ) -> Result<proto::ReloadBuffersResponse> {
6483        let sender_id = envelope.original_sender_id()?;
6484        let reload = this.update(&mut cx, |this, cx| {
6485            let mut buffers = HashSet::default();
6486            for buffer_id in &envelope.payload.buffer_ids {
6487                buffers.insert(
6488                    this.opened_buffers
6489                        .get(buffer_id)
6490                        .and_then(|buffer| buffer.upgrade(cx))
6491                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6492                );
6493            }
6494            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
6495        })?;
6496
6497        let project_transaction = reload.await?;
6498        let project_transaction = this.update(&mut cx, |this, cx| {
6499            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6500        });
6501        Ok(proto::ReloadBuffersResponse {
6502            transaction: Some(project_transaction),
6503        })
6504    }
6505
6506    async fn handle_synchronize_buffers(
6507        this: ModelHandle<Self>,
6508        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
6509        _: Arc<Client>,
6510        mut cx: AsyncAppContext,
6511    ) -> Result<proto::SynchronizeBuffersResponse> {
6512        let project_id = envelope.payload.project_id;
6513        let mut response = proto::SynchronizeBuffersResponse {
6514            buffers: Default::default(),
6515        };
6516
6517        this.update(&mut cx, |this, cx| {
6518            let Some(guest_id) = envelope.original_sender_id else {
6519                error!("missing original_sender_id on SynchronizeBuffers request");
6520                return;
6521            };
6522
6523            this.shared_buffers.entry(guest_id).or_default().clear();
6524            for buffer in envelope.payload.buffers {
6525                let buffer_id = buffer.id;
6526                let remote_version = language::proto::deserialize_version(&buffer.version);
6527                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6528                    this.shared_buffers
6529                        .entry(guest_id)
6530                        .or_default()
6531                        .insert(buffer_id);
6532
6533                    let buffer = buffer.read(cx);
6534                    response.buffers.push(proto::BufferVersion {
6535                        id: buffer_id,
6536                        version: language::proto::serialize_version(&buffer.version),
6537                    });
6538
6539                    let operations = buffer.serialize_ops(Some(remote_version), cx);
6540                    let client = this.client.clone();
6541                    if let Some(file) = buffer.file() {
6542                        client
6543                            .send(proto::UpdateBufferFile {
6544                                project_id,
6545                                buffer_id: buffer_id as u64,
6546                                file: Some(file.to_proto()),
6547                            })
6548                            .log_err();
6549                    }
6550
6551                    client
6552                        .send(proto::UpdateDiffBase {
6553                            project_id,
6554                            buffer_id: buffer_id as u64,
6555                            diff_base: buffer.diff_base().map(Into::into),
6556                        })
6557                        .log_err();
6558
6559                    client
6560                        .send(proto::BufferReloaded {
6561                            project_id,
6562                            buffer_id,
6563                            version: language::proto::serialize_version(buffer.saved_version()),
6564                            mtime: Some(buffer.saved_mtime().into()),
6565                            fingerprint: language::proto::serialize_fingerprint(
6566                                buffer.saved_version_fingerprint(),
6567                            ),
6568                            line_ending: language::proto::serialize_line_ending(
6569                                buffer.line_ending(),
6570                            ) as i32,
6571                        })
6572                        .log_err();
6573
6574                    cx.background()
6575                        .spawn(
6576                            async move {
6577                                let operations = operations.await;
6578                                for chunk in split_operations(operations) {
6579                                    client
6580                                        .request(proto::UpdateBuffer {
6581                                            project_id,
6582                                            buffer_id,
6583                                            operations: chunk,
6584                                        })
6585                                        .await?;
6586                                }
6587                                anyhow::Ok(())
6588                            }
6589                            .log_err(),
6590                        )
6591                        .detach();
6592                }
6593            }
6594        });
6595
6596        Ok(response)
6597    }
6598
6599    async fn handle_format_buffers(
6600        this: ModelHandle<Self>,
6601        envelope: TypedEnvelope<proto::FormatBuffers>,
6602        _: Arc<Client>,
6603        mut cx: AsyncAppContext,
6604    ) -> Result<proto::FormatBuffersResponse> {
6605        let sender_id = envelope.original_sender_id()?;
6606        let format = this.update(&mut cx, |this, cx| {
6607            let mut buffers = HashSet::default();
6608            for buffer_id in &envelope.payload.buffer_ids {
6609                buffers.insert(
6610                    this.opened_buffers
6611                        .get(buffer_id)
6612                        .and_then(|buffer| buffer.upgrade(cx))
6613                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6614                );
6615            }
6616            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
6617            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
6618        })?;
6619
6620        let project_transaction = format.await?;
6621        let project_transaction = this.update(&mut cx, |this, cx| {
6622            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6623        });
6624        Ok(proto::FormatBuffersResponse {
6625            transaction: Some(project_transaction),
6626        })
6627    }
6628
6629    async fn handle_apply_additional_edits_for_completion(
6630        this: ModelHandle<Self>,
6631        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
6632        _: Arc<Client>,
6633        mut cx: AsyncAppContext,
6634    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
6635        let (buffer, completion) = this.update(&mut cx, |this, cx| {
6636            let buffer = this
6637                .opened_buffers
6638                .get(&envelope.payload.buffer_id)
6639                .and_then(|buffer| buffer.upgrade(cx))
6640                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6641            let language = buffer.read(cx).language();
6642            let completion = language::proto::deserialize_completion(
6643                envelope
6644                    .payload
6645                    .completion
6646                    .ok_or_else(|| anyhow!("invalid completion"))?,
6647                language.cloned(),
6648            );
6649            Ok::<_, anyhow::Error>((buffer, completion))
6650        })?;
6651
6652        let completion = completion.await?;
6653
6654        let apply_additional_edits = this.update(&mut cx, |this, cx| {
6655            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
6656        });
6657
6658        Ok(proto::ApplyCompletionAdditionalEditsResponse {
6659            transaction: apply_additional_edits
6660                .await?
6661                .as_ref()
6662                .map(language::proto::serialize_transaction),
6663        })
6664    }
6665
6666    async fn handle_apply_code_action(
6667        this: ModelHandle<Self>,
6668        envelope: TypedEnvelope<proto::ApplyCodeAction>,
6669        _: Arc<Client>,
6670        mut cx: AsyncAppContext,
6671    ) -> Result<proto::ApplyCodeActionResponse> {
6672        let sender_id = envelope.original_sender_id()?;
6673        let action = language::proto::deserialize_code_action(
6674            envelope
6675                .payload
6676                .action
6677                .ok_or_else(|| anyhow!("invalid action"))?,
6678        )?;
6679        let apply_code_action = this.update(&mut cx, |this, cx| {
6680            let buffer = this
6681                .opened_buffers
6682                .get(&envelope.payload.buffer_id)
6683                .and_then(|buffer| buffer.upgrade(cx))
6684                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6685            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
6686        })?;
6687
6688        let project_transaction = apply_code_action.await?;
6689        let project_transaction = this.update(&mut cx, |this, cx| {
6690            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6691        });
6692        Ok(proto::ApplyCodeActionResponse {
6693            transaction: Some(project_transaction),
6694        })
6695    }
6696
6697    async fn handle_on_type_formatting(
6698        this: ModelHandle<Self>,
6699        envelope: TypedEnvelope<proto::OnTypeFormatting>,
6700        _: Arc<Client>,
6701        mut cx: AsyncAppContext,
6702    ) -> Result<proto::OnTypeFormattingResponse> {
6703        let on_type_formatting = this.update(&mut cx, |this, cx| {
6704            let buffer = this
6705                .opened_buffers
6706                .get(&envelope.payload.buffer_id)
6707                .and_then(|buffer| buffer.upgrade(cx))
6708                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6709            let position = envelope
6710                .payload
6711                .position
6712                .and_then(deserialize_anchor)
6713                .ok_or_else(|| anyhow!("invalid position"))?;
6714            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
6715                buffer,
6716                position,
6717                envelope.payload.trigger.clone(),
6718                cx,
6719            ))
6720        })?;
6721
6722        let transaction = on_type_formatting
6723            .await?
6724            .as_ref()
6725            .map(language::proto::serialize_transaction);
6726        Ok(proto::OnTypeFormattingResponse { transaction })
6727    }
6728
6729    async fn handle_inlay_hints(
6730        this: ModelHandle<Self>,
6731        envelope: TypedEnvelope<proto::InlayHints>,
6732        _: Arc<Client>,
6733        mut cx: AsyncAppContext,
6734    ) -> Result<proto::InlayHintsResponse> {
6735        let sender_id = envelope.original_sender_id()?;
6736        let buffer = this.update(&mut cx, |this, cx| {
6737            this.opened_buffers
6738                .get(&envelope.payload.buffer_id)
6739                .and_then(|buffer| buffer.upgrade(cx))
6740                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
6741        })?;
6742        let buffer_version = deserialize_version(&envelope.payload.version);
6743
6744        buffer
6745            .update(&mut cx, |buffer, _| {
6746                buffer.wait_for_version(buffer_version.clone())
6747            })
6748            .await
6749            .with_context(|| {
6750                format!(
6751                    "waiting for version {:?} for buffer {}",
6752                    buffer_version,
6753                    buffer.id()
6754                )
6755            })?;
6756
6757        let start = envelope
6758            .payload
6759            .start
6760            .and_then(deserialize_anchor)
6761            .context("missing range start")?;
6762        let end = envelope
6763            .payload
6764            .end
6765            .and_then(deserialize_anchor)
6766            .context("missing range end")?;
6767        let buffer_hints = this
6768            .update(&mut cx, |project, cx| {
6769                project.inlay_hints(buffer, start..end, cx)
6770            })
6771            .await
6772            .context("inlay hints fetch")?;
6773
6774        Ok(this.update(&mut cx, |project, cx| {
6775            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
6776        }))
6777    }
6778
6779    async fn handle_lsp_command<T: LspCommand>(
6780        this: ModelHandle<Self>,
6781        envelope: TypedEnvelope<T::ProtoRequest>,
6782        _: Arc<Client>,
6783        mut cx: AsyncAppContext,
6784    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
6785    where
6786        <T::LspRequest as lsp::request::Request>::Result: Send,
6787    {
6788        let sender_id = envelope.original_sender_id()?;
6789        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
6790        let buffer_handle = this.read_with(&cx, |this, _| {
6791            this.opened_buffers
6792                .get(&buffer_id)
6793                .and_then(|buffer| buffer.upgrade(&cx))
6794                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
6795        })?;
6796        let request = T::from_proto(
6797            envelope.payload,
6798            this.clone(),
6799            buffer_handle.clone(),
6800            cx.clone(),
6801        )
6802        .await?;
6803        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
6804        let response = this
6805            .update(&mut cx, |this, cx| {
6806                this.request_lsp(buffer_handle, request, cx)
6807            })
6808            .await?;
6809        this.update(&mut cx, |this, cx| {
6810            Ok(T::response_to_proto(
6811                response,
6812                this,
6813                sender_id,
6814                &buffer_version,
6815                cx,
6816            ))
6817        })
6818    }
6819
6820    async fn handle_get_project_symbols(
6821        this: ModelHandle<Self>,
6822        envelope: TypedEnvelope<proto::GetProjectSymbols>,
6823        _: Arc<Client>,
6824        mut cx: AsyncAppContext,
6825    ) -> Result<proto::GetProjectSymbolsResponse> {
6826        let symbols = this
6827            .update(&mut cx, |this, cx| {
6828                this.symbols(&envelope.payload.query, cx)
6829            })
6830            .await?;
6831
6832        Ok(proto::GetProjectSymbolsResponse {
6833            symbols: symbols.iter().map(serialize_symbol).collect(),
6834        })
6835    }
6836
6837    async fn handle_search_project(
6838        this: ModelHandle<Self>,
6839        envelope: TypedEnvelope<proto::SearchProject>,
6840        _: Arc<Client>,
6841        mut cx: AsyncAppContext,
6842    ) -> Result<proto::SearchProjectResponse> {
6843        let peer_id = envelope.original_sender_id()?;
6844        let query = SearchQuery::from_proto(envelope.payload)?;
6845        let result = this
6846            .update(&mut cx, |this, cx| this.search(query, cx))
6847            .await?;
6848
6849        this.update(&mut cx, |this, cx| {
6850            let mut locations = Vec::new();
6851            for (buffer, ranges) in result {
6852                for range in ranges {
6853                    let start = serialize_anchor(&range.start);
6854                    let end = serialize_anchor(&range.end);
6855                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
6856                    locations.push(proto::Location {
6857                        buffer_id,
6858                        start: Some(start),
6859                        end: Some(end),
6860                    });
6861                }
6862            }
6863            Ok(proto::SearchProjectResponse { locations })
6864        })
6865    }
6866
6867    async fn handle_open_buffer_for_symbol(
6868        this: ModelHandle<Self>,
6869        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
6870        _: Arc<Client>,
6871        mut cx: AsyncAppContext,
6872    ) -> Result<proto::OpenBufferForSymbolResponse> {
6873        let peer_id = envelope.original_sender_id()?;
6874        let symbol = envelope
6875            .payload
6876            .symbol
6877            .ok_or_else(|| anyhow!("invalid symbol"))?;
6878        let symbol = this
6879            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
6880            .await?;
6881        let symbol = this.read_with(&cx, |this, _| {
6882            let signature = this.symbol_signature(&symbol.path);
6883            if signature == symbol.signature {
6884                Ok(symbol)
6885            } else {
6886                Err(anyhow!("invalid symbol signature"))
6887            }
6888        })?;
6889        let buffer = this
6890            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
6891            .await?;
6892
6893        Ok(proto::OpenBufferForSymbolResponse {
6894            buffer_id: this.update(&mut cx, |this, cx| {
6895                this.create_buffer_for_peer(&buffer, peer_id, cx)
6896            }),
6897        })
6898    }
6899
6900    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
6901        let mut hasher = Sha256::new();
6902        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
6903        hasher.update(project_path.path.to_string_lossy().as_bytes());
6904        hasher.update(self.nonce.to_be_bytes());
6905        hasher.finalize().as_slice().try_into().unwrap()
6906    }
6907
6908    async fn handle_open_buffer_by_id(
6909        this: ModelHandle<Self>,
6910        envelope: TypedEnvelope<proto::OpenBufferById>,
6911        _: Arc<Client>,
6912        mut cx: AsyncAppContext,
6913    ) -> Result<proto::OpenBufferResponse> {
6914        let peer_id = envelope.original_sender_id()?;
6915        let buffer = this
6916            .update(&mut cx, |this, cx| {
6917                this.open_buffer_by_id(envelope.payload.id, cx)
6918            })
6919            .await?;
6920        this.update(&mut cx, |this, cx| {
6921            Ok(proto::OpenBufferResponse {
6922                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6923            })
6924        })
6925    }
6926
6927    async fn handle_open_buffer_by_path(
6928        this: ModelHandle<Self>,
6929        envelope: TypedEnvelope<proto::OpenBufferByPath>,
6930        _: Arc<Client>,
6931        mut cx: AsyncAppContext,
6932    ) -> Result<proto::OpenBufferResponse> {
6933        let peer_id = envelope.original_sender_id()?;
6934        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6935        let open_buffer = this.update(&mut cx, |this, cx| {
6936            this.open_buffer(
6937                ProjectPath {
6938                    worktree_id,
6939                    path: PathBuf::from(envelope.payload.path).into(),
6940                },
6941                cx,
6942            )
6943        });
6944
6945        let buffer = open_buffer.await?;
6946        this.update(&mut cx, |this, cx| {
6947            Ok(proto::OpenBufferResponse {
6948                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6949            })
6950        })
6951    }
6952
6953    fn serialize_project_transaction_for_peer(
6954        &mut self,
6955        project_transaction: ProjectTransaction,
6956        peer_id: proto::PeerId,
6957        cx: &mut AppContext,
6958    ) -> proto::ProjectTransaction {
6959        let mut serialized_transaction = proto::ProjectTransaction {
6960            buffer_ids: Default::default(),
6961            transactions: Default::default(),
6962        };
6963        for (buffer, transaction) in project_transaction.0 {
6964            serialized_transaction
6965                .buffer_ids
6966                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
6967            serialized_transaction
6968                .transactions
6969                .push(language::proto::serialize_transaction(&transaction));
6970        }
6971        serialized_transaction
6972    }
6973
6974    fn deserialize_project_transaction(
6975        &mut self,
6976        message: proto::ProjectTransaction,
6977        push_to_history: bool,
6978        cx: &mut ModelContext<Self>,
6979    ) -> Task<Result<ProjectTransaction>> {
6980        cx.spawn(|this, mut cx| async move {
6981            let mut project_transaction = ProjectTransaction::default();
6982            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
6983            {
6984                let buffer = this
6985                    .update(&mut cx, |this, cx| {
6986                        this.wait_for_remote_buffer(buffer_id, cx)
6987                    })
6988                    .await?;
6989                let transaction = language::proto::deserialize_transaction(transaction)?;
6990                project_transaction.0.insert(buffer, transaction);
6991            }
6992
6993            for (buffer, transaction) in &project_transaction.0 {
6994                buffer
6995                    .update(&mut cx, |buffer, _| {
6996                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
6997                    })
6998                    .await?;
6999
7000                if push_to_history {
7001                    buffer.update(&mut cx, |buffer, _| {
7002                        buffer.push_transaction(transaction.clone(), Instant::now());
7003                    });
7004                }
7005            }
7006
7007            Ok(project_transaction)
7008        })
7009    }
7010
7011    fn create_buffer_for_peer(
7012        &mut self,
7013        buffer: &ModelHandle<Buffer>,
7014        peer_id: proto::PeerId,
7015        cx: &mut AppContext,
7016    ) -> u64 {
7017        let buffer_id = buffer.read(cx).remote_id();
7018        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7019            updates_tx
7020                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7021                .ok();
7022        }
7023        buffer_id
7024    }
7025
7026    fn wait_for_remote_buffer(
7027        &mut self,
7028        id: u64,
7029        cx: &mut ModelContext<Self>,
7030    ) -> Task<Result<ModelHandle<Buffer>>> {
7031        let mut opened_buffer_rx = self.opened_buffer.1.clone();
7032
7033        cx.spawn_weak(|this, mut cx| async move {
7034            let buffer = loop {
7035                let Some(this) = this.upgrade(&cx) else {
7036                    return Err(anyhow!("project dropped"));
7037                };
7038
7039                let buffer = this.read_with(&cx, |this, cx| {
7040                    this.opened_buffers
7041                        .get(&id)
7042                        .and_then(|buffer| buffer.upgrade(cx))
7043                });
7044
7045                if let Some(buffer) = buffer {
7046                    break buffer;
7047                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
7048                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
7049                }
7050
7051                this.update(&mut cx, |this, _| {
7052                    this.incomplete_remote_buffers.entry(id).or_default();
7053                });
7054                drop(this);
7055
7056                opened_buffer_rx
7057                    .next()
7058                    .await
7059                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7060            };
7061
7062            Ok(buffer)
7063        })
7064    }
7065
7066    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7067        let project_id = match self.client_state.as_ref() {
7068            Some(ProjectClientState::Remote {
7069                sharing_has_stopped,
7070                remote_id,
7071                ..
7072            }) => {
7073                if *sharing_has_stopped {
7074                    return Task::ready(Err(anyhow!(
7075                        "can't synchronize remote buffers on a readonly project"
7076                    )));
7077                } else {
7078                    *remote_id
7079                }
7080            }
7081            Some(ProjectClientState::Local { .. }) | None => {
7082                return Task::ready(Err(anyhow!(
7083                    "can't synchronize remote buffers on a local project"
7084                )))
7085            }
7086        };
7087
7088        let client = self.client.clone();
7089        cx.spawn(|this, cx| async move {
7090            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
7091                let buffers = this
7092                    .opened_buffers
7093                    .iter()
7094                    .filter_map(|(id, buffer)| {
7095                        let buffer = buffer.upgrade(cx)?;
7096                        Some(proto::BufferVersion {
7097                            id: *id,
7098                            version: language::proto::serialize_version(&buffer.read(cx).version),
7099                        })
7100                    })
7101                    .collect();
7102                let incomplete_buffer_ids = this
7103                    .incomplete_remote_buffers
7104                    .keys()
7105                    .copied()
7106                    .collect::<Vec<_>>();
7107
7108                (buffers, incomplete_buffer_ids)
7109            });
7110            let response = client
7111                .request(proto::SynchronizeBuffers {
7112                    project_id,
7113                    buffers,
7114                })
7115                .await?;
7116
7117            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
7118                let client = client.clone();
7119                let buffer_id = buffer.id;
7120                let remote_version = language::proto::deserialize_version(&buffer.version);
7121                this.read_with(&cx, |this, cx| {
7122                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7123                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
7124                        cx.background().spawn(async move {
7125                            let operations = operations.await;
7126                            for chunk in split_operations(operations) {
7127                                client
7128                                    .request(proto::UpdateBuffer {
7129                                        project_id,
7130                                        buffer_id,
7131                                        operations: chunk,
7132                                    })
7133                                    .await?;
7134                            }
7135                            anyhow::Ok(())
7136                        })
7137                    } else {
7138                        Task::ready(Ok(()))
7139                    }
7140                })
7141            });
7142
7143            // Any incomplete buffers have open requests waiting. Request that the host sends
7144            // creates these buffers for us again to unblock any waiting futures.
7145            for id in incomplete_buffer_ids {
7146                cx.background()
7147                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
7148                    .detach();
7149            }
7150
7151            futures::future::join_all(send_updates_for_buffers)
7152                .await
7153                .into_iter()
7154                .collect()
7155        })
7156    }
7157
7158    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
7159        self.worktrees(cx)
7160            .map(|worktree| {
7161                let worktree = worktree.read(cx);
7162                proto::WorktreeMetadata {
7163                    id: worktree.id().to_proto(),
7164                    root_name: worktree.root_name().into(),
7165                    visible: worktree.is_visible(),
7166                    abs_path: worktree.abs_path().to_string_lossy().into(),
7167                }
7168            })
7169            .collect()
7170    }
7171
7172    fn set_worktrees_from_proto(
7173        &mut self,
7174        worktrees: Vec<proto::WorktreeMetadata>,
7175        cx: &mut ModelContext<Project>,
7176    ) -> Result<()> {
7177        let replica_id = self.replica_id();
7178        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
7179
7180        let mut old_worktrees_by_id = self
7181            .worktrees
7182            .drain(..)
7183            .filter_map(|worktree| {
7184                let worktree = worktree.upgrade(cx)?;
7185                Some((worktree.read(cx).id(), worktree))
7186            })
7187            .collect::<HashMap<_, _>>();
7188
7189        for worktree in worktrees {
7190            if let Some(old_worktree) =
7191                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
7192            {
7193                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
7194            } else {
7195                let worktree =
7196                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
7197                let _ = self.add_worktree(&worktree, cx);
7198            }
7199        }
7200
7201        self.metadata_changed(cx);
7202        for id in old_worktrees_by_id.keys() {
7203            cx.emit(Event::WorktreeRemoved(*id));
7204        }
7205
7206        Ok(())
7207    }
7208
7209    fn set_collaborators_from_proto(
7210        &mut self,
7211        messages: Vec<proto::Collaborator>,
7212        cx: &mut ModelContext<Self>,
7213    ) -> Result<()> {
7214        let mut collaborators = HashMap::default();
7215        for message in messages {
7216            let collaborator = Collaborator::from_proto(message)?;
7217            collaborators.insert(collaborator.peer_id, collaborator);
7218        }
7219        for old_peer_id in self.collaborators.keys() {
7220            if !collaborators.contains_key(old_peer_id) {
7221                cx.emit(Event::CollaboratorLeft(*old_peer_id));
7222            }
7223        }
7224        self.collaborators = collaborators;
7225        Ok(())
7226    }
7227
7228    fn deserialize_symbol(
7229        &self,
7230        serialized_symbol: proto::Symbol,
7231    ) -> impl Future<Output = Result<Symbol>> {
7232        let languages = self.languages.clone();
7233        async move {
7234            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
7235            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
7236            let start = serialized_symbol
7237                .start
7238                .ok_or_else(|| anyhow!("invalid start"))?;
7239            let end = serialized_symbol
7240                .end
7241                .ok_or_else(|| anyhow!("invalid end"))?;
7242            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
7243            let path = ProjectPath {
7244                worktree_id,
7245                path: PathBuf::from(serialized_symbol.path).into(),
7246            };
7247            let language = languages
7248                .language_for_file(&path.path, None)
7249                .await
7250                .log_err();
7251            Ok(Symbol {
7252                language_server_name: LanguageServerName(
7253                    serialized_symbol.language_server_name.into(),
7254                ),
7255                source_worktree_id,
7256                path,
7257                label: {
7258                    match language {
7259                        Some(language) => {
7260                            language
7261                                .label_for_symbol(&serialized_symbol.name, kind)
7262                                .await
7263                        }
7264                        None => None,
7265                    }
7266                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
7267                },
7268
7269                name: serialized_symbol.name,
7270                range: Unclipped(PointUtf16::new(start.row, start.column))
7271                    ..Unclipped(PointUtf16::new(end.row, end.column)),
7272                kind,
7273                signature: serialized_symbol
7274                    .signature
7275                    .try_into()
7276                    .map_err(|_| anyhow!("invalid signature"))?,
7277            })
7278        }
7279    }
7280
7281    async fn handle_buffer_saved(
7282        this: ModelHandle<Self>,
7283        envelope: TypedEnvelope<proto::BufferSaved>,
7284        _: Arc<Client>,
7285        mut cx: AsyncAppContext,
7286    ) -> Result<()> {
7287        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
7288        let version = deserialize_version(&envelope.payload.version);
7289        let mtime = envelope
7290            .payload
7291            .mtime
7292            .ok_or_else(|| anyhow!("missing mtime"))?
7293            .into();
7294
7295        this.update(&mut cx, |this, cx| {
7296            let buffer = this
7297                .opened_buffers
7298                .get(&envelope.payload.buffer_id)
7299                .and_then(|buffer| buffer.upgrade(cx))
7300                .or_else(|| {
7301                    this.incomplete_remote_buffers
7302                        .get(&envelope.payload.buffer_id)
7303                        .and_then(|b| b.clone())
7304                });
7305            if let Some(buffer) = buffer {
7306                buffer.update(cx, |buffer, cx| {
7307                    buffer.did_save(version, fingerprint, mtime, cx);
7308                });
7309            }
7310            Ok(())
7311        })
7312    }
7313
7314    async fn handle_buffer_reloaded(
7315        this: ModelHandle<Self>,
7316        envelope: TypedEnvelope<proto::BufferReloaded>,
7317        _: Arc<Client>,
7318        mut cx: AsyncAppContext,
7319    ) -> Result<()> {
7320        let payload = envelope.payload;
7321        let version = deserialize_version(&payload.version);
7322        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
7323        let line_ending = deserialize_line_ending(
7324            proto::LineEnding::from_i32(payload.line_ending)
7325                .ok_or_else(|| anyhow!("missing line ending"))?,
7326        );
7327        let mtime = payload
7328            .mtime
7329            .ok_or_else(|| anyhow!("missing mtime"))?
7330            .into();
7331        this.update(&mut cx, |this, cx| {
7332            let buffer = this
7333                .opened_buffers
7334                .get(&payload.buffer_id)
7335                .and_then(|buffer| buffer.upgrade(cx))
7336                .or_else(|| {
7337                    this.incomplete_remote_buffers
7338                        .get(&payload.buffer_id)
7339                        .cloned()
7340                        .flatten()
7341                });
7342            if let Some(buffer) = buffer {
7343                buffer.update(cx, |buffer, cx| {
7344                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
7345                });
7346            }
7347            Ok(())
7348        })
7349    }
7350
7351    #[allow(clippy::type_complexity)]
7352    fn edits_from_lsp(
7353        &mut self,
7354        buffer: &ModelHandle<Buffer>,
7355        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
7356        server_id: LanguageServerId,
7357        version: Option<i32>,
7358        cx: &mut ModelContext<Self>,
7359    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
7360        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
7361        cx.background().spawn(async move {
7362            let snapshot = snapshot?;
7363            let mut lsp_edits = lsp_edits
7364                .into_iter()
7365                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
7366                .collect::<Vec<_>>();
7367            lsp_edits.sort_by_key(|(range, _)| range.start);
7368
7369            let mut lsp_edits = lsp_edits.into_iter().peekable();
7370            let mut edits = Vec::new();
7371            while let Some((range, mut new_text)) = lsp_edits.next() {
7372                // Clip invalid ranges provided by the language server.
7373                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
7374                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
7375
7376                // Combine any LSP edits that are adjacent.
7377                //
7378                // Also, combine LSP edits that are separated from each other by only
7379                // a newline. This is important because for some code actions,
7380                // Rust-analyzer rewrites the entire buffer via a series of edits that
7381                // are separated by unchanged newline characters.
7382                //
7383                // In order for the diffing logic below to work properly, any edits that
7384                // cancel each other out must be combined into one.
7385                while let Some((next_range, next_text)) = lsp_edits.peek() {
7386                    if next_range.start.0 > range.end {
7387                        if next_range.start.0.row > range.end.row + 1
7388                            || next_range.start.0.column > 0
7389                            || snapshot.clip_point_utf16(
7390                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
7391                                Bias::Left,
7392                            ) > range.end
7393                        {
7394                            break;
7395                        }
7396                        new_text.push('\n');
7397                    }
7398                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
7399                    new_text.push_str(next_text);
7400                    lsp_edits.next();
7401                }
7402
7403                // For multiline edits, perform a diff of the old and new text so that
7404                // we can identify the changes more precisely, preserving the locations
7405                // of any anchors positioned in the unchanged regions.
7406                if range.end.row > range.start.row {
7407                    let mut offset = range.start.to_offset(&snapshot);
7408                    let old_text = snapshot.text_for_range(range).collect::<String>();
7409
7410                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
7411                    let mut moved_since_edit = true;
7412                    for change in diff.iter_all_changes() {
7413                        let tag = change.tag();
7414                        let value = change.value();
7415                        match tag {
7416                            ChangeTag::Equal => {
7417                                offset += value.len();
7418                                moved_since_edit = true;
7419                            }
7420                            ChangeTag::Delete => {
7421                                let start = snapshot.anchor_after(offset);
7422                                let end = snapshot.anchor_before(offset + value.len());
7423                                if moved_since_edit {
7424                                    edits.push((start..end, String::new()));
7425                                } else {
7426                                    edits.last_mut().unwrap().0.end = end;
7427                                }
7428                                offset += value.len();
7429                                moved_since_edit = false;
7430                            }
7431                            ChangeTag::Insert => {
7432                                if moved_since_edit {
7433                                    let anchor = snapshot.anchor_after(offset);
7434                                    edits.push((anchor..anchor, value.to_string()));
7435                                } else {
7436                                    edits.last_mut().unwrap().1.push_str(value);
7437                                }
7438                                moved_since_edit = false;
7439                            }
7440                        }
7441                    }
7442                } else if range.end == range.start {
7443                    let anchor = snapshot.anchor_after(range.start);
7444                    edits.push((anchor..anchor, new_text));
7445                } else {
7446                    let edit_start = snapshot.anchor_after(range.start);
7447                    let edit_end = snapshot.anchor_before(range.end);
7448                    edits.push((edit_start..edit_end, new_text));
7449                }
7450            }
7451
7452            Ok(edits)
7453        })
7454    }
7455
7456    fn buffer_snapshot_for_lsp_version(
7457        &mut self,
7458        buffer: &ModelHandle<Buffer>,
7459        server_id: LanguageServerId,
7460        version: Option<i32>,
7461        cx: &AppContext,
7462    ) -> Result<TextBufferSnapshot> {
7463        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
7464
7465        if let Some(version) = version {
7466            let buffer_id = buffer.read(cx).remote_id();
7467            let snapshots = self
7468                .buffer_snapshots
7469                .get_mut(&buffer_id)
7470                .and_then(|m| m.get_mut(&server_id))
7471                .ok_or_else(|| {
7472                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
7473                })?;
7474
7475            let found_snapshot = snapshots
7476                .binary_search_by_key(&version, |e| e.version)
7477                .map(|ix| snapshots[ix].snapshot.clone())
7478                .map_err(|_| {
7479                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
7480                })?;
7481
7482            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
7483            Ok(found_snapshot)
7484        } else {
7485            Ok((buffer.read(cx)).text_snapshot())
7486        }
7487    }
7488
7489    pub fn language_servers(
7490        &self,
7491    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
7492        self.language_server_ids
7493            .iter()
7494            .map(|((worktree_id, server_name), server_id)| {
7495                (*server_id, server_name.clone(), *worktree_id)
7496            })
7497    }
7498
7499    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7500        if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
7501            Some(server.clone())
7502        } else {
7503            None
7504        }
7505    }
7506
7507    pub fn language_servers_for_buffer(
7508        &self,
7509        buffer: &Buffer,
7510        cx: &AppContext,
7511    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7512        self.language_server_ids_for_buffer(buffer, cx)
7513            .into_iter()
7514            .filter_map(|server_id| {
7515                if let LanguageServerState::Running {
7516                    adapter, server, ..
7517                } = self.language_servers.get(&server_id)?
7518                {
7519                    Some((adapter, server))
7520                } else {
7521                    None
7522                }
7523            })
7524    }
7525
7526    fn primary_language_servers_for_buffer(
7527        &self,
7528        buffer: &Buffer,
7529        cx: &AppContext,
7530    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7531        self.language_servers_for_buffer(buffer, cx).next()
7532    }
7533
7534    fn language_server_for_buffer(
7535        &self,
7536        buffer: &Buffer,
7537        server_id: LanguageServerId,
7538        cx: &AppContext,
7539    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7540        self.language_servers_for_buffer(buffer, cx)
7541            .find(|(_, s)| s.server_id() == server_id)
7542    }
7543
7544    fn language_server_ids_for_buffer(
7545        &self,
7546        buffer: &Buffer,
7547        cx: &AppContext,
7548    ) -> Vec<LanguageServerId> {
7549        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
7550            let worktree_id = file.worktree_id(cx);
7551            language
7552                .lsp_adapters()
7553                .iter()
7554                .flat_map(|adapter| {
7555                    let key = (worktree_id, adapter.name.clone());
7556                    self.language_server_ids.get(&key).copied()
7557                })
7558                .collect()
7559        } else {
7560            Vec::new()
7561        }
7562    }
7563}
7564
7565fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
7566    let mut literal_end = 0;
7567    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
7568        if part.contains(&['*', '?', '{', '}']) {
7569            break;
7570        } else {
7571            if i > 0 {
7572                // Acount for separator prior to this part
7573                literal_end += path::MAIN_SEPARATOR.len_utf8();
7574            }
7575            literal_end += part.len();
7576        }
7577    }
7578    &glob[..literal_end]
7579}
7580
7581impl WorktreeHandle {
7582    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
7583        match self {
7584            WorktreeHandle::Strong(handle) => Some(handle.clone()),
7585            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
7586        }
7587    }
7588
7589    pub fn handle_id(&self) -> usize {
7590        match self {
7591            WorktreeHandle::Strong(handle) => handle.id(),
7592            WorktreeHandle::Weak(handle) => handle.id(),
7593        }
7594    }
7595}
7596
7597impl OpenBuffer {
7598    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
7599        match self {
7600            OpenBuffer::Strong(handle) => Some(handle.clone()),
7601            OpenBuffer::Weak(handle) => handle.upgrade(cx),
7602            OpenBuffer::Operations(_) => None,
7603        }
7604    }
7605}
7606
7607pub struct PathMatchCandidateSet {
7608    pub snapshot: Snapshot,
7609    pub include_ignored: bool,
7610    pub include_root_name: bool,
7611}
7612
7613impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
7614    type Candidates = PathMatchCandidateSetIter<'a>;
7615
7616    fn id(&self) -> usize {
7617        self.snapshot.id().to_usize()
7618    }
7619
7620    fn len(&self) -> usize {
7621        if self.include_ignored {
7622            self.snapshot.file_count()
7623        } else {
7624            self.snapshot.visible_file_count()
7625        }
7626    }
7627
7628    fn prefix(&self) -> Arc<str> {
7629        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
7630            self.snapshot.root_name().into()
7631        } else if self.include_root_name {
7632            format!("{}/", self.snapshot.root_name()).into()
7633        } else {
7634            "".into()
7635        }
7636    }
7637
7638    fn candidates(&'a self, start: usize) -> Self::Candidates {
7639        PathMatchCandidateSetIter {
7640            traversal: self.snapshot.files(self.include_ignored, start),
7641        }
7642    }
7643}
7644
7645pub struct PathMatchCandidateSetIter<'a> {
7646    traversal: Traversal<'a>,
7647}
7648
7649impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
7650    type Item = fuzzy::PathMatchCandidate<'a>;
7651
7652    fn next(&mut self) -> Option<Self::Item> {
7653        self.traversal.next().map(|entry| {
7654            if let EntryKind::File(char_bag) = entry.kind {
7655                fuzzy::PathMatchCandidate {
7656                    path: &entry.path,
7657                    char_bag,
7658                }
7659            } else {
7660                unreachable!()
7661            }
7662        })
7663    }
7664}
7665
7666impl Entity for Project {
7667    type Event = Event;
7668
7669    fn release(&mut self, cx: &mut gpui::AppContext) {
7670        match &self.client_state {
7671            Some(ProjectClientState::Local { .. }) => {
7672                let _ = self.unshare_internal(cx);
7673            }
7674            Some(ProjectClientState::Remote { remote_id, .. }) => {
7675                let _ = self.client.send(proto::LeaveProject {
7676                    project_id: *remote_id,
7677                });
7678                self.disconnected_from_host_internal(cx);
7679            }
7680            _ => {}
7681        }
7682    }
7683
7684    fn app_will_quit(
7685        &mut self,
7686        _: &mut AppContext,
7687    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
7688        let shutdown_futures = self
7689            .language_servers
7690            .drain()
7691            .map(|(_, server_state)| async {
7692                use LanguageServerState::*;
7693                match server_state {
7694                    Running { server, .. } => server.shutdown()?.await,
7695                    Starting(task) => task.await?.shutdown()?.await,
7696                }
7697            })
7698            .collect::<Vec<_>>();
7699
7700        Some(
7701            async move {
7702                futures::future::join_all(shutdown_futures).await;
7703            }
7704            .boxed(),
7705        )
7706    }
7707}
7708
7709impl Collaborator {
7710    fn from_proto(message: proto::Collaborator) -> Result<Self> {
7711        Ok(Self {
7712            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
7713            replica_id: message.replica_id as ReplicaId,
7714        })
7715    }
7716}
7717
7718impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
7719    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
7720        Self {
7721            worktree_id,
7722            path: path.as_ref().into(),
7723        }
7724    }
7725}
7726
7727impl ProjectLspAdapterDelegate {
7728    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
7729        Arc::new(Self {
7730            project: cx.handle(),
7731            http_client: project.client.http_client(),
7732        })
7733    }
7734}
7735
7736impl LspAdapterDelegate for ProjectLspAdapterDelegate {
7737    fn show_notification(&self, message: &str, cx: &mut AppContext) {
7738        self.project
7739            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
7740    }
7741
7742    fn http_client(&self) -> Arc<dyn HttpClient> {
7743        self.http_client.clone()
7744    }
7745}
7746
7747fn split_operations(
7748    mut operations: Vec<proto::Operation>,
7749) -> impl Iterator<Item = Vec<proto::Operation>> {
7750    #[cfg(any(test, feature = "test-support"))]
7751    const CHUNK_SIZE: usize = 5;
7752
7753    #[cfg(not(any(test, feature = "test-support")))]
7754    const CHUNK_SIZE: usize = 100;
7755
7756    let mut done = false;
7757    std::iter::from_fn(move || {
7758        if done {
7759            return None;
7760        }
7761
7762        let operations = operations
7763            .drain(..cmp::min(CHUNK_SIZE, operations.len()))
7764            .collect::<Vec<_>>();
7765        if operations.is_empty() {
7766            done = true;
7767        }
7768        Some(operations)
7769    })
7770}
7771
7772fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
7773    proto::Symbol {
7774        language_server_name: symbol.language_server_name.0.to_string(),
7775        source_worktree_id: symbol.source_worktree_id.to_proto(),
7776        worktree_id: symbol.path.worktree_id.to_proto(),
7777        path: symbol.path.path.to_string_lossy().to_string(),
7778        name: symbol.name.clone(),
7779        kind: unsafe { mem::transmute(symbol.kind) },
7780        start: Some(proto::PointUtf16 {
7781            row: symbol.range.start.0.row,
7782            column: symbol.range.start.0.column,
7783        }),
7784        end: Some(proto::PointUtf16 {
7785            row: symbol.range.end.0.row,
7786            column: symbol.range.end.0.column,
7787        }),
7788        signature: symbol.signature.to_vec(),
7789    }
7790}
7791
7792fn relativize_path(base: &Path, path: &Path) -> PathBuf {
7793    let mut path_components = path.components();
7794    let mut base_components = base.components();
7795    let mut components: Vec<Component> = Vec::new();
7796    loop {
7797        match (path_components.next(), base_components.next()) {
7798            (None, None) => break,
7799            (Some(a), None) => {
7800                components.push(a);
7801                components.extend(path_components.by_ref());
7802                break;
7803            }
7804            (None, _) => components.push(Component::ParentDir),
7805            (Some(a), Some(b)) if components.is_empty() && a == b => (),
7806            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
7807            (Some(a), Some(_)) => {
7808                components.push(Component::ParentDir);
7809                for _ in base_components {
7810                    components.push(Component::ParentDir);
7811                }
7812                components.push(a);
7813                components.extend(path_components.by_ref());
7814                break;
7815            }
7816        }
7817    }
7818    components.iter().map(|c| c.as_os_str()).collect()
7819}
7820
7821impl Item for Buffer {
7822    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
7823        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
7824    }
7825
7826    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
7827        File::from_dyn(self.file()).map(|file| ProjectPath {
7828            worktree_id: file.worktree_id(cx),
7829            path: file.path().clone(),
7830        })
7831    }
7832}
7833
7834async fn wait_for_loading_buffer(
7835    mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
7836) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
7837    loop {
7838        if let Some(result) = receiver.borrow().as_ref() {
7839            match result {
7840                Ok(buffer) => return Ok(buffer.to_owned()),
7841                Err(e) => return Err(e.to_owned()),
7842            }
7843        }
7844        receiver.next().await;
7845    }
7846}