project.rs

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