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