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