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, paths::LOCAL_SETTINGS_RELATIVE_PATH, post_inc, ResultExt,
  82    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.update_initialization_overrides(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        adapter.update_initialization_overrides(override_options.as_ref());
2549
2550        let server_id = pending_server.server_id;
2551        let container_dir = pending_server.container_dir.clone();
2552        let state = LanguageServerState::Starting({
2553            let adapter = adapter.clone();
2554            let initialization_options = adapter.initialization_options();
2555            let server_name = adapter.name.0.clone();
2556            let languages = self.languages.clone();
2557            let language = language.clone();
2558            let key = key.clone();
2559
2560            cx.spawn_weak(|this, mut cx| async move {
2561                let result = Self::setup_and_insert_language_server(
2562                    this,
2563                    initialization_options,
2564                    pending_server,
2565                    adapter.clone(),
2566                    languages,
2567                    language.clone(),
2568                    server_id,
2569                    key,
2570                    &mut cx,
2571                )
2572                .await;
2573
2574                match result {
2575                    Ok(server) => server,
2576
2577                    Err(err) => {
2578                        log::error!("failed to start language server {:?}: {}", server_name, err);
2579
2580                        if let Some(this) = this.upgrade(&cx) {
2581                            if let Some(container_dir) = container_dir {
2582                                let installation_test_binary = adapter
2583                                    .installation_test_binary(container_dir.to_path_buf())
2584                                    .await;
2585
2586                                this.update(&mut cx, |_, cx| {
2587                                    Self::check_errored_server(
2588                                        language,
2589                                        adapter,
2590                                        server_id,
2591                                        installation_test_binary,
2592                                        cx,
2593                                    )
2594                                });
2595                            }
2596                        }
2597
2598                        None
2599                    }
2600                }
2601            })
2602        });
2603
2604        self.language_servers.insert(server_id, state);
2605        self.language_server_ids.insert(key, server_id);
2606    }
2607
2608    fn reinstall_language_server(
2609        &mut self,
2610        language: Arc<Language>,
2611        adapter: Arc<CachedLspAdapter>,
2612        server_id: LanguageServerId,
2613        cx: &mut ModelContext<Self>,
2614    ) -> Option<Task<()>> {
2615        log::info!("beginning to reinstall server");
2616
2617        let existing_server = match self.language_servers.remove(&server_id) {
2618            Some(LanguageServerState::Running { server, .. }) => Some(server),
2619            _ => None,
2620        };
2621
2622        for worktree in &self.worktrees {
2623            if let Some(worktree) = worktree.upgrade(cx) {
2624                let key = (worktree.read(cx).id(), adapter.name.clone());
2625                self.language_server_ids.remove(&key);
2626            }
2627        }
2628
2629        Some(cx.spawn(move |this, mut cx| async move {
2630            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2631                log::info!("shutting down existing server");
2632                task.await;
2633            }
2634
2635            // TODO: This is race-safe with regards to preventing new instances from
2636            // starting while deleting, but existing instances in other projects are going
2637            // to be very confused and messed up
2638            this.update(&mut cx, |this, cx| {
2639                this.languages.delete_server_container(adapter.clone(), cx)
2640            })
2641            .await;
2642
2643            this.update(&mut cx, |this, mut cx| {
2644                let worktrees = this.worktrees.clone();
2645                for worktree in worktrees {
2646                    let worktree = match worktree.upgrade(cx) {
2647                        Some(worktree) => worktree.read(cx),
2648                        None => continue,
2649                    };
2650                    let worktree_id = worktree.id();
2651                    let root_path = worktree.abs_path();
2652
2653                    this.start_language_server(
2654                        worktree_id,
2655                        root_path,
2656                        adapter.clone(),
2657                        language.clone(),
2658                        &mut cx,
2659                    );
2660                }
2661            })
2662        }))
2663    }
2664
2665    async fn setup_and_insert_language_server(
2666        this: WeakModelHandle<Self>,
2667        initialization_options: Option<serde_json::Value>,
2668        pending_server: PendingLanguageServer,
2669        adapter: Arc<CachedLspAdapter>,
2670        languages: Arc<LanguageRegistry>,
2671        language: Arc<Language>,
2672        server_id: LanguageServerId,
2673        key: (WorktreeId, LanguageServerName),
2674        cx: &mut AsyncAppContext,
2675    ) -> Result<Option<Arc<LanguageServer>>> {
2676        let setup = Self::setup_pending_language_server(
2677            this,
2678            initialization_options,
2679            pending_server,
2680            adapter.clone(),
2681            languages,
2682            server_id,
2683            cx,
2684        );
2685
2686        let language_server = match setup.await? {
2687            Some(language_server) => language_server,
2688            None => return Ok(None),
2689        };
2690
2691        let this = match this.upgrade(cx) {
2692            Some(this) => this,
2693            None => return Err(anyhow!("failed to upgrade project handle")),
2694        };
2695
2696        this.update(cx, |this, cx| {
2697            this.insert_newly_running_language_server(
2698                language,
2699                adapter,
2700                language_server.clone(),
2701                server_id,
2702                key,
2703                cx,
2704            )
2705        })?;
2706
2707        Ok(Some(language_server))
2708    }
2709
2710    async fn setup_pending_language_server(
2711        this: WeakModelHandle<Self>,
2712        initialization_options: Option<serde_json::Value>,
2713        pending_server: PendingLanguageServer,
2714        adapter: Arc<CachedLspAdapter>,
2715        languages: Arc<LanguageRegistry>,
2716        server_id: LanguageServerId,
2717        cx: &mut AsyncAppContext,
2718    ) -> Result<Option<Arc<LanguageServer>>> {
2719        let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2720        let language_server = match pending_server.task.await? {
2721            Some(server) => server.initialize(initialization_options).await?,
2722            None => {
2723                return Ok(None);
2724            }
2725        };
2726
2727        language_server
2728            .on_notification::<lsp::notification::LogMessage, _>({
2729                move |params, mut cx| {
2730                    if let Some(this) = this.upgrade(&cx) {
2731                        this.update(&mut cx, |_, cx| {
2732                            cx.emit(Event::LanguageServerLog(server_id, params.message))
2733                        });
2734                    }
2735                }
2736            })
2737            .detach();
2738
2739        language_server
2740            .on_notification::<lsp::notification::PublishDiagnostics, _>({
2741                let adapter = adapter.clone();
2742                move |mut params, cx| {
2743                    let this = this;
2744                    let adapter = adapter.clone();
2745                    cx.spawn(|mut cx| async move {
2746                        adapter.process_diagnostics(&mut params).await;
2747                        if let Some(this) = this.upgrade(&cx) {
2748                            this.update(&mut cx, |this, cx| {
2749                                this.update_diagnostics(
2750                                    server_id,
2751                                    params,
2752                                    &adapter.disk_based_diagnostic_sources,
2753                                    cx,
2754                                )
2755                                .log_err();
2756                            });
2757                        }
2758                    })
2759                    .detach();
2760                }
2761            })
2762            .detach();
2763
2764        language_server
2765            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2766                let languages = languages.clone();
2767                move |params, mut cx| {
2768                    let languages = languages.clone();
2769                    async move {
2770                        let workspace_config =
2771                            cx.update(|cx| languages.workspace_configuration(cx)).await;
2772                        Ok(params
2773                            .items
2774                            .into_iter()
2775                            .map(|item| {
2776                                if let Some(section) = &item.section {
2777                                    workspace_config
2778                                        .get(section)
2779                                        .cloned()
2780                                        .unwrap_or(serde_json::Value::Null)
2781                                } else {
2782                                    workspace_config.clone()
2783                                }
2784                            })
2785                            .collect())
2786                    }
2787                }
2788            })
2789            .detach();
2790
2791        // Even though we don't have handling for these requests, respond to them to
2792        // avoid stalling any language server like `gopls` which waits for a response
2793        // to these requests when initializing.
2794        language_server
2795            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>(
2796                move |params, mut cx| async move {
2797                    if let Some(this) = this.upgrade(&cx) {
2798                        this.update(&mut cx, |this, _| {
2799                            if let Some(status) = this.language_server_statuses.get_mut(&server_id)
2800                            {
2801                                if let lsp::NumberOrString::String(token) = params.token {
2802                                    status.progress_tokens.insert(token);
2803                                }
2804                            }
2805                        });
2806                    }
2807                    Ok(())
2808                },
2809            )
2810            .detach();
2811        language_server
2812            .on_request::<lsp::request::RegisterCapability, _, _>({
2813                move |params, mut cx| async move {
2814                    let this = this
2815                        .upgrade(&cx)
2816                        .ok_or_else(|| anyhow!("project dropped"))?;
2817                    for reg in params.registrations {
2818                        if reg.method == "workspace/didChangeWatchedFiles" {
2819                            if let Some(options) = reg.register_options {
2820                                let options = serde_json::from_value(options)?;
2821                                this.update(&mut cx, |this, cx| {
2822                                    this.on_lsp_did_change_watched_files(server_id, options, cx);
2823                                });
2824                            }
2825                        }
2826                    }
2827                    Ok(())
2828                }
2829            })
2830            .detach();
2831
2832        language_server
2833            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2834                let adapter = adapter.clone();
2835                move |params, cx| {
2836                    Self::on_lsp_workspace_edit(this, params, server_id, adapter.clone(), cx)
2837                }
2838            })
2839            .detach();
2840
2841        language_server
2842            .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
2843                move |(), mut cx| async move {
2844                    let this = this
2845                        .upgrade(&cx)
2846                        .ok_or_else(|| anyhow!("project dropped"))?;
2847                    this.update(&mut cx, |project, cx| {
2848                        cx.emit(Event::RefreshInlays);
2849                        project.remote_id().map(|project_id| {
2850                            project.client.send(proto::RefreshInlayHints { project_id })
2851                        })
2852                    })
2853                    .transpose()?;
2854                    Ok(())
2855                }
2856            })
2857            .detach();
2858
2859        let disk_based_diagnostics_progress_token =
2860            adapter.disk_based_diagnostics_progress_token.clone();
2861
2862        language_server
2863            .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
2864                if let Some(this) = this.upgrade(&cx) {
2865                    this.update(&mut cx, |this, cx| {
2866                        this.on_lsp_progress(
2867                            params,
2868                            server_id,
2869                            disk_based_diagnostics_progress_token.clone(),
2870                            cx,
2871                        );
2872                    });
2873                }
2874            })
2875            .detach();
2876
2877        language_server
2878            .notify::<lsp::notification::DidChangeConfiguration>(
2879                lsp::DidChangeConfigurationParams {
2880                    settings: workspace_config,
2881                },
2882            )
2883            .ok();
2884
2885        Ok(Some(language_server))
2886    }
2887
2888    fn insert_newly_running_language_server(
2889        &mut self,
2890        language: Arc<Language>,
2891        adapter: Arc<CachedLspAdapter>,
2892        language_server: Arc<LanguageServer>,
2893        server_id: LanguageServerId,
2894        key: (WorktreeId, LanguageServerName),
2895        cx: &mut ModelContext<Self>,
2896    ) -> Result<()> {
2897        // If the language server for this key doesn't match the server id, don't store the
2898        // server. Which will cause it to be dropped, killing the process
2899        if self
2900            .language_server_ids
2901            .get(&key)
2902            .map(|id| id != &server_id)
2903            .unwrap_or(false)
2904        {
2905            return Ok(());
2906        }
2907
2908        // Update language_servers collection with Running variant of LanguageServerState
2909        // indicating that the server is up and running and ready
2910        self.language_servers.insert(
2911            server_id,
2912            LanguageServerState::Running {
2913                adapter: adapter.clone(),
2914                language: language.clone(),
2915                watched_paths: Default::default(),
2916                server: language_server.clone(),
2917                simulate_disk_based_diagnostics_completion: None,
2918            },
2919        );
2920
2921        self.language_server_statuses.insert(
2922            server_id,
2923            LanguageServerStatus {
2924                name: language_server.name().to_string(),
2925                pending_work: Default::default(),
2926                has_pending_diagnostic_updates: false,
2927                progress_tokens: Default::default(),
2928            },
2929        );
2930
2931        cx.emit(Event::LanguageServerAdded(server_id));
2932
2933        if let Some(project_id) = self.remote_id() {
2934            self.client.send(proto::StartLanguageServer {
2935                project_id,
2936                server: Some(proto::LanguageServer {
2937                    id: server_id.0 as u64,
2938                    name: language_server.name().to_string(),
2939                }),
2940            })?;
2941        }
2942
2943        // Tell the language server about every open buffer in the worktree that matches the language.
2944        for buffer in self.opened_buffers.values() {
2945            if let Some(buffer_handle) = buffer.upgrade(cx) {
2946                let buffer = buffer_handle.read(cx);
2947                let file = match File::from_dyn(buffer.file()) {
2948                    Some(file) => file,
2949                    None => continue,
2950                };
2951                let language = match buffer.language() {
2952                    Some(language) => language,
2953                    None => continue,
2954                };
2955
2956                if file.worktree.read(cx).id() != key.0
2957                    || !language.lsp_adapters().iter().any(|a| a.name == key.1)
2958                {
2959                    continue;
2960                }
2961
2962                let file = match file.as_local() {
2963                    Some(file) => file,
2964                    None => continue,
2965                };
2966
2967                let versions = self
2968                    .buffer_snapshots
2969                    .entry(buffer.remote_id())
2970                    .or_default()
2971                    .entry(server_id)
2972                    .or_insert_with(|| {
2973                        vec![LspBufferSnapshot {
2974                            version: 0,
2975                            snapshot: buffer.text_snapshot(),
2976                        }]
2977                    });
2978
2979                let snapshot = versions.last().unwrap();
2980                let version = snapshot.version;
2981                let initial_snapshot = &snapshot.snapshot;
2982                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2983                language_server.notify::<lsp::notification::DidOpenTextDocument>(
2984                    lsp::DidOpenTextDocumentParams {
2985                        text_document: lsp::TextDocumentItem::new(
2986                            uri,
2987                            adapter
2988                                .language_ids
2989                                .get(language.name().as_ref())
2990                                .cloned()
2991                                .unwrap_or_default(),
2992                            version,
2993                            initial_snapshot.text(),
2994                        ),
2995                    },
2996                )?;
2997
2998                buffer_handle.update(cx, |buffer, cx| {
2999                    buffer.set_completion_triggers(
3000                        language_server
3001                            .capabilities()
3002                            .completion_provider
3003                            .as_ref()
3004                            .and_then(|provider| provider.trigger_characters.clone())
3005                            .unwrap_or_default(),
3006                        cx,
3007                    )
3008                });
3009            }
3010        }
3011
3012        cx.notify();
3013        Ok(())
3014    }
3015
3016    // Returns a list of all of the worktrees which no longer have a language server and the root path
3017    // for the stopped server
3018    fn stop_language_server(
3019        &mut self,
3020        worktree_id: WorktreeId,
3021        adapter_name: LanguageServerName,
3022        cx: &mut ModelContext<Self>,
3023    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
3024        let key = (worktree_id, adapter_name);
3025        if let Some(server_id) = self.language_server_ids.remove(&key) {
3026            // Remove other entries for this language server as well
3027            let mut orphaned_worktrees = vec![worktree_id];
3028            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3029            for other_key in other_keys {
3030                if self.language_server_ids.get(&other_key) == Some(&server_id) {
3031                    self.language_server_ids.remove(&other_key);
3032                    orphaned_worktrees.push(other_key.0);
3033                }
3034            }
3035
3036            for buffer in self.opened_buffers.values() {
3037                if let Some(buffer) = buffer.upgrade(cx) {
3038                    buffer.update(cx, |buffer, cx| {
3039                        buffer.update_diagnostics(server_id, Default::default(), cx);
3040                    });
3041                }
3042            }
3043            for worktree in &self.worktrees {
3044                if let Some(worktree) = worktree.upgrade(cx) {
3045                    worktree.update(cx, |worktree, cx| {
3046                        if let Some(worktree) = worktree.as_local_mut() {
3047                            worktree.clear_diagnostics_for_language_server(server_id, cx);
3048                        }
3049                    });
3050                }
3051            }
3052
3053            self.language_server_statuses.remove(&server_id);
3054            cx.notify();
3055
3056            let server_state = self.language_servers.remove(&server_id);
3057            cx.emit(Event::LanguageServerRemoved(server_id));
3058            cx.spawn_weak(|this, mut cx| async move {
3059                let mut root_path = None;
3060
3061                let server = match server_state {
3062                    Some(LanguageServerState::Starting(task)) => task.await,
3063                    Some(LanguageServerState::Running { server, .. }) => Some(server),
3064                    None => None,
3065                };
3066
3067                if let Some(server) = server {
3068                    root_path = Some(server.root_path().clone());
3069                    if let Some(shutdown) = server.shutdown() {
3070                        shutdown.await;
3071                    }
3072                }
3073
3074                if let Some(this) = this.upgrade(&cx) {
3075                    this.update(&mut cx, |this, cx| {
3076                        this.language_server_statuses.remove(&server_id);
3077                        cx.notify();
3078                    });
3079                }
3080
3081                (root_path, orphaned_worktrees)
3082            })
3083        } else {
3084            Task::ready((None, Vec::new()))
3085        }
3086    }
3087
3088    pub fn restart_language_servers_for_buffers(
3089        &mut self,
3090        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
3091        cx: &mut ModelContext<Self>,
3092    ) -> Option<()> {
3093        let language_server_lookup_info: HashSet<(ModelHandle<Worktree>, Arc<Language>)> = buffers
3094            .into_iter()
3095            .filter_map(|buffer| {
3096                let buffer = buffer.read(cx);
3097                let file = File::from_dyn(buffer.file())?;
3098                let full_path = file.full_path(cx);
3099                let language = self
3100                    .languages
3101                    .language_for_file(&full_path, Some(buffer.as_rope()))
3102                    .now_or_never()?
3103                    .ok()?;
3104                Some((file.worktree.clone(), language))
3105            })
3106            .collect();
3107        for (worktree, language) in language_server_lookup_info {
3108            self.restart_language_servers(worktree, language, cx);
3109        }
3110
3111        None
3112    }
3113
3114    // TODO This will break in the case where the adapter's root paths and worktrees are not equal
3115    fn restart_language_servers(
3116        &mut self,
3117        worktree: ModelHandle<Worktree>,
3118        language: Arc<Language>,
3119        cx: &mut ModelContext<Self>,
3120    ) {
3121        let worktree_id = worktree.read(cx).id();
3122        let fallback_path = worktree.read(cx).abs_path();
3123
3124        let mut stops = Vec::new();
3125        for adapter in language.lsp_adapters() {
3126            stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
3127        }
3128
3129        if stops.is_empty() {
3130            return;
3131        }
3132        let mut stops = stops.into_iter();
3133
3134        cx.spawn_weak(|this, mut cx| async move {
3135            let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
3136            for stop in stops {
3137                let (_, worktrees) = stop.await;
3138                orphaned_worktrees.extend_from_slice(&worktrees);
3139            }
3140
3141            let this = match this.upgrade(&cx) {
3142                Some(this) => this,
3143                None => return,
3144            };
3145
3146            this.update(&mut cx, |this, cx| {
3147                // Attempt to restart using original server path. Fallback to passed in
3148                // path if we could not retrieve the root path
3149                let root_path = original_root_path
3150                    .map(|path_buf| Arc::from(path_buf.as_path()))
3151                    .unwrap_or(fallback_path);
3152
3153                this.start_language_servers(&worktree, root_path, language.clone(), cx);
3154
3155                // Lookup new server ids and set them for each of the orphaned worktrees
3156                for adapter in language.lsp_adapters() {
3157                    if let Some(new_server_id) = this
3158                        .language_server_ids
3159                        .get(&(worktree_id, adapter.name.clone()))
3160                        .cloned()
3161                    {
3162                        for &orphaned_worktree in &orphaned_worktrees {
3163                            this.language_server_ids
3164                                .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
3165                        }
3166                    }
3167                }
3168            });
3169        })
3170        .detach();
3171    }
3172
3173    fn check_errored_server(
3174        language: Arc<Language>,
3175        adapter: Arc<CachedLspAdapter>,
3176        server_id: LanguageServerId,
3177        installation_test_binary: Option<LanguageServerBinary>,
3178        cx: &mut ModelContext<Self>,
3179    ) {
3180        if !adapter.can_be_reinstalled() {
3181            log::info!(
3182                "Validation check requested for {:?} but it cannot be reinstalled",
3183                adapter.name.0
3184            );
3185            return;
3186        }
3187
3188        cx.spawn(|this, mut cx| async move {
3189            log::info!("About to spawn test binary");
3190
3191            // A lack of test binary counts as a failure
3192            let process = installation_test_binary.and_then(|binary| {
3193                smol::process::Command::new(&binary.path)
3194                    .current_dir(&binary.path)
3195                    .args(binary.arguments)
3196                    .stdin(Stdio::piped())
3197                    .stdout(Stdio::piped())
3198                    .stderr(Stdio::inherit())
3199                    .kill_on_drop(true)
3200                    .spawn()
3201                    .ok()
3202            });
3203
3204            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3205            let mut timeout = cx.background().timer(PROCESS_TIMEOUT).fuse();
3206
3207            let mut errored = false;
3208            if let Some(mut process) = process {
3209                futures::select! {
3210                    status = process.status().fuse() => match status {
3211                        Ok(status) => errored = !status.success(),
3212                        Err(_) => errored = true,
3213                    },
3214
3215                    _ = timeout => {
3216                        log::info!("test binary time-ed out, this counts as a success");
3217                        _ = process.kill();
3218                    }
3219                }
3220            } else {
3221                log::warn!("test binary failed to launch");
3222                errored = true;
3223            }
3224
3225            if errored {
3226                log::warn!("test binary check failed");
3227                let task = this.update(&mut cx, move |this, mut cx| {
3228                    this.reinstall_language_server(language, adapter, server_id, &mut cx)
3229                });
3230
3231                if let Some(task) = task {
3232                    task.await;
3233                }
3234            }
3235        })
3236        .detach();
3237    }
3238
3239    fn on_lsp_progress(
3240        &mut self,
3241        progress: lsp::ProgressParams,
3242        language_server_id: LanguageServerId,
3243        disk_based_diagnostics_progress_token: Option<String>,
3244        cx: &mut ModelContext<Self>,
3245    ) {
3246        let token = match progress.token {
3247            lsp::NumberOrString::String(token) => token,
3248            lsp::NumberOrString::Number(token) => {
3249                log::info!("skipping numeric progress token {}", token);
3250                return;
3251            }
3252        };
3253        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3254        let language_server_status =
3255            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3256                status
3257            } else {
3258                return;
3259            };
3260
3261        if !language_server_status.progress_tokens.contains(&token) {
3262            return;
3263        }
3264
3265        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3266            .as_ref()
3267            .map_or(false, |disk_based_token| {
3268                token.starts_with(disk_based_token)
3269            });
3270
3271        match progress {
3272            lsp::WorkDoneProgress::Begin(report) => {
3273                if is_disk_based_diagnostics_progress {
3274                    language_server_status.has_pending_diagnostic_updates = true;
3275                    self.disk_based_diagnostics_started(language_server_id, cx);
3276                    self.buffer_ordered_messages_tx
3277                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3278                            language_server_id,
3279                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3280                        })
3281                        .ok();
3282                } else {
3283                    self.on_lsp_work_start(
3284                        language_server_id,
3285                        token.clone(),
3286                        LanguageServerProgress {
3287                            message: report.message.clone(),
3288                            percentage: report.percentage.map(|p| p as usize),
3289                            last_update_at: Instant::now(),
3290                        },
3291                        cx,
3292                    );
3293                    self.buffer_ordered_messages_tx
3294                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3295                            language_server_id,
3296                            message: proto::update_language_server::Variant::WorkStart(
3297                                proto::LspWorkStart {
3298                                    token,
3299                                    message: report.message,
3300                                    percentage: report.percentage.map(|p| p as u32),
3301                                },
3302                            ),
3303                        })
3304                        .ok();
3305                }
3306            }
3307            lsp::WorkDoneProgress::Report(report) => {
3308                if !is_disk_based_diagnostics_progress {
3309                    self.on_lsp_work_progress(
3310                        language_server_id,
3311                        token.clone(),
3312                        LanguageServerProgress {
3313                            message: report.message.clone(),
3314                            percentage: report.percentage.map(|p| p as usize),
3315                            last_update_at: Instant::now(),
3316                        },
3317                        cx,
3318                    );
3319                    self.buffer_ordered_messages_tx
3320                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3321                            language_server_id,
3322                            message: proto::update_language_server::Variant::WorkProgress(
3323                                proto::LspWorkProgress {
3324                                    token,
3325                                    message: report.message,
3326                                    percentage: report.percentage.map(|p| p as u32),
3327                                },
3328                            ),
3329                        })
3330                        .ok();
3331                }
3332            }
3333            lsp::WorkDoneProgress::End(_) => {
3334                language_server_status.progress_tokens.remove(&token);
3335
3336                if is_disk_based_diagnostics_progress {
3337                    language_server_status.has_pending_diagnostic_updates = false;
3338                    self.disk_based_diagnostics_finished(language_server_id, cx);
3339                    self.buffer_ordered_messages_tx
3340                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3341                            language_server_id,
3342                            message:
3343                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3344                                    Default::default(),
3345                                ),
3346                        })
3347                        .ok();
3348                } else {
3349                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
3350                    self.buffer_ordered_messages_tx
3351                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3352                            language_server_id,
3353                            message: proto::update_language_server::Variant::WorkEnd(
3354                                proto::LspWorkEnd { token },
3355                            ),
3356                        })
3357                        .ok();
3358                }
3359            }
3360        }
3361    }
3362
3363    fn on_lsp_work_start(
3364        &mut self,
3365        language_server_id: LanguageServerId,
3366        token: String,
3367        progress: LanguageServerProgress,
3368        cx: &mut ModelContext<Self>,
3369    ) {
3370        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3371            status.pending_work.insert(token, progress);
3372            cx.notify();
3373        }
3374    }
3375
3376    fn on_lsp_work_progress(
3377        &mut self,
3378        language_server_id: LanguageServerId,
3379        token: String,
3380        progress: LanguageServerProgress,
3381        cx: &mut ModelContext<Self>,
3382    ) {
3383        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3384            let entry = status
3385                .pending_work
3386                .entry(token)
3387                .or_insert(LanguageServerProgress {
3388                    message: Default::default(),
3389                    percentage: Default::default(),
3390                    last_update_at: progress.last_update_at,
3391                });
3392            if progress.message.is_some() {
3393                entry.message = progress.message;
3394            }
3395            if progress.percentage.is_some() {
3396                entry.percentage = progress.percentage;
3397            }
3398            entry.last_update_at = progress.last_update_at;
3399            cx.notify();
3400        }
3401    }
3402
3403    fn on_lsp_work_end(
3404        &mut self,
3405        language_server_id: LanguageServerId,
3406        token: String,
3407        cx: &mut ModelContext<Self>,
3408    ) {
3409        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3410            cx.emit(Event::RefreshInlays);
3411            status.pending_work.remove(&token);
3412            cx.notify();
3413        }
3414    }
3415
3416    fn on_lsp_did_change_watched_files(
3417        &mut self,
3418        language_server_id: LanguageServerId,
3419        params: DidChangeWatchedFilesRegistrationOptions,
3420        cx: &mut ModelContext<Self>,
3421    ) {
3422        if let Some(LanguageServerState::Running { watched_paths, .. }) =
3423            self.language_servers.get_mut(&language_server_id)
3424        {
3425            let mut builders = HashMap::default();
3426            for watcher in params.watchers {
3427                for worktree in &self.worktrees {
3428                    if let Some(worktree) = worktree.upgrade(cx) {
3429                        let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3430                            if let Some(abs_path) = tree.abs_path().to_str() {
3431                                let relative_glob_pattern = match &watcher.glob_pattern {
3432                                    lsp::GlobPattern::String(s) => s
3433                                        .strip_prefix(abs_path)
3434                                        .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3435                                    lsp::GlobPattern::Relative(rp) => {
3436                                        let base_uri = match &rp.base_uri {
3437                                            lsp::OneOf::Left(workspace_folder) => {
3438                                                &workspace_folder.uri
3439                                            }
3440                                            lsp::OneOf::Right(base_uri) => base_uri,
3441                                        };
3442                                        base_uri.to_file_path().ok().and_then(|file_path| {
3443                                            (file_path.to_str() == Some(abs_path))
3444                                                .then_some(rp.pattern.as_str())
3445                                        })
3446                                    }
3447                                };
3448                                if let Some(relative_glob_pattern) = relative_glob_pattern {
3449                                    let literal_prefix =
3450                                        glob_literal_prefix(&relative_glob_pattern);
3451                                    tree.as_local_mut()
3452                                        .unwrap()
3453                                        .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3454                                    if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3455                                        builders
3456                                            .entry(tree.id())
3457                                            .or_insert_with(|| GlobSetBuilder::new())
3458                                            .add(glob);
3459                                    }
3460                                    return true;
3461                                }
3462                            }
3463                            false
3464                        });
3465                        if glob_is_inside_worktree {
3466                            break;
3467                        }
3468                    }
3469                }
3470            }
3471
3472            watched_paths.clear();
3473            for (worktree_id, builder) in builders {
3474                if let Ok(globset) = builder.build() {
3475                    watched_paths.insert(worktree_id, globset);
3476                }
3477            }
3478
3479            cx.notify();
3480        }
3481    }
3482
3483    async fn on_lsp_workspace_edit(
3484        this: WeakModelHandle<Self>,
3485        params: lsp::ApplyWorkspaceEditParams,
3486        server_id: LanguageServerId,
3487        adapter: Arc<CachedLspAdapter>,
3488        mut cx: AsyncAppContext,
3489    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3490        let this = this
3491            .upgrade(&cx)
3492            .ok_or_else(|| anyhow!("project project closed"))?;
3493        let language_server = this
3494            .read_with(&cx, |this, _| this.language_server_for_id(server_id))
3495            .ok_or_else(|| anyhow!("language server not found"))?;
3496        let transaction = Self::deserialize_workspace_edit(
3497            this.clone(),
3498            params.edit,
3499            true,
3500            adapter.clone(),
3501            language_server.clone(),
3502            &mut cx,
3503        )
3504        .await
3505        .log_err();
3506        this.update(&mut cx, |this, _| {
3507            if let Some(transaction) = transaction {
3508                this.last_workspace_edits_by_language_server
3509                    .insert(server_id, transaction);
3510            }
3511        });
3512        Ok(lsp::ApplyWorkspaceEditResponse {
3513            applied: true,
3514            failed_change: None,
3515            failure_reason: None,
3516        })
3517    }
3518
3519    pub fn language_server_statuses(
3520        &self,
3521    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3522        self.language_server_statuses.values()
3523    }
3524
3525    pub fn update_diagnostics(
3526        &mut self,
3527        language_server_id: LanguageServerId,
3528        mut params: lsp::PublishDiagnosticsParams,
3529        disk_based_sources: &[String],
3530        cx: &mut ModelContext<Self>,
3531    ) -> Result<()> {
3532        let abs_path = params
3533            .uri
3534            .to_file_path()
3535            .map_err(|_| anyhow!("URI is not a file"))?;
3536        let mut diagnostics = Vec::default();
3537        let mut primary_diagnostic_group_ids = HashMap::default();
3538        let mut sources_by_group_id = HashMap::default();
3539        let mut supporting_diagnostics = HashMap::default();
3540
3541        // Ensure that primary diagnostics are always the most severe
3542        params.diagnostics.sort_by_key(|item| item.severity);
3543
3544        for diagnostic in &params.diagnostics {
3545            let source = diagnostic.source.as_ref();
3546            let code = diagnostic.code.as_ref().map(|code| match code {
3547                lsp::NumberOrString::Number(code) => code.to_string(),
3548                lsp::NumberOrString::String(code) => code.clone(),
3549            });
3550            let range = range_from_lsp(diagnostic.range);
3551            let is_supporting = diagnostic
3552                .related_information
3553                .as_ref()
3554                .map_or(false, |infos| {
3555                    infos.iter().any(|info| {
3556                        primary_diagnostic_group_ids.contains_key(&(
3557                            source,
3558                            code.clone(),
3559                            range_from_lsp(info.location.range),
3560                        ))
3561                    })
3562                });
3563
3564            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3565                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3566            });
3567
3568            if is_supporting {
3569                supporting_diagnostics.insert(
3570                    (source, code.clone(), range),
3571                    (diagnostic.severity, is_unnecessary),
3572                );
3573            } else {
3574                let group_id = post_inc(&mut self.next_diagnostic_group_id);
3575                let is_disk_based =
3576                    source.map_or(false, |source| disk_based_sources.contains(source));
3577
3578                sources_by_group_id.insert(group_id, source);
3579                primary_diagnostic_group_ids
3580                    .insert((source, code.clone(), range.clone()), group_id);
3581
3582                diagnostics.push(DiagnosticEntry {
3583                    range,
3584                    diagnostic: Diagnostic {
3585                        source: diagnostic.source.clone(),
3586                        code: code.clone(),
3587                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3588                        message: diagnostic.message.clone(),
3589                        group_id,
3590                        is_primary: true,
3591                        is_valid: true,
3592                        is_disk_based,
3593                        is_unnecessary,
3594                    },
3595                });
3596                if let Some(infos) = &diagnostic.related_information {
3597                    for info in infos {
3598                        if info.location.uri == params.uri && !info.message.is_empty() {
3599                            let range = range_from_lsp(info.location.range);
3600                            diagnostics.push(DiagnosticEntry {
3601                                range,
3602                                diagnostic: Diagnostic {
3603                                    source: diagnostic.source.clone(),
3604                                    code: code.clone(),
3605                                    severity: DiagnosticSeverity::INFORMATION,
3606                                    message: info.message.clone(),
3607                                    group_id,
3608                                    is_primary: false,
3609                                    is_valid: true,
3610                                    is_disk_based,
3611                                    is_unnecessary: false,
3612                                },
3613                            });
3614                        }
3615                    }
3616                }
3617            }
3618        }
3619
3620        for entry in &mut diagnostics {
3621            let diagnostic = &mut entry.diagnostic;
3622            if !diagnostic.is_primary {
3623                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3624                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3625                    source,
3626                    diagnostic.code.clone(),
3627                    entry.range.clone(),
3628                )) {
3629                    if let Some(severity) = severity {
3630                        diagnostic.severity = severity;
3631                    }
3632                    diagnostic.is_unnecessary = is_unnecessary;
3633                }
3634            }
3635        }
3636
3637        self.update_diagnostic_entries(
3638            language_server_id,
3639            abs_path,
3640            params.version,
3641            diagnostics,
3642            cx,
3643        )?;
3644        Ok(())
3645    }
3646
3647    pub fn update_diagnostic_entries(
3648        &mut self,
3649        server_id: LanguageServerId,
3650        abs_path: PathBuf,
3651        version: Option<i32>,
3652        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3653        cx: &mut ModelContext<Project>,
3654    ) -> Result<(), anyhow::Error> {
3655        let (worktree, relative_path) = self
3656            .find_local_worktree(&abs_path, cx)
3657            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3658
3659        let project_path = ProjectPath {
3660            worktree_id: worktree.read(cx).id(),
3661            path: relative_path.into(),
3662        };
3663
3664        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3665            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3666        }
3667
3668        let updated = worktree.update(cx, |worktree, cx| {
3669            worktree
3670                .as_local_mut()
3671                .ok_or_else(|| anyhow!("not a local worktree"))?
3672                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3673        })?;
3674        if updated {
3675            cx.emit(Event::DiagnosticsUpdated {
3676                language_server_id: server_id,
3677                path: project_path,
3678            });
3679        }
3680        Ok(())
3681    }
3682
3683    fn update_buffer_diagnostics(
3684        &mut self,
3685        buffer: &ModelHandle<Buffer>,
3686        server_id: LanguageServerId,
3687        version: Option<i32>,
3688        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3689        cx: &mut ModelContext<Self>,
3690    ) -> Result<()> {
3691        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3692            Ordering::Equal
3693                .then_with(|| b.is_primary.cmp(&a.is_primary))
3694                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3695                .then_with(|| a.severity.cmp(&b.severity))
3696                .then_with(|| a.message.cmp(&b.message))
3697        }
3698
3699        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3700
3701        diagnostics.sort_unstable_by(|a, b| {
3702            Ordering::Equal
3703                .then_with(|| a.range.start.cmp(&b.range.start))
3704                .then_with(|| b.range.end.cmp(&a.range.end))
3705                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3706        });
3707
3708        let mut sanitized_diagnostics = Vec::new();
3709        let edits_since_save = Patch::new(
3710            snapshot
3711                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3712                .collect(),
3713        );
3714        for entry in diagnostics {
3715            let start;
3716            let end;
3717            if entry.diagnostic.is_disk_based {
3718                // Some diagnostics are based on files on disk instead of buffers'
3719                // current contents. Adjust these diagnostics' ranges to reflect
3720                // any unsaved edits.
3721                start = edits_since_save.old_to_new(entry.range.start);
3722                end = edits_since_save.old_to_new(entry.range.end);
3723            } else {
3724                start = entry.range.start;
3725                end = entry.range.end;
3726            }
3727
3728            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3729                ..snapshot.clip_point_utf16(end, Bias::Right);
3730
3731            // Expand empty ranges by one codepoint
3732            if range.start == range.end {
3733                // This will be go to the next boundary when being clipped
3734                range.end.column += 1;
3735                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3736                if range.start == range.end && range.end.column > 0 {
3737                    range.start.column -= 1;
3738                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3739                }
3740            }
3741
3742            sanitized_diagnostics.push(DiagnosticEntry {
3743                range,
3744                diagnostic: entry.diagnostic,
3745            });
3746        }
3747        drop(edits_since_save);
3748
3749        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
3750        buffer.update(cx, |buffer, cx| {
3751            buffer.update_diagnostics(server_id, set, cx)
3752        });
3753        Ok(())
3754    }
3755
3756    pub fn reload_buffers(
3757        &self,
3758        buffers: HashSet<ModelHandle<Buffer>>,
3759        push_to_history: bool,
3760        cx: &mut ModelContext<Self>,
3761    ) -> Task<Result<ProjectTransaction>> {
3762        let mut local_buffers = Vec::new();
3763        let mut remote_buffers = None;
3764        for buffer_handle in buffers {
3765            let buffer = buffer_handle.read(cx);
3766            if buffer.is_dirty() {
3767                if let Some(file) = File::from_dyn(buffer.file()) {
3768                    if file.is_local() {
3769                        local_buffers.push(buffer_handle);
3770                    } else {
3771                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3772                    }
3773                }
3774            }
3775        }
3776
3777        let remote_buffers = self.remote_id().zip(remote_buffers);
3778        let client = self.client.clone();
3779
3780        cx.spawn(|this, mut cx| async move {
3781            let mut project_transaction = ProjectTransaction::default();
3782
3783            if let Some((project_id, remote_buffers)) = remote_buffers {
3784                let response = client
3785                    .request(proto::ReloadBuffers {
3786                        project_id,
3787                        buffer_ids: remote_buffers
3788                            .iter()
3789                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3790                            .collect(),
3791                    })
3792                    .await?
3793                    .transaction
3794                    .ok_or_else(|| anyhow!("missing transaction"))?;
3795                project_transaction = this
3796                    .update(&mut cx, |this, cx| {
3797                        this.deserialize_project_transaction(response, push_to_history, cx)
3798                    })
3799                    .await?;
3800            }
3801
3802            for buffer in local_buffers {
3803                let transaction = buffer
3804                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
3805                    .await?;
3806                buffer.update(&mut cx, |buffer, cx| {
3807                    if let Some(transaction) = transaction {
3808                        if !push_to_history {
3809                            buffer.forget_transaction(transaction.id);
3810                        }
3811                        project_transaction.0.insert(cx.handle(), transaction);
3812                    }
3813                });
3814            }
3815
3816            Ok(project_transaction)
3817        })
3818    }
3819
3820    pub fn format(
3821        &self,
3822        buffers: HashSet<ModelHandle<Buffer>>,
3823        push_to_history: bool,
3824        trigger: FormatTrigger,
3825        cx: &mut ModelContext<Project>,
3826    ) -> Task<Result<ProjectTransaction>> {
3827        if self.is_local() {
3828            let mut buffers_with_paths_and_servers = buffers
3829                .into_iter()
3830                .filter_map(|buffer_handle| {
3831                    let buffer = buffer_handle.read(cx);
3832                    let file = File::from_dyn(buffer.file())?;
3833                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3834                    let server = self
3835                        .primary_language_servers_for_buffer(buffer, cx)
3836                        .map(|s| s.1.clone());
3837                    Some((buffer_handle, buffer_abs_path, server))
3838                })
3839                .collect::<Vec<_>>();
3840
3841            cx.spawn(|this, mut cx| async move {
3842                // Do not allow multiple concurrent formatting requests for the
3843                // same buffer.
3844                this.update(&mut cx, |this, cx| {
3845                    buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
3846                        this.buffers_being_formatted
3847                            .insert(buffer.read(cx).remote_id())
3848                    });
3849                });
3850
3851                let _cleanup = defer({
3852                    let this = this.clone();
3853                    let mut cx = cx.clone();
3854                    let buffers = &buffers_with_paths_and_servers;
3855                    move || {
3856                        this.update(&mut cx, |this, cx| {
3857                            for (buffer, _, _) in buffers {
3858                                this.buffers_being_formatted
3859                                    .remove(&buffer.read(cx).remote_id());
3860                            }
3861                        });
3862                    }
3863                });
3864
3865                let mut project_transaction = ProjectTransaction::default();
3866                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3867                    let settings = buffer.read_with(&cx, |buffer, cx| {
3868                        language_settings(buffer.language(), buffer.file(), cx).clone()
3869                    });
3870
3871                    let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
3872                    let ensure_final_newline = settings.ensure_final_newline_on_save;
3873                    let format_on_save = settings.format_on_save.clone();
3874                    let formatter = settings.formatter.clone();
3875                    let tab_size = settings.tab_size;
3876
3877                    // First, format buffer's whitespace according to the settings.
3878                    let trailing_whitespace_diff = if remove_trailing_whitespace {
3879                        Some(
3880                            buffer
3881                                .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3882                                .await,
3883                        )
3884                    } else {
3885                        None
3886                    };
3887                    let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3888                        buffer.finalize_last_transaction();
3889                        buffer.start_transaction();
3890                        if let Some(diff) = trailing_whitespace_diff {
3891                            buffer.apply_diff(diff, cx);
3892                        }
3893                        if ensure_final_newline {
3894                            buffer.ensure_final_newline(cx);
3895                        }
3896                        buffer.end_transaction(cx)
3897                    });
3898
3899                    // Currently, formatting operations are represented differently depending on
3900                    // whether they come from a language server or an external command.
3901                    enum FormatOperation {
3902                        Lsp(Vec<(Range<Anchor>, String)>),
3903                        External(Diff),
3904                    }
3905
3906                    // Apply language-specific formatting using either a language server
3907                    // or external command.
3908                    let mut format_operation = None;
3909                    match (formatter, format_on_save) {
3910                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3911
3912                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3913                        | (_, FormatOnSave::LanguageServer) => {
3914                            if let Some((language_server, buffer_abs_path)) =
3915                                language_server.as_ref().zip(buffer_abs_path.as_ref())
3916                            {
3917                                format_operation = Some(FormatOperation::Lsp(
3918                                    Self::format_via_lsp(
3919                                        &this,
3920                                        &buffer,
3921                                        buffer_abs_path,
3922                                        &language_server,
3923                                        tab_size,
3924                                        &mut cx,
3925                                    )
3926                                    .await
3927                                    .context("failed to format via language server")?,
3928                                ));
3929                            }
3930                        }
3931
3932                        (
3933                            Formatter::External { command, arguments },
3934                            FormatOnSave::On | FormatOnSave::Off,
3935                        )
3936                        | (_, FormatOnSave::External { command, arguments }) => {
3937                            if let Some(buffer_abs_path) = buffer_abs_path {
3938                                format_operation = Self::format_via_external_command(
3939                                    &buffer,
3940                                    &buffer_abs_path,
3941                                    &command,
3942                                    &arguments,
3943                                    &mut cx,
3944                                )
3945                                .await
3946                                .context(format!(
3947                                    "failed to format via external command {:?}",
3948                                    command
3949                                ))?
3950                                .map(FormatOperation::External);
3951                            }
3952                        }
3953                    };
3954
3955                    buffer.update(&mut cx, |b, cx| {
3956                        // If the buffer had its whitespace formatted and was edited while the language-specific
3957                        // formatting was being computed, avoid applying the language-specific formatting, because
3958                        // it can't be grouped with the whitespace formatting in the undo history.
3959                        if let Some(transaction_id) = whitespace_transaction_id {
3960                            if b.peek_undo_stack()
3961                                .map_or(true, |e| e.transaction_id() != transaction_id)
3962                            {
3963                                format_operation.take();
3964                            }
3965                        }
3966
3967                        // Apply any language-specific formatting, and group the two formatting operations
3968                        // in the buffer's undo history.
3969                        if let Some(operation) = format_operation {
3970                            match operation {
3971                                FormatOperation::Lsp(edits) => {
3972                                    b.edit(edits, None, cx);
3973                                }
3974                                FormatOperation::External(diff) => {
3975                                    b.apply_diff(diff, cx);
3976                                }
3977                            }
3978
3979                            if let Some(transaction_id) = whitespace_transaction_id {
3980                                b.group_until_transaction(transaction_id);
3981                            }
3982                        }
3983
3984                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
3985                            if !push_to_history {
3986                                b.forget_transaction(transaction.id);
3987                            }
3988                            project_transaction.0.insert(buffer.clone(), transaction);
3989                        }
3990                    });
3991                }
3992
3993                Ok(project_transaction)
3994            })
3995        } else {
3996            let remote_id = self.remote_id();
3997            let client = self.client.clone();
3998            cx.spawn(|this, mut cx| async move {
3999                let mut project_transaction = ProjectTransaction::default();
4000                if let Some(project_id) = remote_id {
4001                    let response = client
4002                        .request(proto::FormatBuffers {
4003                            project_id,
4004                            trigger: trigger as i32,
4005                            buffer_ids: buffers
4006                                .iter()
4007                                .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
4008                                .collect(),
4009                        })
4010                        .await?
4011                        .transaction
4012                        .ok_or_else(|| anyhow!("missing transaction"))?;
4013                    project_transaction = this
4014                        .update(&mut cx, |this, cx| {
4015                            this.deserialize_project_transaction(response, push_to_history, cx)
4016                        })
4017                        .await?;
4018                }
4019                Ok(project_transaction)
4020            })
4021        }
4022    }
4023
4024    async fn format_via_lsp(
4025        this: &ModelHandle<Self>,
4026        buffer: &ModelHandle<Buffer>,
4027        abs_path: &Path,
4028        language_server: &Arc<LanguageServer>,
4029        tab_size: NonZeroU32,
4030        cx: &mut AsyncAppContext,
4031    ) -> Result<Vec<(Range<Anchor>, String)>> {
4032        let uri = lsp::Url::from_file_path(abs_path)
4033            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4034        let text_document = lsp::TextDocumentIdentifier::new(uri);
4035        let capabilities = &language_server.capabilities();
4036
4037        let formatting_provider = capabilities.document_formatting_provider.as_ref();
4038        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4039
4040        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4041            language_server
4042                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4043                    text_document,
4044                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4045                    work_done_progress_params: Default::default(),
4046                })
4047                .await?
4048        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4049            let buffer_start = lsp::Position::new(0, 0);
4050            let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()));
4051
4052            language_server
4053                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4054                    text_document,
4055                    range: lsp::Range::new(buffer_start, buffer_end),
4056                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4057                    work_done_progress_params: Default::default(),
4058                })
4059                .await?
4060        } else {
4061            None
4062        };
4063
4064        if let Some(lsp_edits) = lsp_edits {
4065            this.update(cx, |this, cx| {
4066                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4067            })
4068            .await
4069        } else {
4070            Ok(Vec::new())
4071        }
4072    }
4073
4074    async fn format_via_external_command(
4075        buffer: &ModelHandle<Buffer>,
4076        buffer_abs_path: &Path,
4077        command: &str,
4078        arguments: &[String],
4079        cx: &mut AsyncAppContext,
4080    ) -> Result<Option<Diff>> {
4081        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
4082            let file = File::from_dyn(buffer.file())?;
4083            let worktree = file.worktree.read(cx).as_local()?;
4084            let mut worktree_path = worktree.abs_path().to_path_buf();
4085            if worktree.root_entry()?.is_file() {
4086                worktree_path.pop();
4087            }
4088            Some(worktree_path)
4089        });
4090
4091        if let Some(working_dir_path) = working_dir_path {
4092            let mut child =
4093                smol::process::Command::new(command)
4094                    .args(arguments.iter().map(|arg| {
4095                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4096                    }))
4097                    .current_dir(&working_dir_path)
4098                    .stdin(smol::process::Stdio::piped())
4099                    .stdout(smol::process::Stdio::piped())
4100                    .stderr(smol::process::Stdio::piped())
4101                    .spawn()?;
4102            let stdin = child
4103                .stdin
4104                .as_mut()
4105                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4106            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
4107            for chunk in text.chunks() {
4108                stdin.write_all(chunk.as_bytes()).await?;
4109            }
4110            stdin.flush().await?;
4111
4112            let output = child.output().await?;
4113            if !output.status.success() {
4114                return Err(anyhow!(
4115                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4116                    output.status.code(),
4117                    String::from_utf8_lossy(&output.stdout),
4118                    String::from_utf8_lossy(&output.stderr),
4119                ));
4120            }
4121
4122            let stdout = String::from_utf8(output.stdout)?;
4123            Ok(Some(
4124                buffer
4125                    .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
4126                    .await,
4127            ))
4128        } else {
4129            Ok(None)
4130        }
4131    }
4132
4133    pub fn definition<T: ToPointUtf16>(
4134        &self,
4135        buffer: &ModelHandle<Buffer>,
4136        position: T,
4137        cx: &mut ModelContext<Self>,
4138    ) -> Task<Result<Vec<LocationLink>>> {
4139        let position = position.to_point_utf16(buffer.read(cx));
4140        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
4141    }
4142
4143    pub fn type_definition<T: ToPointUtf16>(
4144        &self,
4145        buffer: &ModelHandle<Buffer>,
4146        position: T,
4147        cx: &mut ModelContext<Self>,
4148    ) -> Task<Result<Vec<LocationLink>>> {
4149        let position = position.to_point_utf16(buffer.read(cx));
4150        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
4151    }
4152
4153    pub fn references<T: ToPointUtf16>(
4154        &self,
4155        buffer: &ModelHandle<Buffer>,
4156        position: T,
4157        cx: &mut ModelContext<Self>,
4158    ) -> Task<Result<Vec<Location>>> {
4159        let position = position.to_point_utf16(buffer.read(cx));
4160        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
4161    }
4162
4163    pub fn document_highlights<T: ToPointUtf16>(
4164        &self,
4165        buffer: &ModelHandle<Buffer>,
4166        position: T,
4167        cx: &mut ModelContext<Self>,
4168    ) -> Task<Result<Vec<DocumentHighlight>>> {
4169        let position = position.to_point_utf16(buffer.read(cx));
4170        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
4171    }
4172
4173    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4174        if self.is_local() {
4175            let mut requests = Vec::new();
4176            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4177                let worktree_id = *worktree_id;
4178                let worktree_handle = self.worktree_for_id(worktree_id, cx);
4179                let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4180                    Some(worktree) => worktree,
4181                    None => continue,
4182                };
4183                let worktree_abs_path = worktree.abs_path().clone();
4184
4185                let (adapter, language, server) = match self.language_servers.get(server_id) {
4186                    Some(LanguageServerState::Running {
4187                        adapter,
4188                        language,
4189                        server,
4190                        ..
4191                    }) => (adapter.clone(), language.clone(), server),
4192
4193                    _ => continue,
4194                };
4195
4196                requests.push(
4197                    server
4198                        .request::<lsp::request::WorkspaceSymbolRequest>(
4199                            lsp::WorkspaceSymbolParams {
4200                                query: query.to_string(),
4201                                ..Default::default()
4202                            },
4203                        )
4204                        .log_err()
4205                        .map(move |response| {
4206                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4207                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4208                                    flat_responses.into_iter().map(|lsp_symbol| {
4209                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4210                                    }).collect::<Vec<_>>()
4211                                }
4212                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4213                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
4214                                        let location = match lsp_symbol.location {
4215                                            OneOf::Left(location) => location,
4216                                            OneOf::Right(_) => {
4217                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4218                                                return None
4219                                            }
4220                                        };
4221                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
4222                                    }).collect::<Vec<_>>()
4223                                }
4224                            }).unwrap_or_default();
4225
4226                            (
4227                                adapter,
4228                                language,
4229                                worktree_id,
4230                                worktree_abs_path,
4231                                lsp_symbols,
4232                            )
4233                        }),
4234                );
4235            }
4236
4237            cx.spawn_weak(|this, cx| async move {
4238                let responses = futures::future::join_all(requests).await;
4239                let this = match this.upgrade(&cx) {
4240                    Some(this) => this,
4241                    None => return Ok(Vec::new()),
4242                };
4243
4244                let symbols = this.read_with(&cx, |this, cx| {
4245                    let mut symbols = Vec::new();
4246                    for (
4247                        adapter,
4248                        adapter_language,
4249                        source_worktree_id,
4250                        worktree_abs_path,
4251                        lsp_symbols,
4252                    ) in responses
4253                    {
4254                        symbols.extend(lsp_symbols.into_iter().filter_map(
4255                            |(symbol_name, symbol_kind, symbol_location)| {
4256                                let abs_path = symbol_location.uri.to_file_path().ok()?;
4257                                let mut worktree_id = source_worktree_id;
4258                                let path;
4259                                if let Some((worktree, rel_path)) =
4260                                    this.find_local_worktree(&abs_path, cx)
4261                                {
4262                                    worktree_id = worktree.read(cx).id();
4263                                    path = rel_path;
4264                                } else {
4265                                    path = relativize_path(&worktree_abs_path, &abs_path);
4266                                }
4267
4268                                let project_path = ProjectPath {
4269                                    worktree_id,
4270                                    path: path.into(),
4271                                };
4272                                let signature = this.symbol_signature(&project_path);
4273                                let adapter_language = adapter_language.clone();
4274                                let language = this
4275                                    .languages
4276                                    .language_for_file(&project_path.path, None)
4277                                    .unwrap_or_else(move |_| adapter_language);
4278                                let language_server_name = adapter.name.clone();
4279                                Some(async move {
4280                                    let language = language.await;
4281                                    let label =
4282                                        language.label_for_symbol(&symbol_name, symbol_kind).await;
4283
4284                                    Symbol {
4285                                        language_server_name,
4286                                        source_worktree_id,
4287                                        path: project_path,
4288                                        label: label.unwrap_or_else(|| {
4289                                            CodeLabel::plain(symbol_name.clone(), None)
4290                                        }),
4291                                        kind: symbol_kind,
4292                                        name: symbol_name,
4293                                        range: range_from_lsp(symbol_location.range),
4294                                        signature,
4295                                    }
4296                                })
4297                            },
4298                        ));
4299                    }
4300
4301                    symbols
4302                });
4303
4304                Ok(futures::future::join_all(symbols).await)
4305            })
4306        } else if let Some(project_id) = self.remote_id() {
4307            let request = self.client.request(proto::GetProjectSymbols {
4308                project_id,
4309                query: query.to_string(),
4310            });
4311            cx.spawn_weak(|this, cx| async move {
4312                let response = request.await?;
4313                let mut symbols = Vec::new();
4314                if let Some(this) = this.upgrade(&cx) {
4315                    let new_symbols = this.read_with(&cx, |this, _| {
4316                        response
4317                            .symbols
4318                            .into_iter()
4319                            .map(|symbol| this.deserialize_symbol(symbol))
4320                            .collect::<Vec<_>>()
4321                    });
4322                    symbols = futures::future::join_all(new_symbols)
4323                        .await
4324                        .into_iter()
4325                        .filter_map(|symbol| symbol.log_err())
4326                        .collect::<Vec<_>>();
4327                }
4328                Ok(symbols)
4329            })
4330        } else {
4331            Task::ready(Ok(Default::default()))
4332        }
4333    }
4334
4335    pub fn open_buffer_for_symbol(
4336        &mut self,
4337        symbol: &Symbol,
4338        cx: &mut ModelContext<Self>,
4339    ) -> Task<Result<ModelHandle<Buffer>>> {
4340        if self.is_local() {
4341            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4342                symbol.source_worktree_id,
4343                symbol.language_server_name.clone(),
4344            )) {
4345                *id
4346            } else {
4347                return Task::ready(Err(anyhow!(
4348                    "language server for worktree and language not found"
4349                )));
4350            };
4351
4352            let worktree_abs_path = if let Some(worktree_abs_path) = self
4353                .worktree_for_id(symbol.path.worktree_id, cx)
4354                .and_then(|worktree| worktree.read(cx).as_local())
4355                .map(|local_worktree| local_worktree.abs_path())
4356            {
4357                worktree_abs_path
4358            } else {
4359                return Task::ready(Err(anyhow!("worktree not found for symbol")));
4360            };
4361            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
4362            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4363                uri
4364            } else {
4365                return Task::ready(Err(anyhow!("invalid symbol path")));
4366            };
4367
4368            self.open_local_buffer_via_lsp(
4369                symbol_uri,
4370                language_server_id,
4371                symbol.language_server_name.clone(),
4372                cx,
4373            )
4374        } else if let Some(project_id) = self.remote_id() {
4375            let request = self.client.request(proto::OpenBufferForSymbol {
4376                project_id,
4377                symbol: Some(serialize_symbol(symbol)),
4378            });
4379            cx.spawn(|this, mut cx| async move {
4380                let response = request.await?;
4381                this.update(&mut cx, |this, cx| {
4382                    this.wait_for_remote_buffer(response.buffer_id, cx)
4383                })
4384                .await
4385            })
4386        } else {
4387            Task::ready(Err(anyhow!("project does not have a remote id")))
4388        }
4389    }
4390
4391    pub fn hover<T: ToPointUtf16>(
4392        &self,
4393        buffer: &ModelHandle<Buffer>,
4394        position: T,
4395        cx: &mut ModelContext<Self>,
4396    ) -> Task<Result<Option<Hover>>> {
4397        let position = position.to_point_utf16(buffer.read(cx));
4398        self.request_lsp(buffer.clone(), GetHover { position }, cx)
4399    }
4400
4401    pub fn completions<T: ToPointUtf16>(
4402        &self,
4403        buffer: &ModelHandle<Buffer>,
4404        position: T,
4405        cx: &mut ModelContext<Self>,
4406    ) -> Task<Result<Vec<Completion>>> {
4407        let position = position.to_point_utf16(buffer.read(cx));
4408        self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
4409    }
4410
4411    pub fn apply_additional_edits_for_completion(
4412        &self,
4413        buffer_handle: ModelHandle<Buffer>,
4414        completion: Completion,
4415        push_to_history: bool,
4416        cx: &mut ModelContext<Self>,
4417    ) -> Task<Result<Option<Transaction>>> {
4418        let buffer = buffer_handle.read(cx);
4419        let buffer_id = buffer.remote_id();
4420
4421        if self.is_local() {
4422            let lang_server = match self.primary_language_servers_for_buffer(buffer, cx) {
4423                Some((_, server)) => server.clone(),
4424                _ => return Task::ready(Ok(Default::default())),
4425            };
4426
4427            cx.spawn(|this, mut cx| async move {
4428                let resolved_completion = lang_server
4429                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4430                    .await?;
4431
4432                if let Some(edits) = resolved_completion.additional_text_edits {
4433                    let edits = this
4434                        .update(&mut cx, |this, cx| {
4435                            this.edits_from_lsp(
4436                                &buffer_handle,
4437                                edits,
4438                                lang_server.server_id(),
4439                                None,
4440                                cx,
4441                            )
4442                        })
4443                        .await?;
4444
4445                    buffer_handle.update(&mut cx, |buffer, cx| {
4446                        buffer.finalize_last_transaction();
4447                        buffer.start_transaction();
4448
4449                        for (range, text) in edits {
4450                            let primary = &completion.old_range;
4451                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
4452                                && primary.end.cmp(&range.start, buffer).is_ge();
4453                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
4454                                && range.end.cmp(&primary.end, buffer).is_ge();
4455
4456                            //Skip additional edits which overlap with the primary completion edit
4457                            //https://github.com/zed-industries/zed/pull/1871
4458                            if !start_within && !end_within {
4459                                buffer.edit([(range, text)], None, cx);
4460                            }
4461                        }
4462
4463                        let transaction = if buffer.end_transaction(cx).is_some() {
4464                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4465                            if !push_to_history {
4466                                buffer.forget_transaction(transaction.id);
4467                            }
4468                            Some(transaction)
4469                        } else {
4470                            None
4471                        };
4472                        Ok(transaction)
4473                    })
4474                } else {
4475                    Ok(None)
4476                }
4477            })
4478        } else if let Some(project_id) = self.remote_id() {
4479            let client = self.client.clone();
4480            cx.spawn(|_, mut cx| async move {
4481                let response = client
4482                    .request(proto::ApplyCompletionAdditionalEdits {
4483                        project_id,
4484                        buffer_id,
4485                        completion: Some(language::proto::serialize_completion(&completion)),
4486                    })
4487                    .await?;
4488
4489                if let Some(transaction) = response.transaction {
4490                    let transaction = language::proto::deserialize_transaction(transaction)?;
4491                    buffer_handle
4492                        .update(&mut cx, |buffer, _| {
4493                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4494                        })
4495                        .await?;
4496                    if push_to_history {
4497                        buffer_handle.update(&mut cx, |buffer, _| {
4498                            buffer.push_transaction(transaction.clone(), Instant::now());
4499                        });
4500                    }
4501                    Ok(Some(transaction))
4502                } else {
4503                    Ok(None)
4504                }
4505            })
4506        } else {
4507            Task::ready(Err(anyhow!("project does not have a remote id")))
4508        }
4509    }
4510
4511    pub fn code_actions<T: Clone + ToOffset>(
4512        &self,
4513        buffer_handle: &ModelHandle<Buffer>,
4514        range: Range<T>,
4515        cx: &mut ModelContext<Self>,
4516    ) -> Task<Result<Vec<CodeAction>>> {
4517        let buffer = buffer_handle.read(cx);
4518        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4519        self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
4520    }
4521
4522    pub fn apply_code_action(
4523        &self,
4524        buffer_handle: ModelHandle<Buffer>,
4525        mut action: CodeAction,
4526        push_to_history: bool,
4527        cx: &mut ModelContext<Self>,
4528    ) -> Task<Result<ProjectTransaction>> {
4529        if self.is_local() {
4530            let buffer = buffer_handle.read(cx);
4531            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4532                self.language_server_for_buffer(buffer, action.server_id, cx)
4533            {
4534                (adapter.clone(), server.clone())
4535            } else {
4536                return Task::ready(Ok(Default::default()));
4537            };
4538            let range = action.range.to_point_utf16(buffer);
4539
4540            cx.spawn(|this, mut cx| async move {
4541                if let Some(lsp_range) = action
4542                    .lsp_action
4543                    .data
4544                    .as_mut()
4545                    .and_then(|d| d.get_mut("codeActionParams"))
4546                    .and_then(|d| d.get_mut("range"))
4547                {
4548                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4549                    action.lsp_action = lang_server
4550                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4551                        .await?;
4552                } else {
4553                    let actions = this
4554                        .update(&mut cx, |this, cx| {
4555                            this.code_actions(&buffer_handle, action.range, cx)
4556                        })
4557                        .await?;
4558                    action.lsp_action = actions
4559                        .into_iter()
4560                        .find(|a| a.lsp_action.title == action.lsp_action.title)
4561                        .ok_or_else(|| anyhow!("code action is outdated"))?
4562                        .lsp_action;
4563                }
4564
4565                if let Some(edit) = action.lsp_action.edit {
4566                    if edit.changes.is_some() || edit.document_changes.is_some() {
4567                        return Self::deserialize_workspace_edit(
4568                            this,
4569                            edit,
4570                            push_to_history,
4571                            lsp_adapter.clone(),
4572                            lang_server.clone(),
4573                            &mut cx,
4574                        )
4575                        .await;
4576                    }
4577                }
4578
4579                if let Some(command) = action.lsp_action.command {
4580                    this.update(&mut cx, |this, _| {
4581                        this.last_workspace_edits_by_language_server
4582                            .remove(&lang_server.server_id());
4583                    });
4584
4585                    let result = lang_server
4586                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4587                            command: command.command,
4588                            arguments: command.arguments.unwrap_or_default(),
4589                            ..Default::default()
4590                        })
4591                        .await;
4592
4593                    if let Err(err) = result {
4594                        // TODO: LSP ERROR
4595                        return Err(err);
4596                    }
4597
4598                    return Ok(this.update(&mut cx, |this, _| {
4599                        this.last_workspace_edits_by_language_server
4600                            .remove(&lang_server.server_id())
4601                            .unwrap_or_default()
4602                    }));
4603                }
4604
4605                Ok(ProjectTransaction::default())
4606            })
4607        } else if let Some(project_id) = self.remote_id() {
4608            let client = self.client.clone();
4609            let request = proto::ApplyCodeAction {
4610                project_id,
4611                buffer_id: buffer_handle.read(cx).remote_id(),
4612                action: Some(language::proto::serialize_code_action(&action)),
4613            };
4614            cx.spawn(|this, mut cx| async move {
4615                let response = client
4616                    .request(request)
4617                    .await?
4618                    .transaction
4619                    .ok_or_else(|| anyhow!("missing transaction"))?;
4620                this.update(&mut cx, |this, cx| {
4621                    this.deserialize_project_transaction(response, push_to_history, cx)
4622                })
4623                .await
4624            })
4625        } else {
4626            Task::ready(Err(anyhow!("project does not have a remote id")))
4627        }
4628    }
4629
4630    fn apply_on_type_formatting(
4631        &self,
4632        buffer: ModelHandle<Buffer>,
4633        position: Anchor,
4634        trigger: String,
4635        cx: &mut ModelContext<Self>,
4636    ) -> Task<Result<Option<Transaction>>> {
4637        if self.is_local() {
4638            cx.spawn(|this, mut cx| async move {
4639                // Do not allow multiple concurrent formatting requests for the
4640                // same buffer.
4641                this.update(&mut cx, |this, cx| {
4642                    this.buffers_being_formatted
4643                        .insert(buffer.read(cx).remote_id())
4644                });
4645
4646                let _cleanup = defer({
4647                    let this = this.clone();
4648                    let mut cx = cx.clone();
4649                    let closure_buffer = buffer.clone();
4650                    move || {
4651                        this.update(&mut cx, |this, cx| {
4652                            this.buffers_being_formatted
4653                                .remove(&closure_buffer.read(cx).remote_id());
4654                        });
4655                    }
4656                });
4657
4658                buffer
4659                    .update(&mut cx, |buffer, _| {
4660                        buffer.wait_for_edits(Some(position.timestamp))
4661                    })
4662                    .await?;
4663                this.update(&mut cx, |this, cx| {
4664                    let position = position.to_point_utf16(buffer.read(cx));
4665                    this.on_type_format(buffer, position, trigger, false, cx)
4666                })
4667                .await
4668            })
4669        } else if let Some(project_id) = self.remote_id() {
4670            let client = self.client.clone();
4671            let request = proto::OnTypeFormatting {
4672                project_id,
4673                buffer_id: buffer.read(cx).remote_id(),
4674                position: Some(serialize_anchor(&position)),
4675                trigger,
4676                version: serialize_version(&buffer.read(cx).version()),
4677            };
4678            cx.spawn(|_, _| async move {
4679                client
4680                    .request(request)
4681                    .await?
4682                    .transaction
4683                    .map(language::proto::deserialize_transaction)
4684                    .transpose()
4685            })
4686        } else {
4687            Task::ready(Err(anyhow!("project does not have a remote id")))
4688        }
4689    }
4690
4691    async fn deserialize_edits(
4692        this: ModelHandle<Self>,
4693        buffer_to_edit: ModelHandle<Buffer>,
4694        edits: Vec<lsp::TextEdit>,
4695        push_to_history: bool,
4696        _: Arc<CachedLspAdapter>,
4697        language_server: Arc<LanguageServer>,
4698        cx: &mut AsyncAppContext,
4699    ) -> Result<Option<Transaction>> {
4700        let edits = this
4701            .update(cx, |this, cx| {
4702                this.edits_from_lsp(
4703                    &buffer_to_edit,
4704                    edits,
4705                    language_server.server_id(),
4706                    None,
4707                    cx,
4708                )
4709            })
4710            .await?;
4711
4712        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4713            buffer.finalize_last_transaction();
4714            buffer.start_transaction();
4715            for (range, text) in edits {
4716                buffer.edit([(range, text)], None, cx);
4717            }
4718
4719            if buffer.end_transaction(cx).is_some() {
4720                let transaction = buffer.finalize_last_transaction().unwrap().clone();
4721                if !push_to_history {
4722                    buffer.forget_transaction(transaction.id);
4723                }
4724                Some(transaction)
4725            } else {
4726                None
4727            }
4728        });
4729
4730        Ok(transaction)
4731    }
4732
4733    async fn deserialize_workspace_edit(
4734        this: ModelHandle<Self>,
4735        edit: lsp::WorkspaceEdit,
4736        push_to_history: bool,
4737        lsp_adapter: Arc<CachedLspAdapter>,
4738        language_server: Arc<LanguageServer>,
4739        cx: &mut AsyncAppContext,
4740    ) -> Result<ProjectTransaction> {
4741        let fs = this.read_with(cx, |this, _| this.fs.clone());
4742        let mut operations = Vec::new();
4743        if let Some(document_changes) = edit.document_changes {
4744            match document_changes {
4745                lsp::DocumentChanges::Edits(edits) => {
4746                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4747                }
4748                lsp::DocumentChanges::Operations(ops) => operations = ops,
4749            }
4750        } else if let Some(changes) = edit.changes {
4751            operations.extend(changes.into_iter().map(|(uri, edits)| {
4752                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4753                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4754                        uri,
4755                        version: None,
4756                    },
4757                    edits: edits.into_iter().map(OneOf::Left).collect(),
4758                })
4759            }));
4760        }
4761
4762        let mut project_transaction = ProjectTransaction::default();
4763        for operation in operations {
4764            match operation {
4765                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4766                    let abs_path = op
4767                        .uri
4768                        .to_file_path()
4769                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4770
4771                    if let Some(parent_path) = abs_path.parent() {
4772                        fs.create_dir(parent_path).await?;
4773                    }
4774                    if abs_path.ends_with("/") {
4775                        fs.create_dir(&abs_path).await?;
4776                    } else {
4777                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4778                            .await?;
4779                    }
4780                }
4781
4782                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4783                    let source_abs_path = op
4784                        .old_uri
4785                        .to_file_path()
4786                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4787                    let target_abs_path = op
4788                        .new_uri
4789                        .to_file_path()
4790                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4791                    fs.rename(
4792                        &source_abs_path,
4793                        &target_abs_path,
4794                        op.options.map(Into::into).unwrap_or_default(),
4795                    )
4796                    .await?;
4797                }
4798
4799                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4800                    let abs_path = op
4801                        .uri
4802                        .to_file_path()
4803                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4804                    let options = op.options.map(Into::into).unwrap_or_default();
4805                    if abs_path.ends_with("/") {
4806                        fs.remove_dir(&abs_path, options).await?;
4807                    } else {
4808                        fs.remove_file(&abs_path, options).await?;
4809                    }
4810                }
4811
4812                lsp::DocumentChangeOperation::Edit(op) => {
4813                    let buffer_to_edit = this
4814                        .update(cx, |this, cx| {
4815                            this.open_local_buffer_via_lsp(
4816                                op.text_document.uri,
4817                                language_server.server_id(),
4818                                lsp_adapter.name.clone(),
4819                                cx,
4820                            )
4821                        })
4822                        .await?;
4823
4824                    let edits = this
4825                        .update(cx, |this, cx| {
4826                            let edits = op.edits.into_iter().map(|edit| match edit {
4827                                OneOf::Left(edit) => edit,
4828                                OneOf::Right(edit) => edit.text_edit,
4829                            });
4830                            this.edits_from_lsp(
4831                                &buffer_to_edit,
4832                                edits,
4833                                language_server.server_id(),
4834                                op.text_document.version,
4835                                cx,
4836                            )
4837                        })
4838                        .await?;
4839
4840                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4841                        buffer.finalize_last_transaction();
4842                        buffer.start_transaction();
4843                        for (range, text) in edits {
4844                            buffer.edit([(range, text)], None, cx);
4845                        }
4846                        let transaction = if buffer.end_transaction(cx).is_some() {
4847                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4848                            if !push_to_history {
4849                                buffer.forget_transaction(transaction.id);
4850                            }
4851                            Some(transaction)
4852                        } else {
4853                            None
4854                        };
4855
4856                        transaction
4857                    });
4858                    if let Some(transaction) = transaction {
4859                        project_transaction.0.insert(buffer_to_edit, transaction);
4860                    }
4861                }
4862            }
4863        }
4864
4865        Ok(project_transaction)
4866    }
4867
4868    pub fn prepare_rename<T: ToPointUtf16>(
4869        &self,
4870        buffer: ModelHandle<Buffer>,
4871        position: T,
4872        cx: &mut ModelContext<Self>,
4873    ) -> Task<Result<Option<Range<Anchor>>>> {
4874        let position = position.to_point_utf16(buffer.read(cx));
4875        self.request_lsp(buffer, PrepareRename { position }, cx)
4876    }
4877
4878    pub fn perform_rename<T: ToPointUtf16>(
4879        &self,
4880        buffer: ModelHandle<Buffer>,
4881        position: T,
4882        new_name: String,
4883        push_to_history: bool,
4884        cx: &mut ModelContext<Self>,
4885    ) -> Task<Result<ProjectTransaction>> {
4886        let position = position.to_point_utf16(buffer.read(cx));
4887        self.request_lsp(
4888            buffer,
4889            PerformRename {
4890                position,
4891                new_name,
4892                push_to_history,
4893            },
4894            cx,
4895        )
4896    }
4897
4898    pub fn on_type_format<T: ToPointUtf16>(
4899        &self,
4900        buffer: ModelHandle<Buffer>,
4901        position: T,
4902        trigger: String,
4903        push_to_history: bool,
4904        cx: &mut ModelContext<Self>,
4905    ) -> Task<Result<Option<Transaction>>> {
4906        let (position, tab_size) = buffer.read_with(cx, |buffer, cx| {
4907            let position = position.to_point_utf16(buffer);
4908            (
4909                position,
4910                language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
4911                    .tab_size,
4912            )
4913        });
4914        self.request_lsp(
4915            buffer.clone(),
4916            OnTypeFormatting {
4917                position,
4918                trigger,
4919                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
4920                push_to_history,
4921            },
4922            cx,
4923        )
4924    }
4925
4926    pub fn inlay_hints<T: ToOffset>(
4927        &self,
4928        buffer_handle: ModelHandle<Buffer>,
4929        range: Range<T>,
4930        cx: &mut ModelContext<Self>,
4931    ) -> Task<Result<Vec<InlayHint>>> {
4932        let buffer = buffer_handle.read(cx);
4933        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4934        let range_start = range.start;
4935        let range_end = range.end;
4936        let buffer_id = buffer.remote_id();
4937        let buffer_version = buffer.version().clone();
4938        let lsp_request = InlayHints { range };
4939
4940        if self.is_local() {
4941            let lsp_request_task = self.request_lsp(buffer_handle.clone(), lsp_request, cx);
4942            cx.spawn(|_, mut cx| async move {
4943                buffer_handle
4944                    .update(&mut cx, |buffer, _| {
4945                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
4946                    })
4947                    .await
4948                    .context("waiting for inlay hint request range edits")?;
4949                lsp_request_task.await.context("inlay hints LSP request")
4950            })
4951        } else if let Some(project_id) = self.remote_id() {
4952            let client = self.client.clone();
4953            let request = proto::InlayHints {
4954                project_id,
4955                buffer_id,
4956                start: Some(serialize_anchor(&range_start)),
4957                end: Some(serialize_anchor(&range_end)),
4958                version: serialize_version(&buffer_version),
4959            };
4960            cx.spawn(|project, cx| async move {
4961                let response = client
4962                    .request(request)
4963                    .await
4964                    .context("inlay hints proto request")?;
4965                let hints_request_result = LspCommand::response_from_proto(
4966                    lsp_request,
4967                    response,
4968                    project,
4969                    buffer_handle.clone(),
4970                    cx,
4971                )
4972                .await;
4973
4974                hints_request_result.context("inlay hints proto response conversion")
4975            })
4976        } else {
4977            Task::ready(Err(anyhow!("project does not have a remote id")))
4978        }
4979    }
4980
4981    #[allow(clippy::type_complexity)]
4982    pub fn search(
4983        &self,
4984        query: SearchQuery,
4985        cx: &mut ModelContext<Self>,
4986    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4987        if self.is_local() {
4988            let snapshots = self
4989                .visible_worktrees(cx)
4990                .filter_map(|tree| {
4991                    let tree = tree.read(cx).as_local()?;
4992                    Some(tree.snapshot())
4993                })
4994                .collect::<Vec<_>>();
4995
4996            let background = cx.background().clone();
4997            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4998            if path_count == 0 {
4999                return Task::ready(Ok(Default::default()));
5000            }
5001            let workers = background.num_cpus().min(path_count);
5002            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
5003            cx.background()
5004                .spawn({
5005                    let fs = self.fs.clone();
5006                    let background = cx.background().clone();
5007                    let query = query.clone();
5008                    async move {
5009                        let fs = &fs;
5010                        let query = &query;
5011                        let matching_paths_tx = &matching_paths_tx;
5012                        let paths_per_worker = (path_count + workers - 1) / workers;
5013                        let snapshots = &snapshots;
5014                        background
5015                            .scoped(|scope| {
5016                                for worker_ix in 0..workers {
5017                                    let worker_start_ix = worker_ix * paths_per_worker;
5018                                    let worker_end_ix = worker_start_ix + paths_per_worker;
5019                                    scope.spawn(async move {
5020                                        let mut snapshot_start_ix = 0;
5021                                        let mut abs_path = PathBuf::new();
5022                                        for snapshot in snapshots {
5023                                            let snapshot_end_ix =
5024                                                snapshot_start_ix + snapshot.visible_file_count();
5025                                            if worker_end_ix <= snapshot_start_ix {
5026                                                break;
5027                                            } else if worker_start_ix > snapshot_end_ix {
5028                                                snapshot_start_ix = snapshot_end_ix;
5029                                                continue;
5030                                            } else {
5031                                                let start_in_snapshot = worker_start_ix
5032                                                    .saturating_sub(snapshot_start_ix);
5033                                                let end_in_snapshot =
5034                                                    cmp::min(worker_end_ix, snapshot_end_ix)
5035                                                        - snapshot_start_ix;
5036
5037                                                for entry in snapshot
5038                                                    .files(false, start_in_snapshot)
5039                                                    .take(end_in_snapshot - start_in_snapshot)
5040                                                {
5041                                                    if matching_paths_tx.is_closed() {
5042                                                        break;
5043                                                    }
5044                                                    let matches = if query
5045                                                        .file_matches(Some(&entry.path))
5046                                                    {
5047                                                        abs_path.clear();
5048                                                        abs_path.push(&snapshot.abs_path());
5049                                                        abs_path.push(&entry.path);
5050                                                        if let Some(file) =
5051                                                            fs.open_sync(&abs_path).await.log_err()
5052                                                        {
5053                                                            query.detect(file).unwrap_or(false)
5054                                                        } else {
5055                                                            false
5056                                                        }
5057                                                    } else {
5058                                                        false
5059                                                    };
5060
5061                                                    if matches {
5062                                                        let project_path =
5063                                                            (snapshot.id(), entry.path.clone());
5064                                                        if matching_paths_tx
5065                                                            .send(project_path)
5066                                                            .await
5067                                                            .is_err()
5068                                                        {
5069                                                            break;
5070                                                        }
5071                                                    }
5072                                                }
5073
5074                                                snapshot_start_ix = snapshot_end_ix;
5075                                            }
5076                                        }
5077                                    });
5078                                }
5079                            })
5080                            .await;
5081                    }
5082                })
5083                .detach();
5084
5085            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
5086            let open_buffers = self
5087                .opened_buffers
5088                .values()
5089                .filter_map(|b| b.upgrade(cx))
5090                .collect::<HashSet<_>>();
5091            cx.spawn(|this, cx| async move {
5092                for buffer in &open_buffers {
5093                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5094                    buffers_tx.send((buffer.clone(), snapshot)).await?;
5095                }
5096
5097                let open_buffers = Rc::new(RefCell::new(open_buffers));
5098                while let Some(project_path) = matching_paths_rx.next().await {
5099                    if buffers_tx.is_closed() {
5100                        break;
5101                    }
5102
5103                    let this = this.clone();
5104                    let open_buffers = open_buffers.clone();
5105                    let buffers_tx = buffers_tx.clone();
5106                    cx.spawn(|mut cx| async move {
5107                        if let Some(buffer) = this
5108                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
5109                            .await
5110                            .log_err()
5111                        {
5112                            if open_buffers.borrow_mut().insert(buffer.clone()) {
5113                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5114                                buffers_tx.send((buffer, snapshot)).await?;
5115                            }
5116                        }
5117
5118                        Ok::<_, anyhow::Error>(())
5119                    })
5120                    .detach();
5121                }
5122
5123                Ok::<_, anyhow::Error>(())
5124            })
5125            .detach_and_log_err(cx);
5126
5127            let background = cx.background().clone();
5128            cx.background().spawn(async move {
5129                let query = &query;
5130                let mut matched_buffers = Vec::new();
5131                for _ in 0..workers {
5132                    matched_buffers.push(HashMap::default());
5133                }
5134                background
5135                    .scoped(|scope| {
5136                        for worker_matched_buffers in matched_buffers.iter_mut() {
5137                            let mut buffers_rx = buffers_rx.clone();
5138                            scope.spawn(async move {
5139                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
5140                                    let buffer_matches = if query.file_matches(
5141                                        snapshot.file().map(|file| file.path().as_ref()),
5142                                    ) {
5143                                        query
5144                                            .search(snapshot.as_rope())
5145                                            .await
5146                                            .iter()
5147                                            .map(|range| {
5148                                                snapshot.anchor_before(range.start)
5149                                                    ..snapshot.anchor_after(range.end)
5150                                            })
5151                                            .collect()
5152                                    } else {
5153                                        Vec::new()
5154                                    };
5155                                    if !buffer_matches.is_empty() {
5156                                        worker_matched_buffers
5157                                            .insert(buffer.clone(), buffer_matches);
5158                                    }
5159                                }
5160                            });
5161                        }
5162                    })
5163                    .await;
5164                Ok(matched_buffers.into_iter().flatten().collect())
5165            })
5166        } else if let Some(project_id) = self.remote_id() {
5167            let request = self.client.request(query.to_proto(project_id));
5168            cx.spawn(|this, mut cx| async move {
5169                let response = request.await?;
5170                let mut result = HashMap::default();
5171                for location in response.locations {
5172                    let target_buffer = this
5173                        .update(&mut cx, |this, cx| {
5174                            this.wait_for_remote_buffer(location.buffer_id, cx)
5175                        })
5176                        .await?;
5177                    let start = location
5178                        .start
5179                        .and_then(deserialize_anchor)
5180                        .ok_or_else(|| anyhow!("missing target start"))?;
5181                    let end = location
5182                        .end
5183                        .and_then(deserialize_anchor)
5184                        .ok_or_else(|| anyhow!("missing target end"))?;
5185                    result
5186                        .entry(target_buffer)
5187                        .or_insert(Vec::new())
5188                        .push(start..end)
5189                }
5190                Ok(result)
5191            })
5192        } else {
5193            Task::ready(Ok(Default::default()))
5194        }
5195    }
5196
5197    // TODO: Wire this up to allow selecting a server?
5198    fn request_lsp<R: LspCommand>(
5199        &self,
5200        buffer_handle: ModelHandle<Buffer>,
5201        request: R,
5202        cx: &mut ModelContext<Self>,
5203    ) -> Task<Result<R::Response>>
5204    where
5205        <R::LspRequest as lsp::request::Request>::Result: Send,
5206    {
5207        let buffer = buffer_handle.read(cx);
5208        if self.is_local() {
5209            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5210            if let Some((file, language_server)) = file.zip(
5211                self.primary_language_servers_for_buffer(buffer, cx)
5212                    .map(|(_, server)| server.clone()),
5213            ) {
5214                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5215                return cx.spawn(|this, cx| async move {
5216                    if !request.check_capabilities(language_server.capabilities()) {
5217                        return Ok(Default::default());
5218                    }
5219
5220                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
5221                    let response = match result {
5222                        Ok(response) => response,
5223
5224                        Err(err) => {
5225                            log::warn!(
5226                                "Generic lsp request to {} failed: {}",
5227                                language_server.name(),
5228                                err
5229                            );
5230                            return Err(err);
5231                        }
5232                    };
5233
5234                    request
5235                        .response_from_lsp(
5236                            response,
5237                            this,
5238                            buffer_handle,
5239                            language_server.server_id(),
5240                            cx,
5241                        )
5242                        .await
5243                });
5244            }
5245        } else if let Some(project_id) = self.remote_id() {
5246            let rpc = self.client.clone();
5247            let message = request.to_proto(project_id, buffer);
5248            return cx.spawn_weak(|this, cx| async move {
5249                // Ensure the project is still alive by the time the task
5250                // is scheduled.
5251                this.upgrade(&cx)
5252                    .ok_or_else(|| anyhow!("project dropped"))?;
5253
5254                let response = rpc.request(message).await?;
5255
5256                let this = this
5257                    .upgrade(&cx)
5258                    .ok_or_else(|| anyhow!("project dropped"))?;
5259                if this.read_with(&cx, |this, _| this.is_read_only()) {
5260                    Err(anyhow!("disconnected before completing request"))
5261                } else {
5262                    request
5263                        .response_from_proto(response, this, buffer_handle, cx)
5264                        .await
5265                }
5266            });
5267        }
5268        Task::ready(Ok(Default::default()))
5269    }
5270
5271    pub fn find_or_create_local_worktree(
5272        &mut self,
5273        abs_path: impl AsRef<Path>,
5274        visible: bool,
5275        cx: &mut ModelContext<Self>,
5276    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
5277        let abs_path = abs_path.as_ref();
5278        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
5279            Task::ready(Ok((tree, relative_path)))
5280        } else {
5281            let worktree = self.create_local_worktree(abs_path, visible, cx);
5282            cx.foreground()
5283                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
5284        }
5285    }
5286
5287    pub fn find_local_worktree(
5288        &self,
5289        abs_path: &Path,
5290        cx: &AppContext,
5291    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
5292        for tree in &self.worktrees {
5293            if let Some(tree) = tree.upgrade(cx) {
5294                if let Some(relative_path) = tree
5295                    .read(cx)
5296                    .as_local()
5297                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
5298                {
5299                    return Some((tree.clone(), relative_path.into()));
5300                }
5301            }
5302        }
5303        None
5304    }
5305
5306    pub fn is_shared(&self) -> bool {
5307        match &self.client_state {
5308            Some(ProjectClientState::Local { .. }) => true,
5309            _ => false,
5310        }
5311    }
5312
5313    fn create_local_worktree(
5314        &mut self,
5315        abs_path: impl AsRef<Path>,
5316        visible: bool,
5317        cx: &mut ModelContext<Self>,
5318    ) -> Task<Result<ModelHandle<Worktree>>> {
5319        let fs = self.fs.clone();
5320        let client = self.client.clone();
5321        let next_entry_id = self.next_entry_id.clone();
5322        let path: Arc<Path> = abs_path.as_ref().into();
5323        let task = self
5324            .loading_local_worktrees
5325            .entry(path.clone())
5326            .or_insert_with(|| {
5327                cx.spawn(|project, mut cx| {
5328                    async move {
5329                        let worktree = Worktree::local(
5330                            client.clone(),
5331                            path.clone(),
5332                            visible,
5333                            fs,
5334                            next_entry_id,
5335                            &mut cx,
5336                        )
5337                        .await;
5338
5339                        project.update(&mut cx, |project, _| {
5340                            project.loading_local_worktrees.remove(&path);
5341                        });
5342
5343                        let worktree = worktree?;
5344                        project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
5345                        Ok(worktree)
5346                    }
5347                    .map_err(Arc::new)
5348                })
5349                .shared()
5350            })
5351            .clone();
5352        cx.foreground().spawn(async move {
5353            match task.await {
5354                Ok(worktree) => Ok(worktree),
5355                Err(err) => Err(anyhow!("{}", err)),
5356            }
5357        })
5358    }
5359
5360    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
5361        self.worktrees.retain(|worktree| {
5362            if let Some(worktree) = worktree.upgrade(cx) {
5363                let id = worktree.read(cx).id();
5364                if id == id_to_remove {
5365                    cx.emit(Event::WorktreeRemoved(id));
5366                    false
5367                } else {
5368                    true
5369                }
5370            } else {
5371                false
5372            }
5373        });
5374        self.metadata_changed(cx);
5375    }
5376
5377    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
5378        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
5379        if worktree.read(cx).is_local() {
5380            cx.subscribe(worktree, |this, worktree, event, cx| match event {
5381                worktree::Event::UpdatedEntries(changes) => {
5382                    this.update_local_worktree_buffers(&worktree, changes, cx);
5383                    this.update_local_worktree_language_servers(&worktree, changes, cx);
5384                    this.update_local_worktree_settings(&worktree, changes, cx);
5385                }
5386                worktree::Event::UpdatedGitRepositories(updated_repos) => {
5387                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
5388                }
5389            })
5390            .detach();
5391        }
5392
5393        let push_strong_handle = {
5394            let worktree = worktree.read(cx);
5395            self.is_shared() || worktree.is_visible() || worktree.is_remote()
5396        };
5397        if push_strong_handle {
5398            self.worktrees
5399                .push(WorktreeHandle::Strong(worktree.clone()));
5400        } else {
5401            self.worktrees
5402                .push(WorktreeHandle::Weak(worktree.downgrade()));
5403        }
5404
5405        let handle_id = worktree.id();
5406        cx.observe_release(worktree, move |this, worktree, cx| {
5407            let _ = this.remove_worktree(worktree.id(), cx);
5408            cx.update_global::<SettingsStore, _, _>(|store, cx| {
5409                store.clear_local_settings(handle_id, cx).log_err()
5410            });
5411        })
5412        .detach();
5413
5414        cx.emit(Event::WorktreeAdded);
5415        self.metadata_changed(cx);
5416    }
5417
5418    fn update_local_worktree_buffers(
5419        &mut self,
5420        worktree_handle: &ModelHandle<Worktree>,
5421        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5422        cx: &mut ModelContext<Self>,
5423    ) {
5424        let snapshot = worktree_handle.read(cx).snapshot();
5425
5426        let mut renamed_buffers = Vec::new();
5427        for (path, entry_id, _) in changes {
5428            let worktree_id = worktree_handle.read(cx).id();
5429            let project_path = ProjectPath {
5430                worktree_id,
5431                path: path.clone(),
5432            };
5433
5434            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
5435                Some(&buffer_id) => buffer_id,
5436                None => match self.local_buffer_ids_by_path.get(&project_path) {
5437                    Some(&buffer_id) => buffer_id,
5438                    None => continue,
5439                },
5440            };
5441
5442            let open_buffer = self.opened_buffers.get(&buffer_id);
5443            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
5444                buffer
5445            } else {
5446                self.opened_buffers.remove(&buffer_id);
5447                self.local_buffer_ids_by_path.remove(&project_path);
5448                self.local_buffer_ids_by_entry_id.remove(entry_id);
5449                continue;
5450            };
5451
5452            buffer.update(cx, |buffer, cx| {
5453                if let Some(old_file) = File::from_dyn(buffer.file()) {
5454                    if old_file.worktree != *worktree_handle {
5455                        return;
5456                    }
5457
5458                    let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
5459                        File {
5460                            is_local: true,
5461                            entry_id: entry.id,
5462                            mtime: entry.mtime,
5463                            path: entry.path.clone(),
5464                            worktree: worktree_handle.clone(),
5465                            is_deleted: false,
5466                        }
5467                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
5468                        File {
5469                            is_local: true,
5470                            entry_id: entry.id,
5471                            mtime: entry.mtime,
5472                            path: entry.path.clone(),
5473                            worktree: worktree_handle.clone(),
5474                            is_deleted: false,
5475                        }
5476                    } else {
5477                        File {
5478                            is_local: true,
5479                            entry_id: old_file.entry_id,
5480                            path: old_file.path().clone(),
5481                            mtime: old_file.mtime(),
5482                            worktree: worktree_handle.clone(),
5483                            is_deleted: true,
5484                        }
5485                    };
5486
5487                    let old_path = old_file.abs_path(cx);
5488                    if new_file.abs_path(cx) != old_path {
5489                        renamed_buffers.push((cx.handle(), old_file.clone()));
5490                        self.local_buffer_ids_by_path.remove(&project_path);
5491                        self.local_buffer_ids_by_path.insert(
5492                            ProjectPath {
5493                                worktree_id,
5494                                path: path.clone(),
5495                            },
5496                            buffer_id,
5497                        );
5498                    }
5499
5500                    if new_file.entry_id != *entry_id {
5501                        self.local_buffer_ids_by_entry_id.remove(entry_id);
5502                        self.local_buffer_ids_by_entry_id
5503                            .insert(new_file.entry_id, buffer_id);
5504                    }
5505
5506                    if new_file != *old_file {
5507                        if let Some(project_id) = self.remote_id() {
5508                            self.client
5509                                .send(proto::UpdateBufferFile {
5510                                    project_id,
5511                                    buffer_id: buffer_id as u64,
5512                                    file: Some(new_file.to_proto()),
5513                                })
5514                                .log_err();
5515                        }
5516
5517                        buffer.file_updated(Arc::new(new_file), cx).detach();
5518                    }
5519                }
5520            });
5521        }
5522
5523        for (buffer, old_file) in renamed_buffers {
5524            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
5525            self.detect_language_for_buffer(&buffer, cx);
5526            self.register_buffer_with_language_servers(&buffer, cx);
5527        }
5528    }
5529
5530    fn update_local_worktree_language_servers(
5531        &mut self,
5532        worktree_handle: &ModelHandle<Worktree>,
5533        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5534        cx: &mut ModelContext<Self>,
5535    ) {
5536        if changes.is_empty() {
5537            return;
5538        }
5539
5540        let worktree_id = worktree_handle.read(cx).id();
5541        let mut language_server_ids = self
5542            .language_server_ids
5543            .iter()
5544            .filter_map(|((server_worktree_id, _), server_id)| {
5545                (*server_worktree_id == worktree_id).then_some(*server_id)
5546            })
5547            .collect::<Vec<_>>();
5548        language_server_ids.sort();
5549        language_server_ids.dedup();
5550
5551        let abs_path = worktree_handle.read(cx).abs_path();
5552        for server_id in &language_server_ids {
5553            if let Some(LanguageServerState::Running {
5554                server,
5555                watched_paths,
5556                ..
5557            }) = self.language_servers.get(server_id)
5558            {
5559                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
5560                    let params = lsp::DidChangeWatchedFilesParams {
5561                        changes: changes
5562                            .iter()
5563                            .filter_map(|(path, _, change)| {
5564                                if !watched_paths.is_match(&path) {
5565                                    return None;
5566                                }
5567                                let typ = match change {
5568                                    PathChange::Loaded => return None,
5569                                    PathChange::Added => lsp::FileChangeType::CREATED,
5570                                    PathChange::Removed => lsp::FileChangeType::DELETED,
5571                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
5572                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
5573                                };
5574                                Some(lsp::FileEvent {
5575                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
5576                                    typ,
5577                                })
5578                            })
5579                            .collect(),
5580                    };
5581
5582                    if !params.changes.is_empty() {
5583                        server
5584                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
5585                            .log_err();
5586                    }
5587                }
5588            }
5589        }
5590    }
5591
5592    fn update_local_worktree_buffers_git_repos(
5593        &mut self,
5594        worktree_handle: ModelHandle<Worktree>,
5595        changed_repos: &UpdatedGitRepositoriesSet,
5596        cx: &mut ModelContext<Self>,
5597    ) {
5598        debug_assert!(worktree_handle.read(cx).is_local());
5599
5600        // Identify the loading buffers whose containing repository that has changed.
5601        let future_buffers = self
5602            .loading_buffers_by_path
5603            .iter()
5604            .filter_map(|(project_path, receiver)| {
5605                if project_path.worktree_id != worktree_handle.read(cx).id() {
5606                    return None;
5607                }
5608                let path = &project_path.path;
5609                changed_repos
5610                    .iter()
5611                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
5612                let receiver = receiver.clone();
5613                let path = path.clone();
5614                Some(async move {
5615                    wait_for_loading_buffer(receiver)
5616                        .await
5617                        .ok()
5618                        .map(|buffer| (buffer, path))
5619                })
5620            })
5621            .collect::<FuturesUnordered<_>>();
5622
5623        // Identify the current buffers whose containing repository has changed.
5624        let current_buffers = self
5625            .opened_buffers
5626            .values()
5627            .filter_map(|buffer| {
5628                let buffer = buffer.upgrade(cx)?;
5629                let file = File::from_dyn(buffer.read(cx).file())?;
5630                if file.worktree != worktree_handle {
5631                    return None;
5632                }
5633                let path = file.path();
5634                changed_repos
5635                    .iter()
5636                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
5637                Some((buffer, path.clone()))
5638            })
5639            .collect::<Vec<_>>();
5640
5641        if future_buffers.len() + current_buffers.len() == 0 {
5642            return;
5643        }
5644
5645        let remote_id = self.remote_id();
5646        let client = self.client.clone();
5647        cx.spawn_weak(move |_, mut cx| async move {
5648            // Wait for all of the buffers to load.
5649            let future_buffers = future_buffers.collect::<Vec<_>>().await;
5650
5651            // Reload the diff base for every buffer whose containing git repository has changed.
5652            let snapshot =
5653                worktree_handle.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
5654            let diff_bases_by_buffer = cx
5655                .background()
5656                .spawn(async move {
5657                    future_buffers
5658                        .into_iter()
5659                        .filter_map(|e| e)
5660                        .chain(current_buffers)
5661                        .filter_map(|(buffer, path)| {
5662                            let (work_directory, repo) =
5663                                snapshot.repository_and_work_directory_for_path(&path)?;
5664                            let repo = snapshot.get_local_repo(&repo)?;
5665                            let relative_path = path.strip_prefix(&work_directory).ok()?;
5666                            let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
5667                            Some((buffer, base_text))
5668                        })
5669                        .collect::<Vec<_>>()
5670                })
5671                .await;
5672
5673            // Assign the new diff bases on all of the buffers.
5674            for (buffer, diff_base) in diff_bases_by_buffer {
5675                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
5676                    buffer.set_diff_base(diff_base.clone(), cx);
5677                    buffer.remote_id()
5678                });
5679                if let Some(project_id) = remote_id {
5680                    client
5681                        .send(proto::UpdateDiffBase {
5682                            project_id,
5683                            buffer_id,
5684                            diff_base,
5685                        })
5686                        .log_err();
5687                }
5688            }
5689        })
5690        .detach();
5691    }
5692
5693    fn update_local_worktree_settings(
5694        &mut self,
5695        worktree: &ModelHandle<Worktree>,
5696        changes: &UpdatedEntriesSet,
5697        cx: &mut ModelContext<Self>,
5698    ) {
5699        let project_id = self.remote_id();
5700        let worktree_id = worktree.id();
5701        let worktree = worktree.read(cx).as_local().unwrap();
5702        let remote_worktree_id = worktree.id();
5703
5704        let mut settings_contents = Vec::new();
5705        for (path, _, change) in changes.iter() {
5706            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
5707                let settings_dir = Arc::from(
5708                    path.ancestors()
5709                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
5710                        .unwrap(),
5711                );
5712                let fs = self.fs.clone();
5713                let removed = *change == PathChange::Removed;
5714                let abs_path = worktree.absolutize(path);
5715                settings_contents.push(async move {
5716                    (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
5717                });
5718            }
5719        }
5720
5721        if settings_contents.is_empty() {
5722            return;
5723        }
5724
5725        let client = self.client.clone();
5726        cx.spawn_weak(move |_, mut cx| async move {
5727            let settings_contents: Vec<(Arc<Path>, _)> =
5728                futures::future::join_all(settings_contents).await;
5729            cx.update(|cx| {
5730                cx.update_global::<SettingsStore, _, _>(|store, cx| {
5731                    for (directory, file_content) in settings_contents {
5732                        let file_content = file_content.and_then(|content| content.log_err());
5733                        store
5734                            .set_local_settings(
5735                                worktree_id,
5736                                directory.clone(),
5737                                file_content.as_ref().map(String::as_str),
5738                                cx,
5739                            )
5740                            .log_err();
5741                        if let Some(remote_id) = project_id {
5742                            client
5743                                .send(proto::UpdateWorktreeSettings {
5744                                    project_id: remote_id,
5745                                    worktree_id: remote_worktree_id.to_proto(),
5746                                    path: directory.to_string_lossy().into_owned(),
5747                                    content: file_content,
5748                                })
5749                                .log_err();
5750                        }
5751                    }
5752                });
5753            });
5754        })
5755        .detach();
5756    }
5757
5758    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
5759        let new_active_entry = entry.and_then(|project_path| {
5760            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
5761            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
5762            Some(entry.id)
5763        });
5764        if new_active_entry != self.active_entry {
5765            self.active_entry = new_active_entry;
5766            cx.emit(Event::ActiveEntryChanged(new_active_entry));
5767        }
5768    }
5769
5770    pub fn language_servers_running_disk_based_diagnostics(
5771        &self,
5772    ) -> impl Iterator<Item = LanguageServerId> + '_ {
5773        self.language_server_statuses
5774            .iter()
5775            .filter_map(|(id, status)| {
5776                if status.has_pending_diagnostic_updates {
5777                    Some(*id)
5778                } else {
5779                    None
5780                }
5781            })
5782    }
5783
5784    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
5785        let mut summary = DiagnosticSummary::default();
5786        for (_, _, path_summary) in self.diagnostic_summaries(cx) {
5787            summary.error_count += path_summary.error_count;
5788            summary.warning_count += path_summary.warning_count;
5789        }
5790        summary
5791    }
5792
5793    pub fn diagnostic_summaries<'a>(
5794        &'a self,
5795        cx: &'a AppContext,
5796    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
5797        self.visible_worktrees(cx).flat_map(move |worktree| {
5798            let worktree = worktree.read(cx);
5799            let worktree_id = worktree.id();
5800            worktree
5801                .diagnostic_summaries()
5802                .map(move |(path, server_id, summary)| {
5803                    (ProjectPath { worktree_id, path }, server_id, summary)
5804                })
5805        })
5806    }
5807
5808    pub fn disk_based_diagnostics_started(
5809        &mut self,
5810        language_server_id: LanguageServerId,
5811        cx: &mut ModelContext<Self>,
5812    ) {
5813        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
5814    }
5815
5816    pub fn disk_based_diagnostics_finished(
5817        &mut self,
5818        language_server_id: LanguageServerId,
5819        cx: &mut ModelContext<Self>,
5820    ) {
5821        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
5822    }
5823
5824    pub fn active_entry(&self) -> Option<ProjectEntryId> {
5825        self.active_entry
5826    }
5827
5828    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
5829        self.worktree_for_id(path.worktree_id, cx)?
5830            .read(cx)
5831            .entry_for_path(&path.path)
5832            .cloned()
5833    }
5834
5835    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
5836        let worktree = self.worktree_for_entry(entry_id, cx)?;
5837        let worktree = worktree.read(cx);
5838        let worktree_id = worktree.id();
5839        let path = worktree.entry_for_id(entry_id)?.path.clone();
5840        Some(ProjectPath { worktree_id, path })
5841    }
5842
5843    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
5844        let workspace_root = self
5845            .worktree_for_id(project_path.worktree_id, cx)?
5846            .read(cx)
5847            .abs_path();
5848        let project_path = project_path.path.as_ref();
5849
5850        Some(if project_path == Path::new("") {
5851            workspace_root.to_path_buf()
5852        } else {
5853            workspace_root.join(project_path)
5854        })
5855    }
5856
5857    // RPC message handlers
5858
5859    async fn handle_unshare_project(
5860        this: ModelHandle<Self>,
5861        _: TypedEnvelope<proto::UnshareProject>,
5862        _: Arc<Client>,
5863        mut cx: AsyncAppContext,
5864    ) -> Result<()> {
5865        this.update(&mut cx, |this, cx| {
5866            if this.is_local() {
5867                this.unshare(cx)?;
5868            } else {
5869                this.disconnected_from_host(cx);
5870            }
5871            Ok(())
5872        })
5873    }
5874
5875    async fn handle_add_collaborator(
5876        this: ModelHandle<Self>,
5877        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
5878        _: Arc<Client>,
5879        mut cx: AsyncAppContext,
5880    ) -> Result<()> {
5881        let collaborator = envelope
5882            .payload
5883            .collaborator
5884            .take()
5885            .ok_or_else(|| anyhow!("empty collaborator"))?;
5886
5887        let collaborator = Collaborator::from_proto(collaborator)?;
5888        this.update(&mut cx, |this, cx| {
5889            this.shared_buffers.remove(&collaborator.peer_id);
5890            this.collaborators
5891                .insert(collaborator.peer_id, collaborator);
5892            cx.notify();
5893        });
5894
5895        Ok(())
5896    }
5897
5898    async fn handle_update_project_collaborator(
5899        this: ModelHandle<Self>,
5900        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
5901        _: Arc<Client>,
5902        mut cx: AsyncAppContext,
5903    ) -> Result<()> {
5904        let old_peer_id = envelope
5905            .payload
5906            .old_peer_id
5907            .ok_or_else(|| anyhow!("missing old peer id"))?;
5908        let new_peer_id = envelope
5909            .payload
5910            .new_peer_id
5911            .ok_or_else(|| anyhow!("missing new peer id"))?;
5912        this.update(&mut cx, |this, cx| {
5913            let collaborator = this
5914                .collaborators
5915                .remove(&old_peer_id)
5916                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
5917            let is_host = collaborator.replica_id == 0;
5918            this.collaborators.insert(new_peer_id, collaborator);
5919
5920            let buffers = this.shared_buffers.remove(&old_peer_id);
5921            log::info!(
5922                "peer {} became {}. moving buffers {:?}",
5923                old_peer_id,
5924                new_peer_id,
5925                &buffers
5926            );
5927            if let Some(buffers) = buffers {
5928                this.shared_buffers.insert(new_peer_id, buffers);
5929            }
5930
5931            if is_host {
5932                this.opened_buffers
5933                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
5934                this.buffer_ordered_messages_tx
5935                    .unbounded_send(BufferOrderedMessage::Resync)
5936                    .unwrap();
5937            }
5938
5939            cx.emit(Event::CollaboratorUpdated {
5940                old_peer_id,
5941                new_peer_id,
5942            });
5943            cx.notify();
5944            Ok(())
5945        })
5946    }
5947
5948    async fn handle_remove_collaborator(
5949        this: ModelHandle<Self>,
5950        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5951        _: Arc<Client>,
5952        mut cx: AsyncAppContext,
5953    ) -> Result<()> {
5954        this.update(&mut cx, |this, cx| {
5955            let peer_id = envelope
5956                .payload
5957                .peer_id
5958                .ok_or_else(|| anyhow!("invalid peer id"))?;
5959            let replica_id = this
5960                .collaborators
5961                .remove(&peer_id)
5962                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
5963                .replica_id;
5964            for buffer in this.opened_buffers.values() {
5965                if let Some(buffer) = buffer.upgrade(cx) {
5966                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5967                }
5968            }
5969            this.shared_buffers.remove(&peer_id);
5970
5971            cx.emit(Event::CollaboratorLeft(peer_id));
5972            cx.notify();
5973            Ok(())
5974        })
5975    }
5976
5977    async fn handle_update_project(
5978        this: ModelHandle<Self>,
5979        envelope: TypedEnvelope<proto::UpdateProject>,
5980        _: Arc<Client>,
5981        mut cx: AsyncAppContext,
5982    ) -> Result<()> {
5983        this.update(&mut cx, |this, cx| {
5984            // Don't handle messages that were sent before the response to us joining the project
5985            if envelope.message_id > this.join_project_response_message_id {
5986                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5987            }
5988            Ok(())
5989        })
5990    }
5991
5992    async fn handle_update_worktree(
5993        this: ModelHandle<Self>,
5994        envelope: TypedEnvelope<proto::UpdateWorktree>,
5995        _: Arc<Client>,
5996        mut cx: AsyncAppContext,
5997    ) -> Result<()> {
5998        this.update(&mut cx, |this, cx| {
5999            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6000            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6001                worktree.update(cx, |worktree, _| {
6002                    let worktree = worktree.as_remote_mut().unwrap();
6003                    worktree.update_from_remote(envelope.payload);
6004                });
6005            }
6006            Ok(())
6007        })
6008    }
6009
6010    async fn handle_update_worktree_settings(
6011        this: ModelHandle<Self>,
6012        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6013        _: Arc<Client>,
6014        mut cx: AsyncAppContext,
6015    ) -> Result<()> {
6016        this.update(&mut cx, |this, cx| {
6017            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6018            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6019                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6020                    store
6021                        .set_local_settings(
6022                            worktree.id(),
6023                            PathBuf::from(&envelope.payload.path).into(),
6024                            envelope.payload.content.as_ref().map(String::as_str),
6025                            cx,
6026                        )
6027                        .log_err();
6028                });
6029            }
6030            Ok(())
6031        })
6032    }
6033
6034    async fn handle_create_project_entry(
6035        this: ModelHandle<Self>,
6036        envelope: TypedEnvelope<proto::CreateProjectEntry>,
6037        _: Arc<Client>,
6038        mut cx: AsyncAppContext,
6039    ) -> Result<proto::ProjectEntryResponse> {
6040        let worktree = this.update(&mut cx, |this, cx| {
6041            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6042            this.worktree_for_id(worktree_id, cx)
6043                .ok_or_else(|| anyhow!("worktree not found"))
6044        })?;
6045        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6046        let entry = worktree
6047            .update(&mut cx, |worktree, cx| {
6048                let worktree = worktree.as_local_mut().unwrap();
6049                let path = PathBuf::from(envelope.payload.path);
6050                worktree.create_entry(path, envelope.payload.is_directory, cx)
6051            })
6052            .await?;
6053        Ok(proto::ProjectEntryResponse {
6054            entry: Some((&entry).into()),
6055            worktree_scan_id: worktree_scan_id as u64,
6056        })
6057    }
6058
6059    async fn handle_rename_project_entry(
6060        this: ModelHandle<Self>,
6061        envelope: TypedEnvelope<proto::RenameProjectEntry>,
6062        _: Arc<Client>,
6063        mut cx: AsyncAppContext,
6064    ) -> Result<proto::ProjectEntryResponse> {
6065        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6066        let worktree = this.read_with(&cx, |this, cx| {
6067            this.worktree_for_entry(entry_id, cx)
6068                .ok_or_else(|| anyhow!("worktree not found"))
6069        })?;
6070        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6071        let entry = worktree
6072            .update(&mut cx, |worktree, cx| {
6073                let new_path = PathBuf::from(envelope.payload.new_path);
6074                worktree
6075                    .as_local_mut()
6076                    .unwrap()
6077                    .rename_entry(entry_id, new_path, cx)
6078                    .ok_or_else(|| anyhow!("invalid entry"))
6079            })?
6080            .await?;
6081        Ok(proto::ProjectEntryResponse {
6082            entry: Some((&entry).into()),
6083            worktree_scan_id: worktree_scan_id as u64,
6084        })
6085    }
6086
6087    async fn handle_copy_project_entry(
6088        this: ModelHandle<Self>,
6089        envelope: TypedEnvelope<proto::CopyProjectEntry>,
6090        _: Arc<Client>,
6091        mut cx: AsyncAppContext,
6092    ) -> Result<proto::ProjectEntryResponse> {
6093        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6094        let worktree = this.read_with(&cx, |this, cx| {
6095            this.worktree_for_entry(entry_id, cx)
6096                .ok_or_else(|| anyhow!("worktree not found"))
6097        })?;
6098        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6099        let entry = worktree
6100            .update(&mut cx, |worktree, cx| {
6101                let new_path = PathBuf::from(envelope.payload.new_path);
6102                worktree
6103                    .as_local_mut()
6104                    .unwrap()
6105                    .copy_entry(entry_id, new_path, cx)
6106                    .ok_or_else(|| anyhow!("invalid entry"))
6107            })?
6108            .await?;
6109        Ok(proto::ProjectEntryResponse {
6110            entry: Some((&entry).into()),
6111            worktree_scan_id: worktree_scan_id as u64,
6112        })
6113    }
6114
6115    async fn handle_delete_project_entry(
6116        this: ModelHandle<Self>,
6117        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6118        _: Arc<Client>,
6119        mut cx: AsyncAppContext,
6120    ) -> Result<proto::ProjectEntryResponse> {
6121        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6122
6123        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
6124
6125        let worktree = this.read_with(&cx, |this, cx| {
6126            this.worktree_for_entry(entry_id, cx)
6127                .ok_or_else(|| anyhow!("worktree not found"))
6128        })?;
6129        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6130        worktree
6131            .update(&mut cx, |worktree, cx| {
6132                worktree
6133                    .as_local_mut()
6134                    .unwrap()
6135                    .delete_entry(entry_id, cx)
6136                    .ok_or_else(|| anyhow!("invalid entry"))
6137            })?
6138            .await?;
6139        Ok(proto::ProjectEntryResponse {
6140            entry: None,
6141            worktree_scan_id: worktree_scan_id as u64,
6142        })
6143    }
6144
6145    async fn handle_expand_project_entry(
6146        this: ModelHandle<Self>,
6147        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
6148        _: Arc<Client>,
6149        mut cx: AsyncAppContext,
6150    ) -> Result<proto::ExpandProjectEntryResponse> {
6151        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6152        let worktree = this
6153            .read_with(&cx, |this, cx| this.worktree_for_entry(entry_id, cx))
6154            .ok_or_else(|| anyhow!("invalid request"))?;
6155        worktree
6156            .update(&mut cx, |worktree, cx| {
6157                worktree
6158                    .as_local_mut()
6159                    .unwrap()
6160                    .expand_entry(entry_id, cx)
6161                    .ok_or_else(|| anyhow!("invalid entry"))
6162            })?
6163            .await?;
6164        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id()) as u64;
6165        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
6166    }
6167
6168    async fn handle_update_diagnostic_summary(
6169        this: ModelHandle<Self>,
6170        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
6171        _: Arc<Client>,
6172        mut cx: AsyncAppContext,
6173    ) -> Result<()> {
6174        this.update(&mut cx, |this, cx| {
6175            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6176            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6177                if let Some(summary) = envelope.payload.summary {
6178                    let project_path = ProjectPath {
6179                        worktree_id,
6180                        path: Path::new(&summary.path).into(),
6181                    };
6182                    worktree.update(cx, |worktree, _| {
6183                        worktree
6184                            .as_remote_mut()
6185                            .unwrap()
6186                            .update_diagnostic_summary(project_path.path.clone(), &summary);
6187                    });
6188                    cx.emit(Event::DiagnosticsUpdated {
6189                        language_server_id: LanguageServerId(summary.language_server_id as usize),
6190                        path: project_path,
6191                    });
6192                }
6193            }
6194            Ok(())
6195        })
6196    }
6197
6198    async fn handle_start_language_server(
6199        this: ModelHandle<Self>,
6200        envelope: TypedEnvelope<proto::StartLanguageServer>,
6201        _: Arc<Client>,
6202        mut cx: AsyncAppContext,
6203    ) -> Result<()> {
6204        let server = envelope
6205            .payload
6206            .server
6207            .ok_or_else(|| anyhow!("invalid server"))?;
6208        this.update(&mut cx, |this, cx| {
6209            this.language_server_statuses.insert(
6210                LanguageServerId(server.id as usize),
6211                LanguageServerStatus {
6212                    name: server.name,
6213                    pending_work: Default::default(),
6214                    has_pending_diagnostic_updates: false,
6215                    progress_tokens: Default::default(),
6216                },
6217            );
6218            cx.notify();
6219        });
6220        Ok(())
6221    }
6222
6223    async fn handle_update_language_server(
6224        this: ModelHandle<Self>,
6225        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
6226        _: Arc<Client>,
6227        mut cx: AsyncAppContext,
6228    ) -> Result<()> {
6229        this.update(&mut cx, |this, cx| {
6230            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
6231
6232            match envelope
6233                .payload
6234                .variant
6235                .ok_or_else(|| anyhow!("invalid variant"))?
6236            {
6237                proto::update_language_server::Variant::WorkStart(payload) => {
6238                    this.on_lsp_work_start(
6239                        language_server_id,
6240                        payload.token,
6241                        LanguageServerProgress {
6242                            message: payload.message,
6243                            percentage: payload.percentage.map(|p| p as usize),
6244                            last_update_at: Instant::now(),
6245                        },
6246                        cx,
6247                    );
6248                }
6249
6250                proto::update_language_server::Variant::WorkProgress(payload) => {
6251                    this.on_lsp_work_progress(
6252                        language_server_id,
6253                        payload.token,
6254                        LanguageServerProgress {
6255                            message: payload.message,
6256                            percentage: payload.percentage.map(|p| p as usize),
6257                            last_update_at: Instant::now(),
6258                        },
6259                        cx,
6260                    );
6261                }
6262
6263                proto::update_language_server::Variant::WorkEnd(payload) => {
6264                    this.on_lsp_work_end(language_server_id, payload.token, cx);
6265                }
6266
6267                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
6268                    this.disk_based_diagnostics_started(language_server_id, cx);
6269                }
6270
6271                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
6272                    this.disk_based_diagnostics_finished(language_server_id, cx)
6273                }
6274            }
6275
6276            Ok(())
6277        })
6278    }
6279
6280    async fn handle_update_buffer(
6281        this: ModelHandle<Self>,
6282        envelope: TypedEnvelope<proto::UpdateBuffer>,
6283        _: Arc<Client>,
6284        mut cx: AsyncAppContext,
6285    ) -> Result<proto::Ack> {
6286        this.update(&mut cx, |this, cx| {
6287            let payload = envelope.payload.clone();
6288            let buffer_id = payload.buffer_id;
6289            let ops = payload
6290                .operations
6291                .into_iter()
6292                .map(language::proto::deserialize_operation)
6293                .collect::<Result<Vec<_>, _>>()?;
6294            let is_remote = this.is_remote();
6295            match this.opened_buffers.entry(buffer_id) {
6296                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
6297                    OpenBuffer::Strong(buffer) => {
6298                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
6299                    }
6300                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
6301                    OpenBuffer::Weak(_) => {}
6302                },
6303                hash_map::Entry::Vacant(e) => {
6304                    assert!(
6305                        is_remote,
6306                        "received buffer update from {:?}",
6307                        envelope.original_sender_id
6308                    );
6309                    e.insert(OpenBuffer::Operations(ops));
6310                }
6311            }
6312            Ok(proto::Ack {})
6313        })
6314    }
6315
6316    async fn handle_create_buffer_for_peer(
6317        this: ModelHandle<Self>,
6318        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
6319        _: Arc<Client>,
6320        mut cx: AsyncAppContext,
6321    ) -> Result<()> {
6322        this.update(&mut cx, |this, cx| {
6323            match envelope
6324                .payload
6325                .variant
6326                .ok_or_else(|| anyhow!("missing variant"))?
6327            {
6328                proto::create_buffer_for_peer::Variant::State(mut state) => {
6329                    let mut buffer_file = None;
6330                    if let Some(file) = state.file.take() {
6331                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
6332                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
6333                            anyhow!("no worktree found for id {}", file.worktree_id)
6334                        })?;
6335                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
6336                            as Arc<dyn language::File>);
6337                    }
6338
6339                    let buffer_id = state.id;
6340                    let buffer = cx.add_model(|_| {
6341                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
6342                    });
6343                    this.incomplete_remote_buffers
6344                        .insert(buffer_id, Some(buffer));
6345                }
6346                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
6347                    let buffer = this
6348                        .incomplete_remote_buffers
6349                        .get(&chunk.buffer_id)
6350                        .cloned()
6351                        .flatten()
6352                        .ok_or_else(|| {
6353                            anyhow!(
6354                                "received chunk for buffer {} without initial state",
6355                                chunk.buffer_id
6356                            )
6357                        })?;
6358                    let operations = chunk
6359                        .operations
6360                        .into_iter()
6361                        .map(language::proto::deserialize_operation)
6362                        .collect::<Result<Vec<_>>>()?;
6363                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
6364
6365                    if chunk.is_last {
6366                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
6367                        this.register_buffer(&buffer, cx)?;
6368                    }
6369                }
6370            }
6371
6372            Ok(())
6373        })
6374    }
6375
6376    async fn handle_update_diff_base(
6377        this: ModelHandle<Self>,
6378        envelope: TypedEnvelope<proto::UpdateDiffBase>,
6379        _: Arc<Client>,
6380        mut cx: AsyncAppContext,
6381    ) -> Result<()> {
6382        this.update(&mut cx, |this, cx| {
6383            let buffer_id = envelope.payload.buffer_id;
6384            let diff_base = envelope.payload.diff_base;
6385            if let Some(buffer) = this
6386                .opened_buffers
6387                .get_mut(&buffer_id)
6388                .and_then(|b| b.upgrade(cx))
6389                .or_else(|| {
6390                    this.incomplete_remote_buffers
6391                        .get(&buffer_id)
6392                        .cloned()
6393                        .flatten()
6394                })
6395            {
6396                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
6397            }
6398            Ok(())
6399        })
6400    }
6401
6402    async fn handle_update_buffer_file(
6403        this: ModelHandle<Self>,
6404        envelope: TypedEnvelope<proto::UpdateBufferFile>,
6405        _: Arc<Client>,
6406        mut cx: AsyncAppContext,
6407    ) -> Result<()> {
6408        let buffer_id = envelope.payload.buffer_id;
6409
6410        this.update(&mut cx, |this, cx| {
6411            let payload = envelope.payload.clone();
6412            if let Some(buffer) = this
6413                .opened_buffers
6414                .get(&buffer_id)
6415                .and_then(|b| b.upgrade(cx))
6416                .or_else(|| {
6417                    this.incomplete_remote_buffers
6418                        .get(&buffer_id)
6419                        .cloned()
6420                        .flatten()
6421                })
6422            {
6423                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
6424                let worktree = this
6425                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
6426                    .ok_or_else(|| anyhow!("no such worktree"))?;
6427                let file = File::from_proto(file, worktree, cx)?;
6428                buffer.update(cx, |buffer, cx| {
6429                    buffer.file_updated(Arc::new(file), cx).detach();
6430                });
6431                this.detect_language_for_buffer(&buffer, cx);
6432            }
6433            Ok(())
6434        })
6435    }
6436
6437    async fn handle_save_buffer(
6438        this: ModelHandle<Self>,
6439        envelope: TypedEnvelope<proto::SaveBuffer>,
6440        _: Arc<Client>,
6441        mut cx: AsyncAppContext,
6442    ) -> Result<proto::BufferSaved> {
6443        let buffer_id = envelope.payload.buffer_id;
6444        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
6445            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
6446            let buffer = this
6447                .opened_buffers
6448                .get(&buffer_id)
6449                .and_then(|buffer| buffer.upgrade(cx))
6450                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
6451            anyhow::Ok((project_id, buffer))
6452        })?;
6453        buffer
6454            .update(&mut cx, |buffer, _| {
6455                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
6456            })
6457            .await?;
6458        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
6459
6460        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
6461            .await?;
6462        Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
6463            project_id,
6464            buffer_id,
6465            version: serialize_version(buffer.saved_version()),
6466            mtime: Some(buffer.saved_mtime().into()),
6467            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
6468        }))
6469    }
6470
6471    async fn handle_reload_buffers(
6472        this: ModelHandle<Self>,
6473        envelope: TypedEnvelope<proto::ReloadBuffers>,
6474        _: Arc<Client>,
6475        mut cx: AsyncAppContext,
6476    ) -> Result<proto::ReloadBuffersResponse> {
6477        let sender_id = envelope.original_sender_id()?;
6478        let reload = this.update(&mut cx, |this, cx| {
6479            let mut buffers = HashSet::default();
6480            for buffer_id in &envelope.payload.buffer_ids {
6481                buffers.insert(
6482                    this.opened_buffers
6483                        .get(buffer_id)
6484                        .and_then(|buffer| buffer.upgrade(cx))
6485                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6486                );
6487            }
6488            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
6489        })?;
6490
6491        let project_transaction = reload.await?;
6492        let project_transaction = this.update(&mut cx, |this, cx| {
6493            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6494        });
6495        Ok(proto::ReloadBuffersResponse {
6496            transaction: Some(project_transaction),
6497        })
6498    }
6499
6500    async fn handle_synchronize_buffers(
6501        this: ModelHandle<Self>,
6502        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
6503        _: Arc<Client>,
6504        mut cx: AsyncAppContext,
6505    ) -> Result<proto::SynchronizeBuffersResponse> {
6506        let project_id = envelope.payload.project_id;
6507        let mut response = proto::SynchronizeBuffersResponse {
6508            buffers: Default::default(),
6509        };
6510
6511        this.update(&mut cx, |this, cx| {
6512            let Some(guest_id) = envelope.original_sender_id else {
6513                error!("missing original_sender_id on SynchronizeBuffers request");
6514                return;
6515            };
6516
6517            this.shared_buffers.entry(guest_id).or_default().clear();
6518            for buffer in envelope.payload.buffers {
6519                let buffer_id = buffer.id;
6520                let remote_version = language::proto::deserialize_version(&buffer.version);
6521                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6522                    this.shared_buffers
6523                        .entry(guest_id)
6524                        .or_default()
6525                        .insert(buffer_id);
6526
6527                    let buffer = buffer.read(cx);
6528                    response.buffers.push(proto::BufferVersion {
6529                        id: buffer_id,
6530                        version: language::proto::serialize_version(&buffer.version),
6531                    });
6532
6533                    let operations = buffer.serialize_ops(Some(remote_version), cx);
6534                    let client = this.client.clone();
6535                    if let Some(file) = buffer.file() {
6536                        client
6537                            .send(proto::UpdateBufferFile {
6538                                project_id,
6539                                buffer_id: buffer_id as u64,
6540                                file: Some(file.to_proto()),
6541                            })
6542                            .log_err();
6543                    }
6544
6545                    client
6546                        .send(proto::UpdateDiffBase {
6547                            project_id,
6548                            buffer_id: buffer_id as u64,
6549                            diff_base: buffer.diff_base().map(Into::into),
6550                        })
6551                        .log_err();
6552
6553                    client
6554                        .send(proto::BufferReloaded {
6555                            project_id,
6556                            buffer_id,
6557                            version: language::proto::serialize_version(buffer.saved_version()),
6558                            mtime: Some(buffer.saved_mtime().into()),
6559                            fingerprint: language::proto::serialize_fingerprint(
6560                                buffer.saved_version_fingerprint(),
6561                            ),
6562                            line_ending: language::proto::serialize_line_ending(
6563                                buffer.line_ending(),
6564                            ) as i32,
6565                        })
6566                        .log_err();
6567
6568                    cx.background()
6569                        .spawn(
6570                            async move {
6571                                let operations = operations.await;
6572                                for chunk in split_operations(operations) {
6573                                    client
6574                                        .request(proto::UpdateBuffer {
6575                                            project_id,
6576                                            buffer_id,
6577                                            operations: chunk,
6578                                        })
6579                                        .await?;
6580                                }
6581                                anyhow::Ok(())
6582                            }
6583                            .log_err(),
6584                        )
6585                        .detach();
6586                }
6587            }
6588        });
6589
6590        Ok(response)
6591    }
6592
6593    async fn handle_format_buffers(
6594        this: ModelHandle<Self>,
6595        envelope: TypedEnvelope<proto::FormatBuffers>,
6596        _: Arc<Client>,
6597        mut cx: AsyncAppContext,
6598    ) -> Result<proto::FormatBuffersResponse> {
6599        let sender_id = envelope.original_sender_id()?;
6600        let format = this.update(&mut cx, |this, cx| {
6601            let mut buffers = HashSet::default();
6602            for buffer_id in &envelope.payload.buffer_ids {
6603                buffers.insert(
6604                    this.opened_buffers
6605                        .get(buffer_id)
6606                        .and_then(|buffer| buffer.upgrade(cx))
6607                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6608                );
6609            }
6610            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
6611            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
6612        })?;
6613
6614        let project_transaction = format.await?;
6615        let project_transaction = this.update(&mut cx, |this, cx| {
6616            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6617        });
6618        Ok(proto::FormatBuffersResponse {
6619            transaction: Some(project_transaction),
6620        })
6621    }
6622
6623    async fn handle_apply_additional_edits_for_completion(
6624        this: ModelHandle<Self>,
6625        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
6626        _: Arc<Client>,
6627        mut cx: AsyncAppContext,
6628    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
6629        let (buffer, completion) = this.update(&mut cx, |this, cx| {
6630            let buffer = this
6631                .opened_buffers
6632                .get(&envelope.payload.buffer_id)
6633                .and_then(|buffer| buffer.upgrade(cx))
6634                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6635            let language = buffer.read(cx).language();
6636            let completion = language::proto::deserialize_completion(
6637                envelope
6638                    .payload
6639                    .completion
6640                    .ok_or_else(|| anyhow!("invalid completion"))?,
6641                language.cloned(),
6642            );
6643            Ok::<_, anyhow::Error>((buffer, completion))
6644        })?;
6645
6646        let completion = completion.await?;
6647
6648        let apply_additional_edits = this.update(&mut cx, |this, cx| {
6649            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
6650        });
6651
6652        Ok(proto::ApplyCompletionAdditionalEditsResponse {
6653            transaction: apply_additional_edits
6654                .await?
6655                .as_ref()
6656                .map(language::proto::serialize_transaction),
6657        })
6658    }
6659
6660    async fn handle_apply_code_action(
6661        this: ModelHandle<Self>,
6662        envelope: TypedEnvelope<proto::ApplyCodeAction>,
6663        _: Arc<Client>,
6664        mut cx: AsyncAppContext,
6665    ) -> Result<proto::ApplyCodeActionResponse> {
6666        let sender_id = envelope.original_sender_id()?;
6667        let action = language::proto::deserialize_code_action(
6668            envelope
6669                .payload
6670                .action
6671                .ok_or_else(|| anyhow!("invalid action"))?,
6672        )?;
6673        let apply_code_action = this.update(&mut cx, |this, cx| {
6674            let buffer = this
6675                .opened_buffers
6676                .get(&envelope.payload.buffer_id)
6677                .and_then(|buffer| buffer.upgrade(cx))
6678                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6679            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
6680        })?;
6681
6682        let project_transaction = apply_code_action.await?;
6683        let project_transaction = this.update(&mut cx, |this, cx| {
6684            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6685        });
6686        Ok(proto::ApplyCodeActionResponse {
6687            transaction: Some(project_transaction),
6688        })
6689    }
6690
6691    async fn handle_on_type_formatting(
6692        this: ModelHandle<Self>,
6693        envelope: TypedEnvelope<proto::OnTypeFormatting>,
6694        _: Arc<Client>,
6695        mut cx: AsyncAppContext,
6696    ) -> Result<proto::OnTypeFormattingResponse> {
6697        let on_type_formatting = this.update(&mut cx, |this, cx| {
6698            let buffer = this
6699                .opened_buffers
6700                .get(&envelope.payload.buffer_id)
6701                .and_then(|buffer| buffer.upgrade(cx))
6702                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6703            let position = envelope
6704                .payload
6705                .position
6706                .and_then(deserialize_anchor)
6707                .ok_or_else(|| anyhow!("invalid position"))?;
6708            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
6709                buffer,
6710                position,
6711                envelope.payload.trigger.clone(),
6712                cx,
6713            ))
6714        })?;
6715
6716        let transaction = on_type_formatting
6717            .await?
6718            .as_ref()
6719            .map(language::proto::serialize_transaction);
6720        Ok(proto::OnTypeFormattingResponse { transaction })
6721    }
6722
6723    async fn handle_inlay_hints(
6724        this: ModelHandle<Self>,
6725        envelope: TypedEnvelope<proto::InlayHints>,
6726        _: Arc<Client>,
6727        mut cx: AsyncAppContext,
6728    ) -> Result<proto::InlayHintsResponse> {
6729        let sender_id = envelope.original_sender_id()?;
6730        let buffer = this.update(&mut cx, |this, cx| {
6731            this.opened_buffers
6732                .get(&envelope.payload.buffer_id)
6733                .and_then(|buffer| buffer.upgrade(cx))
6734                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
6735        })?;
6736        let buffer_version = deserialize_version(&envelope.payload.version);
6737
6738        buffer
6739            .update(&mut cx, |buffer, _| {
6740                buffer.wait_for_version(buffer_version.clone())
6741            })
6742            .await
6743            .with_context(|| {
6744                format!(
6745                    "waiting for version {:?} for buffer {}",
6746                    buffer_version,
6747                    buffer.id()
6748                )
6749            })?;
6750
6751        let start = envelope
6752            .payload
6753            .start
6754            .and_then(deserialize_anchor)
6755            .context("missing range start")?;
6756        let end = envelope
6757            .payload
6758            .end
6759            .and_then(deserialize_anchor)
6760            .context("missing range end")?;
6761        let buffer_hints = this
6762            .update(&mut cx, |project, cx| {
6763                project.inlay_hints(buffer, start..end, cx)
6764            })
6765            .await
6766            .context("inlay hints fetch")?;
6767
6768        Ok(this.update(&mut cx, |project, cx| {
6769            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
6770        }))
6771    }
6772
6773    async fn handle_refresh_inlay_hints(
6774        this: ModelHandle<Self>,
6775        _: TypedEnvelope<proto::RefreshInlayHints>,
6776        _: Arc<Client>,
6777        mut cx: AsyncAppContext,
6778    ) -> Result<proto::Ack> {
6779        this.update(&mut cx, |_, cx| {
6780            cx.emit(Event::RefreshInlays);
6781        });
6782        Ok(proto::Ack {})
6783    }
6784
6785    async fn handle_lsp_command<T: LspCommand>(
6786        this: ModelHandle<Self>,
6787        envelope: TypedEnvelope<T::ProtoRequest>,
6788        _: Arc<Client>,
6789        mut cx: AsyncAppContext,
6790    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
6791    where
6792        <T::LspRequest as lsp::request::Request>::Result: Send,
6793    {
6794        let sender_id = envelope.original_sender_id()?;
6795        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
6796        let buffer_handle = this.read_with(&cx, |this, _| {
6797            this.opened_buffers
6798                .get(&buffer_id)
6799                .and_then(|buffer| buffer.upgrade(&cx))
6800                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
6801        })?;
6802        let request = T::from_proto(
6803            envelope.payload,
6804            this.clone(),
6805            buffer_handle.clone(),
6806            cx.clone(),
6807        )
6808        .await?;
6809        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
6810        let response = this
6811            .update(&mut cx, |this, cx| {
6812                this.request_lsp(buffer_handle, request, cx)
6813            })
6814            .await?;
6815        this.update(&mut cx, |this, cx| {
6816            Ok(T::response_to_proto(
6817                response,
6818                this,
6819                sender_id,
6820                &buffer_version,
6821                cx,
6822            ))
6823        })
6824    }
6825
6826    async fn handle_get_project_symbols(
6827        this: ModelHandle<Self>,
6828        envelope: TypedEnvelope<proto::GetProjectSymbols>,
6829        _: Arc<Client>,
6830        mut cx: AsyncAppContext,
6831    ) -> Result<proto::GetProjectSymbolsResponse> {
6832        let symbols = this
6833            .update(&mut cx, |this, cx| {
6834                this.symbols(&envelope.payload.query, cx)
6835            })
6836            .await?;
6837
6838        Ok(proto::GetProjectSymbolsResponse {
6839            symbols: symbols.iter().map(serialize_symbol).collect(),
6840        })
6841    }
6842
6843    async fn handle_search_project(
6844        this: ModelHandle<Self>,
6845        envelope: TypedEnvelope<proto::SearchProject>,
6846        _: Arc<Client>,
6847        mut cx: AsyncAppContext,
6848    ) -> Result<proto::SearchProjectResponse> {
6849        let peer_id = envelope.original_sender_id()?;
6850        let query = SearchQuery::from_proto(envelope.payload)?;
6851        let result = this
6852            .update(&mut cx, |this, cx| this.search(query, cx))
6853            .await?;
6854
6855        this.update(&mut cx, |this, cx| {
6856            let mut locations = Vec::new();
6857            for (buffer, ranges) in result {
6858                for range in ranges {
6859                    let start = serialize_anchor(&range.start);
6860                    let end = serialize_anchor(&range.end);
6861                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
6862                    locations.push(proto::Location {
6863                        buffer_id,
6864                        start: Some(start),
6865                        end: Some(end),
6866                    });
6867                }
6868            }
6869            Ok(proto::SearchProjectResponse { locations })
6870        })
6871    }
6872
6873    async fn handle_open_buffer_for_symbol(
6874        this: ModelHandle<Self>,
6875        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
6876        _: Arc<Client>,
6877        mut cx: AsyncAppContext,
6878    ) -> Result<proto::OpenBufferForSymbolResponse> {
6879        let peer_id = envelope.original_sender_id()?;
6880        let symbol = envelope
6881            .payload
6882            .symbol
6883            .ok_or_else(|| anyhow!("invalid symbol"))?;
6884        let symbol = this
6885            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
6886            .await?;
6887        let symbol = this.read_with(&cx, |this, _| {
6888            let signature = this.symbol_signature(&symbol.path);
6889            if signature == symbol.signature {
6890                Ok(symbol)
6891            } else {
6892                Err(anyhow!("invalid symbol signature"))
6893            }
6894        })?;
6895        let buffer = this
6896            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
6897            .await?;
6898
6899        Ok(proto::OpenBufferForSymbolResponse {
6900            buffer_id: this.update(&mut cx, |this, cx| {
6901                this.create_buffer_for_peer(&buffer, peer_id, cx)
6902            }),
6903        })
6904    }
6905
6906    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
6907        let mut hasher = Sha256::new();
6908        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
6909        hasher.update(project_path.path.to_string_lossy().as_bytes());
6910        hasher.update(self.nonce.to_be_bytes());
6911        hasher.finalize().as_slice().try_into().unwrap()
6912    }
6913
6914    async fn handle_open_buffer_by_id(
6915        this: ModelHandle<Self>,
6916        envelope: TypedEnvelope<proto::OpenBufferById>,
6917        _: Arc<Client>,
6918        mut cx: AsyncAppContext,
6919    ) -> Result<proto::OpenBufferResponse> {
6920        let peer_id = envelope.original_sender_id()?;
6921        let buffer = this
6922            .update(&mut cx, |this, cx| {
6923                this.open_buffer_by_id(envelope.payload.id, cx)
6924            })
6925            .await?;
6926        this.update(&mut cx, |this, cx| {
6927            Ok(proto::OpenBufferResponse {
6928                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6929            })
6930        })
6931    }
6932
6933    async fn handle_open_buffer_by_path(
6934        this: ModelHandle<Self>,
6935        envelope: TypedEnvelope<proto::OpenBufferByPath>,
6936        _: Arc<Client>,
6937        mut cx: AsyncAppContext,
6938    ) -> Result<proto::OpenBufferResponse> {
6939        let peer_id = envelope.original_sender_id()?;
6940        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6941        let open_buffer = this.update(&mut cx, |this, cx| {
6942            this.open_buffer(
6943                ProjectPath {
6944                    worktree_id,
6945                    path: PathBuf::from(envelope.payload.path).into(),
6946                },
6947                cx,
6948            )
6949        });
6950
6951        let buffer = open_buffer.await?;
6952        this.update(&mut cx, |this, cx| {
6953            Ok(proto::OpenBufferResponse {
6954                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
6955            })
6956        })
6957    }
6958
6959    fn serialize_project_transaction_for_peer(
6960        &mut self,
6961        project_transaction: ProjectTransaction,
6962        peer_id: proto::PeerId,
6963        cx: &mut AppContext,
6964    ) -> proto::ProjectTransaction {
6965        let mut serialized_transaction = proto::ProjectTransaction {
6966            buffer_ids: Default::default(),
6967            transactions: Default::default(),
6968        };
6969        for (buffer, transaction) in project_transaction.0 {
6970            serialized_transaction
6971                .buffer_ids
6972                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
6973            serialized_transaction
6974                .transactions
6975                .push(language::proto::serialize_transaction(&transaction));
6976        }
6977        serialized_transaction
6978    }
6979
6980    fn deserialize_project_transaction(
6981        &mut self,
6982        message: proto::ProjectTransaction,
6983        push_to_history: bool,
6984        cx: &mut ModelContext<Self>,
6985    ) -> Task<Result<ProjectTransaction>> {
6986        cx.spawn(|this, mut cx| async move {
6987            let mut project_transaction = ProjectTransaction::default();
6988            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
6989            {
6990                let buffer = this
6991                    .update(&mut cx, |this, cx| {
6992                        this.wait_for_remote_buffer(buffer_id, cx)
6993                    })
6994                    .await?;
6995                let transaction = language::proto::deserialize_transaction(transaction)?;
6996                project_transaction.0.insert(buffer, transaction);
6997            }
6998
6999            for (buffer, transaction) in &project_transaction.0 {
7000                buffer
7001                    .update(&mut cx, |buffer, _| {
7002                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7003                    })
7004                    .await?;
7005
7006                if push_to_history {
7007                    buffer.update(&mut cx, |buffer, _| {
7008                        buffer.push_transaction(transaction.clone(), Instant::now());
7009                    });
7010                }
7011            }
7012
7013            Ok(project_transaction)
7014        })
7015    }
7016
7017    fn create_buffer_for_peer(
7018        &mut self,
7019        buffer: &ModelHandle<Buffer>,
7020        peer_id: proto::PeerId,
7021        cx: &mut AppContext,
7022    ) -> u64 {
7023        let buffer_id = buffer.read(cx).remote_id();
7024        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7025            updates_tx
7026                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7027                .ok();
7028        }
7029        buffer_id
7030    }
7031
7032    fn wait_for_remote_buffer(
7033        &mut self,
7034        id: u64,
7035        cx: &mut ModelContext<Self>,
7036    ) -> Task<Result<ModelHandle<Buffer>>> {
7037        let mut opened_buffer_rx = self.opened_buffer.1.clone();
7038
7039        cx.spawn_weak(|this, mut cx| async move {
7040            let buffer = loop {
7041                let Some(this) = this.upgrade(&cx) else {
7042                    return Err(anyhow!("project dropped"));
7043                };
7044
7045                let buffer = this.read_with(&cx, |this, cx| {
7046                    this.opened_buffers
7047                        .get(&id)
7048                        .and_then(|buffer| buffer.upgrade(cx))
7049                });
7050
7051                if let Some(buffer) = buffer {
7052                    break buffer;
7053                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
7054                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
7055                }
7056
7057                this.update(&mut cx, |this, _| {
7058                    this.incomplete_remote_buffers.entry(id).or_default();
7059                });
7060                drop(this);
7061
7062                opened_buffer_rx
7063                    .next()
7064                    .await
7065                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7066            };
7067
7068            Ok(buffer)
7069        })
7070    }
7071
7072    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7073        let project_id = match self.client_state.as_ref() {
7074            Some(ProjectClientState::Remote {
7075                sharing_has_stopped,
7076                remote_id,
7077                ..
7078            }) => {
7079                if *sharing_has_stopped {
7080                    return Task::ready(Err(anyhow!(
7081                        "can't synchronize remote buffers on a readonly project"
7082                    )));
7083                } else {
7084                    *remote_id
7085                }
7086            }
7087            Some(ProjectClientState::Local { .. }) | None => {
7088                return Task::ready(Err(anyhow!(
7089                    "can't synchronize remote buffers on a local project"
7090                )))
7091            }
7092        };
7093
7094        let client = self.client.clone();
7095        cx.spawn(|this, cx| async move {
7096            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
7097                let buffers = this
7098                    .opened_buffers
7099                    .iter()
7100                    .filter_map(|(id, buffer)| {
7101                        let buffer = buffer.upgrade(cx)?;
7102                        Some(proto::BufferVersion {
7103                            id: *id,
7104                            version: language::proto::serialize_version(&buffer.read(cx).version),
7105                        })
7106                    })
7107                    .collect();
7108                let incomplete_buffer_ids = this
7109                    .incomplete_remote_buffers
7110                    .keys()
7111                    .copied()
7112                    .collect::<Vec<_>>();
7113
7114                (buffers, incomplete_buffer_ids)
7115            });
7116            let response = client
7117                .request(proto::SynchronizeBuffers {
7118                    project_id,
7119                    buffers,
7120                })
7121                .await?;
7122
7123            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
7124                let client = client.clone();
7125                let buffer_id = buffer.id;
7126                let remote_version = language::proto::deserialize_version(&buffer.version);
7127                this.read_with(&cx, |this, cx| {
7128                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7129                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
7130                        cx.background().spawn(async move {
7131                            let operations = operations.await;
7132                            for chunk in split_operations(operations) {
7133                                client
7134                                    .request(proto::UpdateBuffer {
7135                                        project_id,
7136                                        buffer_id,
7137                                        operations: chunk,
7138                                    })
7139                                    .await?;
7140                            }
7141                            anyhow::Ok(())
7142                        })
7143                    } else {
7144                        Task::ready(Ok(()))
7145                    }
7146                })
7147            });
7148
7149            // Any incomplete buffers have open requests waiting. Request that the host sends
7150            // creates these buffers for us again to unblock any waiting futures.
7151            for id in incomplete_buffer_ids {
7152                cx.background()
7153                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
7154                    .detach();
7155            }
7156
7157            futures::future::join_all(send_updates_for_buffers)
7158                .await
7159                .into_iter()
7160                .collect()
7161        })
7162    }
7163
7164    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
7165        self.worktrees(cx)
7166            .map(|worktree| {
7167                let worktree = worktree.read(cx);
7168                proto::WorktreeMetadata {
7169                    id: worktree.id().to_proto(),
7170                    root_name: worktree.root_name().into(),
7171                    visible: worktree.is_visible(),
7172                    abs_path: worktree.abs_path().to_string_lossy().into(),
7173                }
7174            })
7175            .collect()
7176    }
7177
7178    fn set_worktrees_from_proto(
7179        &mut self,
7180        worktrees: Vec<proto::WorktreeMetadata>,
7181        cx: &mut ModelContext<Project>,
7182    ) -> Result<()> {
7183        let replica_id = self.replica_id();
7184        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
7185
7186        let mut old_worktrees_by_id = self
7187            .worktrees
7188            .drain(..)
7189            .filter_map(|worktree| {
7190                let worktree = worktree.upgrade(cx)?;
7191                Some((worktree.read(cx).id(), worktree))
7192            })
7193            .collect::<HashMap<_, _>>();
7194
7195        for worktree in worktrees {
7196            if let Some(old_worktree) =
7197                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
7198            {
7199                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
7200            } else {
7201                let worktree =
7202                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
7203                let _ = self.add_worktree(&worktree, cx);
7204            }
7205        }
7206
7207        self.metadata_changed(cx);
7208        for id in old_worktrees_by_id.keys() {
7209            cx.emit(Event::WorktreeRemoved(*id));
7210        }
7211
7212        Ok(())
7213    }
7214
7215    fn set_collaborators_from_proto(
7216        &mut self,
7217        messages: Vec<proto::Collaborator>,
7218        cx: &mut ModelContext<Self>,
7219    ) -> Result<()> {
7220        let mut collaborators = HashMap::default();
7221        for message in messages {
7222            let collaborator = Collaborator::from_proto(message)?;
7223            collaborators.insert(collaborator.peer_id, collaborator);
7224        }
7225        for old_peer_id in self.collaborators.keys() {
7226            if !collaborators.contains_key(old_peer_id) {
7227                cx.emit(Event::CollaboratorLeft(*old_peer_id));
7228            }
7229        }
7230        self.collaborators = collaborators;
7231        Ok(())
7232    }
7233
7234    fn deserialize_symbol(
7235        &self,
7236        serialized_symbol: proto::Symbol,
7237    ) -> impl Future<Output = Result<Symbol>> {
7238        let languages = self.languages.clone();
7239        async move {
7240            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
7241            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
7242            let start = serialized_symbol
7243                .start
7244                .ok_or_else(|| anyhow!("invalid start"))?;
7245            let end = serialized_symbol
7246                .end
7247                .ok_or_else(|| anyhow!("invalid end"))?;
7248            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
7249            let path = ProjectPath {
7250                worktree_id,
7251                path: PathBuf::from(serialized_symbol.path).into(),
7252            };
7253            let language = languages
7254                .language_for_file(&path.path, None)
7255                .await
7256                .log_err();
7257            Ok(Symbol {
7258                language_server_name: LanguageServerName(
7259                    serialized_symbol.language_server_name.into(),
7260                ),
7261                source_worktree_id,
7262                path,
7263                label: {
7264                    match language {
7265                        Some(language) => {
7266                            language
7267                                .label_for_symbol(&serialized_symbol.name, kind)
7268                                .await
7269                        }
7270                        None => None,
7271                    }
7272                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
7273                },
7274
7275                name: serialized_symbol.name,
7276                range: Unclipped(PointUtf16::new(start.row, start.column))
7277                    ..Unclipped(PointUtf16::new(end.row, end.column)),
7278                kind,
7279                signature: serialized_symbol
7280                    .signature
7281                    .try_into()
7282                    .map_err(|_| anyhow!("invalid signature"))?,
7283            })
7284        }
7285    }
7286
7287    async fn handle_buffer_saved(
7288        this: ModelHandle<Self>,
7289        envelope: TypedEnvelope<proto::BufferSaved>,
7290        _: Arc<Client>,
7291        mut cx: AsyncAppContext,
7292    ) -> Result<()> {
7293        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
7294        let version = deserialize_version(&envelope.payload.version);
7295        let mtime = envelope
7296            .payload
7297            .mtime
7298            .ok_or_else(|| anyhow!("missing mtime"))?
7299            .into();
7300
7301        this.update(&mut cx, |this, cx| {
7302            let buffer = this
7303                .opened_buffers
7304                .get(&envelope.payload.buffer_id)
7305                .and_then(|buffer| buffer.upgrade(cx))
7306                .or_else(|| {
7307                    this.incomplete_remote_buffers
7308                        .get(&envelope.payload.buffer_id)
7309                        .and_then(|b| b.clone())
7310                });
7311            if let Some(buffer) = buffer {
7312                buffer.update(cx, |buffer, cx| {
7313                    buffer.did_save(version, fingerprint, mtime, cx);
7314                });
7315            }
7316            Ok(())
7317        })
7318    }
7319
7320    async fn handle_buffer_reloaded(
7321        this: ModelHandle<Self>,
7322        envelope: TypedEnvelope<proto::BufferReloaded>,
7323        _: Arc<Client>,
7324        mut cx: AsyncAppContext,
7325    ) -> Result<()> {
7326        let payload = envelope.payload;
7327        let version = deserialize_version(&payload.version);
7328        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
7329        let line_ending = deserialize_line_ending(
7330            proto::LineEnding::from_i32(payload.line_ending)
7331                .ok_or_else(|| anyhow!("missing line ending"))?,
7332        );
7333        let mtime = payload
7334            .mtime
7335            .ok_or_else(|| anyhow!("missing mtime"))?
7336            .into();
7337        this.update(&mut cx, |this, cx| {
7338            let buffer = this
7339                .opened_buffers
7340                .get(&payload.buffer_id)
7341                .and_then(|buffer| buffer.upgrade(cx))
7342                .or_else(|| {
7343                    this.incomplete_remote_buffers
7344                        .get(&payload.buffer_id)
7345                        .cloned()
7346                        .flatten()
7347                });
7348            if let Some(buffer) = buffer {
7349                buffer.update(cx, |buffer, cx| {
7350                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
7351                });
7352            }
7353            Ok(())
7354        })
7355    }
7356
7357    #[allow(clippy::type_complexity)]
7358    fn edits_from_lsp(
7359        &mut self,
7360        buffer: &ModelHandle<Buffer>,
7361        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
7362        server_id: LanguageServerId,
7363        version: Option<i32>,
7364        cx: &mut ModelContext<Self>,
7365    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
7366        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
7367        cx.background().spawn(async move {
7368            let snapshot = snapshot?;
7369            let mut lsp_edits = lsp_edits
7370                .into_iter()
7371                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
7372                .collect::<Vec<_>>();
7373            lsp_edits.sort_by_key(|(range, _)| range.start);
7374
7375            let mut lsp_edits = lsp_edits.into_iter().peekable();
7376            let mut edits = Vec::new();
7377            while let Some((range, mut new_text)) = lsp_edits.next() {
7378                // Clip invalid ranges provided by the language server.
7379                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
7380                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
7381
7382                // Combine any LSP edits that are adjacent.
7383                //
7384                // Also, combine LSP edits that are separated from each other by only
7385                // a newline. This is important because for some code actions,
7386                // Rust-analyzer rewrites the entire buffer via a series of edits that
7387                // are separated by unchanged newline characters.
7388                //
7389                // In order for the diffing logic below to work properly, any edits that
7390                // cancel each other out must be combined into one.
7391                while let Some((next_range, next_text)) = lsp_edits.peek() {
7392                    if next_range.start.0 > range.end {
7393                        if next_range.start.0.row > range.end.row + 1
7394                            || next_range.start.0.column > 0
7395                            || snapshot.clip_point_utf16(
7396                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
7397                                Bias::Left,
7398                            ) > range.end
7399                        {
7400                            break;
7401                        }
7402                        new_text.push('\n');
7403                    }
7404                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
7405                    new_text.push_str(next_text);
7406                    lsp_edits.next();
7407                }
7408
7409                // For multiline edits, perform a diff of the old and new text so that
7410                // we can identify the changes more precisely, preserving the locations
7411                // of any anchors positioned in the unchanged regions.
7412                if range.end.row > range.start.row {
7413                    let mut offset = range.start.to_offset(&snapshot);
7414                    let old_text = snapshot.text_for_range(range).collect::<String>();
7415
7416                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
7417                    let mut moved_since_edit = true;
7418                    for change in diff.iter_all_changes() {
7419                        let tag = change.tag();
7420                        let value = change.value();
7421                        match tag {
7422                            ChangeTag::Equal => {
7423                                offset += value.len();
7424                                moved_since_edit = true;
7425                            }
7426                            ChangeTag::Delete => {
7427                                let start = snapshot.anchor_after(offset);
7428                                let end = snapshot.anchor_before(offset + value.len());
7429                                if moved_since_edit {
7430                                    edits.push((start..end, String::new()));
7431                                } else {
7432                                    edits.last_mut().unwrap().0.end = end;
7433                                }
7434                                offset += value.len();
7435                                moved_since_edit = false;
7436                            }
7437                            ChangeTag::Insert => {
7438                                if moved_since_edit {
7439                                    let anchor = snapshot.anchor_after(offset);
7440                                    edits.push((anchor..anchor, value.to_string()));
7441                                } else {
7442                                    edits.last_mut().unwrap().1.push_str(value);
7443                                }
7444                                moved_since_edit = false;
7445                            }
7446                        }
7447                    }
7448                } else if range.end == range.start {
7449                    let anchor = snapshot.anchor_after(range.start);
7450                    edits.push((anchor..anchor, new_text));
7451                } else {
7452                    let edit_start = snapshot.anchor_after(range.start);
7453                    let edit_end = snapshot.anchor_before(range.end);
7454                    edits.push((edit_start..edit_end, new_text));
7455                }
7456            }
7457
7458            Ok(edits)
7459        })
7460    }
7461
7462    fn buffer_snapshot_for_lsp_version(
7463        &mut self,
7464        buffer: &ModelHandle<Buffer>,
7465        server_id: LanguageServerId,
7466        version: Option<i32>,
7467        cx: &AppContext,
7468    ) -> Result<TextBufferSnapshot> {
7469        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
7470
7471        if let Some(version) = version {
7472            let buffer_id = buffer.read(cx).remote_id();
7473            let snapshots = self
7474                .buffer_snapshots
7475                .get_mut(&buffer_id)
7476                .and_then(|m| m.get_mut(&server_id))
7477                .ok_or_else(|| {
7478                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
7479                })?;
7480
7481            let found_snapshot = snapshots
7482                .binary_search_by_key(&version, |e| e.version)
7483                .map(|ix| snapshots[ix].snapshot.clone())
7484                .map_err(|_| {
7485                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
7486                })?;
7487
7488            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
7489            Ok(found_snapshot)
7490        } else {
7491            Ok((buffer.read(cx)).text_snapshot())
7492        }
7493    }
7494
7495    pub fn language_servers(
7496        &self,
7497    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
7498        self.language_server_ids
7499            .iter()
7500            .map(|((worktree_id, server_name), server_id)| {
7501                (*server_id, server_name.clone(), *worktree_id)
7502            })
7503    }
7504
7505    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7506        if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
7507            Some(server.clone())
7508        } else {
7509            None
7510        }
7511    }
7512
7513    pub fn language_servers_for_buffer(
7514        &self,
7515        buffer: &Buffer,
7516        cx: &AppContext,
7517    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7518        self.language_server_ids_for_buffer(buffer, cx)
7519            .into_iter()
7520            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
7521                LanguageServerState::Running {
7522                    adapter, server, ..
7523                } => Some((adapter, server)),
7524                _ => None,
7525            })
7526    }
7527
7528    fn primary_language_servers_for_buffer(
7529        &self,
7530        buffer: &Buffer,
7531        cx: &AppContext,
7532    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7533        self.language_servers_for_buffer(buffer, cx).next()
7534    }
7535
7536    fn language_server_for_buffer(
7537        &self,
7538        buffer: &Buffer,
7539        server_id: LanguageServerId,
7540        cx: &AppContext,
7541    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7542        self.language_servers_for_buffer(buffer, cx)
7543            .find(|(_, s)| s.server_id() == server_id)
7544    }
7545
7546    fn language_server_ids_for_buffer(
7547        &self,
7548        buffer: &Buffer,
7549        cx: &AppContext,
7550    ) -> Vec<LanguageServerId> {
7551        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
7552            let worktree_id = file.worktree_id(cx);
7553            language
7554                .lsp_adapters()
7555                .iter()
7556                .flat_map(|adapter| {
7557                    let key = (worktree_id, adapter.name.clone());
7558                    self.language_server_ids.get(&key).copied()
7559                })
7560                .collect()
7561        } else {
7562            Vec::new()
7563        }
7564    }
7565}
7566
7567fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
7568    let mut literal_end = 0;
7569    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
7570        if part.contains(&['*', '?', '{', '}']) {
7571            break;
7572        } else {
7573            if i > 0 {
7574                // Acount for separator prior to this part
7575                literal_end += path::MAIN_SEPARATOR.len_utf8();
7576            }
7577            literal_end += part.len();
7578        }
7579    }
7580    &glob[..literal_end]
7581}
7582
7583impl WorktreeHandle {
7584    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
7585        match self {
7586            WorktreeHandle::Strong(handle) => Some(handle.clone()),
7587            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
7588        }
7589    }
7590
7591    pub fn handle_id(&self) -> usize {
7592        match self {
7593            WorktreeHandle::Strong(handle) => handle.id(),
7594            WorktreeHandle::Weak(handle) => handle.id(),
7595        }
7596    }
7597}
7598
7599impl OpenBuffer {
7600    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
7601        match self {
7602            OpenBuffer::Strong(handle) => Some(handle.clone()),
7603            OpenBuffer::Weak(handle) => handle.upgrade(cx),
7604            OpenBuffer::Operations(_) => None,
7605        }
7606    }
7607}
7608
7609pub struct PathMatchCandidateSet {
7610    pub snapshot: Snapshot,
7611    pub include_ignored: bool,
7612    pub include_root_name: bool,
7613}
7614
7615impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
7616    type Candidates = PathMatchCandidateSetIter<'a>;
7617
7618    fn id(&self) -> usize {
7619        self.snapshot.id().to_usize()
7620    }
7621
7622    fn len(&self) -> usize {
7623        if self.include_ignored {
7624            self.snapshot.file_count()
7625        } else {
7626            self.snapshot.visible_file_count()
7627        }
7628    }
7629
7630    fn prefix(&self) -> Arc<str> {
7631        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
7632            self.snapshot.root_name().into()
7633        } else if self.include_root_name {
7634            format!("{}/", self.snapshot.root_name()).into()
7635        } else {
7636            "".into()
7637        }
7638    }
7639
7640    fn candidates(&'a self, start: usize) -> Self::Candidates {
7641        PathMatchCandidateSetIter {
7642            traversal: self.snapshot.files(self.include_ignored, start),
7643        }
7644    }
7645}
7646
7647pub struct PathMatchCandidateSetIter<'a> {
7648    traversal: Traversal<'a>,
7649}
7650
7651impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
7652    type Item = fuzzy::PathMatchCandidate<'a>;
7653
7654    fn next(&mut self) -> Option<Self::Item> {
7655        self.traversal.next().map(|entry| {
7656            if let EntryKind::File(char_bag) = entry.kind {
7657                fuzzy::PathMatchCandidate {
7658                    path: &entry.path,
7659                    char_bag,
7660                }
7661            } else {
7662                unreachable!()
7663            }
7664        })
7665    }
7666}
7667
7668impl Entity for Project {
7669    type Event = Event;
7670
7671    fn release(&mut self, cx: &mut gpui::AppContext) {
7672        match &self.client_state {
7673            Some(ProjectClientState::Local { .. }) => {
7674                let _ = self.unshare_internal(cx);
7675            }
7676            Some(ProjectClientState::Remote { remote_id, .. }) => {
7677                let _ = self.client.send(proto::LeaveProject {
7678                    project_id: *remote_id,
7679                });
7680                self.disconnected_from_host_internal(cx);
7681            }
7682            _ => {}
7683        }
7684    }
7685
7686    fn app_will_quit(
7687        &mut self,
7688        _: &mut AppContext,
7689    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
7690        let shutdown_futures = self
7691            .language_servers
7692            .drain()
7693            .map(|(_, server_state)| async {
7694                use LanguageServerState::*;
7695                match server_state {
7696                    Running { server, .. } => server.shutdown()?.await,
7697                    Starting(task) => task.await?.shutdown()?.await,
7698                }
7699            })
7700            .collect::<Vec<_>>();
7701
7702        Some(
7703            async move {
7704                futures::future::join_all(shutdown_futures).await;
7705            }
7706            .boxed(),
7707        )
7708    }
7709}
7710
7711impl Collaborator {
7712    fn from_proto(message: proto::Collaborator) -> Result<Self> {
7713        Ok(Self {
7714            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
7715            replica_id: message.replica_id as ReplicaId,
7716        })
7717    }
7718}
7719
7720impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
7721    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
7722        Self {
7723            worktree_id,
7724            path: path.as_ref().into(),
7725        }
7726    }
7727}
7728
7729impl ProjectLspAdapterDelegate {
7730    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
7731        Arc::new(Self {
7732            project: cx.handle(),
7733            http_client: project.client.http_client(),
7734        })
7735    }
7736}
7737
7738impl LspAdapterDelegate for ProjectLspAdapterDelegate {
7739    fn show_notification(&self, message: &str, cx: &mut AppContext) {
7740        self.project
7741            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
7742    }
7743
7744    fn http_client(&self) -> Arc<dyn HttpClient> {
7745        self.http_client.clone()
7746    }
7747}
7748
7749fn split_operations(
7750    mut operations: Vec<proto::Operation>,
7751) -> impl Iterator<Item = Vec<proto::Operation>> {
7752    #[cfg(any(test, feature = "test-support"))]
7753    const CHUNK_SIZE: usize = 5;
7754
7755    #[cfg(not(any(test, feature = "test-support")))]
7756    const CHUNK_SIZE: usize = 100;
7757
7758    let mut done = false;
7759    std::iter::from_fn(move || {
7760        if done {
7761            return None;
7762        }
7763
7764        let operations = operations
7765            .drain(..cmp::min(CHUNK_SIZE, operations.len()))
7766            .collect::<Vec<_>>();
7767        if operations.is_empty() {
7768            done = true;
7769        }
7770        Some(operations)
7771    })
7772}
7773
7774fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
7775    proto::Symbol {
7776        language_server_name: symbol.language_server_name.0.to_string(),
7777        source_worktree_id: symbol.source_worktree_id.to_proto(),
7778        worktree_id: symbol.path.worktree_id.to_proto(),
7779        path: symbol.path.path.to_string_lossy().to_string(),
7780        name: symbol.name.clone(),
7781        kind: unsafe { mem::transmute(symbol.kind) },
7782        start: Some(proto::PointUtf16 {
7783            row: symbol.range.start.0.row,
7784            column: symbol.range.start.0.column,
7785        }),
7786        end: Some(proto::PointUtf16 {
7787            row: symbol.range.end.0.row,
7788            column: symbol.range.end.0.column,
7789        }),
7790        signature: symbol.signature.to_vec(),
7791    }
7792}
7793
7794fn relativize_path(base: &Path, path: &Path) -> PathBuf {
7795    let mut path_components = path.components();
7796    let mut base_components = base.components();
7797    let mut components: Vec<Component> = Vec::new();
7798    loop {
7799        match (path_components.next(), base_components.next()) {
7800            (None, None) => break,
7801            (Some(a), None) => {
7802                components.push(a);
7803                components.extend(path_components.by_ref());
7804                break;
7805            }
7806            (None, _) => components.push(Component::ParentDir),
7807            (Some(a), Some(b)) if components.is_empty() && a == b => (),
7808            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
7809            (Some(a), Some(_)) => {
7810                components.push(Component::ParentDir);
7811                for _ in base_components {
7812                    components.push(Component::ParentDir);
7813                }
7814                components.push(a);
7815                components.extend(path_components.by_ref());
7816                break;
7817            }
7818        }
7819    }
7820    components.iter().map(|c| c.as_os_str()).collect()
7821}
7822
7823impl Item for Buffer {
7824    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
7825        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
7826    }
7827
7828    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
7829        File::from_dyn(self.file()).map(|file| ProjectPath {
7830            worktree_id: file.worktree_id(cx),
7831            path: file.path().clone(),
7832        })
7833    }
7834}
7835
7836async fn wait_for_loading_buffer(
7837    mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
7838) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
7839    loop {
7840        if let Some(result) = receiver.borrow().as_ref() {
7841            match result {
7842                Ok(buffer) => return Ok(buffer.to_owned()),
7843                Err(e) => return Err(e.to_owned()),
7844            }
7845        }
7846        receiver.next().await;
7847    }
7848}