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