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