project.rs

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