project.rs

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