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