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