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        mut rx: UnboundedReceiver<BufferMessage>,
1737        mut cx: AsyncAppContext,
1738    ) {
1739        let mut needs_resync_with_host = false;
1740        while let Some(change) = rx.next().await {
1741            if let Some(this) = this.upgrade(&mut cx) {
1742                let is_local = this.read_with(&cx, |this, _| this.is_local());
1743                match change {
1744                    BufferMessage::Operation {
1745                        buffer_id,
1746                        operation,
1747                    } => {
1748                        if needs_resync_with_host {
1749                            continue;
1750                        }
1751                        let request = this.read_with(&cx, |this, _| {
1752                            let project_id = this.remote_id()?;
1753                            Some(this.client.request(proto::UpdateBuffer {
1754                                buffer_id,
1755                                project_id,
1756                                operations: vec![operation],
1757                            }))
1758                        });
1759                        if let Some(request) = request {
1760                            if request.await.is_err() && !is_local {
1761                                needs_resync_with_host = true;
1762                            }
1763                        }
1764                    }
1765                    BufferMessage::Resync => {
1766                        if this
1767                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))
1768                            .await
1769                            .is_ok()
1770                        {
1771                            needs_resync_with_host = false;
1772                        }
1773                    }
1774                }
1775            } else {
1776                break;
1777            }
1778        }
1779    }
1780
1781    fn on_buffer_event(
1782        &mut self,
1783        buffer: ModelHandle<Buffer>,
1784        event: &BufferEvent,
1785        cx: &mut ModelContext<Self>,
1786    ) -> Option<()> {
1787        match event {
1788            BufferEvent::Operation(operation) => {
1789                self.buffer_changes_tx
1790                    .unbounded_send(BufferMessage::Operation {
1791                        buffer_id: buffer.read(cx).remote_id(),
1792                        operation: language::proto::serialize_operation(operation),
1793                    })
1794                    .ok();
1795            }
1796            BufferEvent::Edited { .. } => {
1797                let language_server = self
1798                    .language_server_for_buffer(buffer.read(cx), cx)
1799                    .map(|(_, server)| server.clone())?;
1800                let buffer = buffer.read(cx);
1801                let file = File::from_dyn(buffer.file())?;
1802                let abs_path = file.as_local()?.abs_path(cx);
1803                let uri = lsp::Url::from_file_path(abs_path).unwrap();
1804                let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1805                let (version, prev_snapshot) = buffer_snapshots.last()?;
1806                let next_snapshot = buffer.text_snapshot();
1807                let next_version = version + 1;
1808
1809                let content_changes = buffer
1810                    .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1811                    .map(|edit| {
1812                        let edit_start = edit.new.start.0;
1813                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1814                        let new_text = next_snapshot
1815                            .text_for_range(edit.new.start.1..edit.new.end.1)
1816                            .collect();
1817                        lsp::TextDocumentContentChangeEvent {
1818                            range: Some(lsp::Range::new(
1819                                point_to_lsp(edit_start),
1820                                point_to_lsp(edit_end),
1821                            )),
1822                            range_length: None,
1823                            text: new_text,
1824                        }
1825                    })
1826                    .collect();
1827
1828                buffer_snapshots.push((next_version, next_snapshot));
1829
1830                language_server
1831                    .notify::<lsp::notification::DidChangeTextDocument>(
1832                        lsp::DidChangeTextDocumentParams {
1833                            text_document: lsp::VersionedTextDocumentIdentifier::new(
1834                                uri,
1835                                next_version,
1836                            ),
1837                            content_changes,
1838                        },
1839                    )
1840                    .log_err();
1841            }
1842            BufferEvent::Saved => {
1843                let file = File::from_dyn(buffer.read(cx).file())?;
1844                let worktree_id = file.worktree_id(cx);
1845                let abs_path = file.as_local()?.abs_path(cx);
1846                let text_document = lsp::TextDocumentIdentifier {
1847                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
1848                };
1849
1850                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1851                    server
1852                        .notify::<lsp::notification::DidSaveTextDocument>(
1853                            lsp::DidSaveTextDocumentParams {
1854                                text_document: text_document.clone(),
1855                                text: None,
1856                            },
1857                        )
1858                        .log_err();
1859                }
1860
1861                let language_server_id = self.language_server_id_for_buffer(buffer.read(cx), cx)?;
1862                if let Some(LanguageServerState::Running {
1863                    adapter,
1864                    simulate_disk_based_diagnostics_completion,
1865                    ..
1866                }) = self.language_servers.get_mut(&language_server_id)
1867                {
1868                    // After saving a buffer using a language server that doesn't provide
1869                    // a disk-based progress token, kick off a timer that will reset every
1870                    // time the buffer is saved. If the timer eventually fires, simulate
1871                    // disk-based diagnostics being finished so that other pieces of UI
1872                    // (e.g., project diagnostics view, diagnostic status bar) can update.
1873                    // We don't emit an event right away because the language server might take
1874                    // some time to publish diagnostics.
1875                    if adapter.disk_based_diagnostics_progress_token.is_none() {
1876                        const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
1877
1878                        let task = cx.spawn_weak(|this, mut cx| async move {
1879                            cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
1880                            if let Some(this) = this.upgrade(&cx) {
1881                                this.update(&mut cx, |this, cx | {
1882                                    this.disk_based_diagnostics_finished(language_server_id, cx);
1883                                    this.broadcast_language_server_update(
1884                                        language_server_id,
1885                                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1886                                            proto::LspDiskBasedDiagnosticsUpdated {},
1887                                        ),
1888                                    );
1889                                });
1890                            }
1891                        });
1892                        *simulate_disk_based_diagnostics_completion = Some(task);
1893                    }
1894                }
1895            }
1896            _ => {}
1897        }
1898
1899        None
1900    }
1901
1902    fn language_servers_for_worktree(
1903        &self,
1904        worktree_id: WorktreeId,
1905    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
1906        self.language_server_ids
1907            .iter()
1908            .filter_map(move |((language_server_worktree_id, _), id)| {
1909                if *language_server_worktree_id == worktree_id {
1910                    if let Some(LanguageServerState::Running {
1911                        adapter,
1912                        language,
1913                        server,
1914                        ..
1915                    }) = self.language_servers.get(id)
1916                    {
1917                        return Some((adapter, language, server));
1918                    }
1919                }
1920                None
1921            })
1922    }
1923
1924    fn maintain_buffer_languages(
1925        languages: &LanguageRegistry,
1926        cx: &mut ModelContext<Project>,
1927    ) -> Task<()> {
1928        let mut subscription = languages.subscribe();
1929        cx.spawn_weak(|project, mut cx| async move {
1930            while let Some(()) = subscription.next().await {
1931                if let Some(project) = project.upgrade(&cx) {
1932                    project.update(&mut cx, |project, cx| {
1933                        let mut plain_text_buffers = Vec::new();
1934                        let mut buffers_with_unknown_injections = Vec::new();
1935                        for buffer in project.opened_buffers.values() {
1936                            if let Some(handle) = buffer.upgrade(cx) {
1937                                let buffer = &handle.read(cx);
1938                                if buffer.language().is_none()
1939                                    || buffer.language() == Some(&*language::PLAIN_TEXT)
1940                                {
1941                                    plain_text_buffers.push(handle);
1942                                } else if buffer.contains_unknown_injections() {
1943                                    buffers_with_unknown_injections.push(handle);
1944                                }
1945                            }
1946                        }
1947
1948                        for buffer in plain_text_buffers {
1949                            project.detect_language_for_buffer(&buffer, cx);
1950                            project.register_buffer_with_language_server(&buffer, cx);
1951                        }
1952
1953                        for buffer in buffers_with_unknown_injections {
1954                            buffer.update(cx, |buffer, cx| buffer.reparse(cx));
1955                        }
1956                    });
1957                }
1958            }
1959        })
1960    }
1961
1962    fn maintain_workspace_config(
1963        languages: Arc<LanguageRegistry>,
1964        cx: &mut ModelContext<Project>,
1965    ) -> Task<()> {
1966        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
1967        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
1968
1969        let settings_observation = cx.observe_global::<Settings, _>(move |_, _| {
1970            *settings_changed_tx.borrow_mut() = ();
1971        });
1972        cx.spawn_weak(|this, mut cx| async move {
1973            while let Some(_) = settings_changed_rx.next().await {
1974                let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
1975                if let Some(this) = this.upgrade(&cx) {
1976                    this.read_with(&cx, |this, _| {
1977                        for server_state in this.language_servers.values() {
1978                            if let LanguageServerState::Running { server, .. } = server_state {
1979                                server
1980                                    .notify::<lsp::notification::DidChangeConfiguration>(
1981                                        lsp::DidChangeConfigurationParams {
1982                                            settings: workspace_config.clone(),
1983                                        },
1984                                    )
1985                                    .ok();
1986                            }
1987                        }
1988                    })
1989                } else {
1990                    break;
1991                }
1992            }
1993
1994            drop(settings_observation);
1995        })
1996    }
1997
1998    fn detect_language_for_buffer(
1999        &mut self,
2000        buffer_handle: &ModelHandle<Buffer>,
2001        cx: &mut ModelContext<Self>,
2002    ) -> Option<()> {
2003        // If the buffer has a language, set it and start the language server if we haven't already.
2004        let buffer = buffer_handle.read(cx);
2005        let full_path = buffer.file()?.full_path(cx);
2006        let content = buffer.as_rope();
2007        let new_language = self
2008            .languages
2009            .language_for_file(&full_path, Some(content))
2010            .now_or_never()?
2011            .ok()?;
2012        self.set_language_for_buffer(buffer_handle, new_language, cx);
2013        None
2014    }
2015
2016    pub fn set_language_for_buffer(
2017        &mut self,
2018        buffer: &ModelHandle<Buffer>,
2019        new_language: Arc<Language>,
2020        cx: &mut ModelContext<Self>,
2021    ) {
2022        buffer.update(cx, |buffer, cx| {
2023            if buffer.language().map_or(true, |old_language| {
2024                !Arc::ptr_eq(old_language, &new_language)
2025            }) {
2026                buffer.set_language(Some(new_language.clone()), cx);
2027            }
2028        });
2029
2030        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2031            if let Some(worktree) = file.worktree.read(cx).as_local() {
2032                let worktree_id = worktree.id();
2033                let worktree_abs_path = worktree.abs_path().clone();
2034                self.start_language_server(worktree_id, worktree_abs_path, new_language, cx);
2035            }
2036        }
2037    }
2038
2039    fn start_language_server(
2040        &mut self,
2041        worktree_id: WorktreeId,
2042        worktree_path: Arc<Path>,
2043        language: Arc<Language>,
2044        cx: &mut ModelContext<Self>,
2045    ) {
2046        if !cx
2047            .global::<Settings>()
2048            .enable_language_server(Some(&language.name()))
2049        {
2050            return;
2051        }
2052
2053        let adapter = if let Some(adapter) = language.lsp_adapter() {
2054            adapter
2055        } else {
2056            return;
2057        };
2058        let key = (worktree_id, adapter.name.clone());
2059
2060        let mut initialization_options = adapter.initialization_options.clone();
2061
2062        let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
2063        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2064        match (&mut initialization_options, override_options) {
2065            (Some(initialization_options), Some(override_options)) => {
2066                merge_json_value_into(override_options, initialization_options);
2067            }
2068            (None, override_options) => initialization_options = override_options,
2069            _ => {}
2070        }
2071
2072        self.language_server_ids
2073            .entry(key.clone())
2074            .or_insert_with(|| {
2075                let languages = self.languages.clone();
2076                let server_id = post_inc(&mut self.next_language_server_id);
2077                let language_server = self.languages.start_language_server(
2078                    server_id,
2079                    language.clone(),
2080                    worktree_path,
2081                    self.client.http_client(),
2082                    cx,
2083                );
2084                self.language_servers.insert(
2085                    server_id,
2086                    LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2087                        let workspace_config =
2088                            cx.update(|cx| languages.workspace_configuration(cx)).await;
2089                        let language_server = language_server?.await.log_err()?;
2090                        let language_server = language_server
2091                            .initialize(initialization_options)
2092                            .await
2093                            .log_err()?;
2094                        let this = this.upgrade(&cx)?;
2095
2096                        language_server
2097                            .on_notification::<lsp::notification::PublishDiagnostics, _>({
2098                                let this = this.downgrade();
2099                                let adapter = adapter.clone();
2100                                move |mut params, cx| {
2101                                    let this = this;
2102                                    let adapter = adapter.clone();
2103                                    cx.spawn(|mut cx| async move {
2104                                        adapter.process_diagnostics(&mut params).await;
2105                                        if let Some(this) = this.upgrade(&cx) {
2106                                            this.update(&mut cx, |this, cx| {
2107                                                this.update_diagnostics(
2108                                                    server_id,
2109                                                    params,
2110                                                    &adapter.disk_based_diagnostic_sources,
2111                                                    cx,
2112                                                )
2113                                                .log_err();
2114                                            });
2115                                        }
2116                                    })
2117                                    .detach();
2118                                }
2119                            })
2120                            .detach();
2121
2122                        language_server
2123                            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2124                                let languages = languages.clone();
2125                                move |params, mut cx| {
2126                                    let languages = languages.clone();
2127                                    async move {
2128                                        let workspace_config = cx
2129                                            .update(|cx| languages.workspace_configuration(cx))
2130                                            .await;
2131                                        Ok(params
2132                                            .items
2133                                            .into_iter()
2134                                            .map(|item| {
2135                                                if let Some(section) = &item.section {
2136                                                    workspace_config
2137                                                        .get(section)
2138                                                        .cloned()
2139                                                        .unwrap_or(serde_json::Value::Null)
2140                                                } else {
2141                                                    workspace_config.clone()
2142                                                }
2143                                            })
2144                                            .collect())
2145                                    }
2146                                }
2147                            })
2148                            .detach();
2149
2150                        // Even though we don't have handling for these requests, respond to them to
2151                        // avoid stalling any language server like `gopls` which waits for a response
2152                        // to these requests when initializing.
2153                        language_server
2154                            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2155                                let this = this.downgrade();
2156                                move |params, mut cx| async move {
2157                                    if let Some(this) = this.upgrade(&cx) {
2158                                        this.update(&mut cx, |this, _| {
2159                                            if let Some(status) =
2160                                                this.language_server_statuses.get_mut(&server_id)
2161                                            {
2162                                                if let lsp::NumberOrString::String(token) =
2163                                                    params.token
2164                                                {
2165                                                    status.progress_tokens.insert(token);
2166                                                }
2167                                            }
2168                                        });
2169                                    }
2170                                    Ok(())
2171                                }
2172                            })
2173                            .detach();
2174                        language_server
2175                            .on_request::<lsp::request::RegisterCapability, _, _>({
2176                                let this = this.downgrade();
2177                                move |params, mut cx| async move {
2178                                    let this = this
2179                                        .upgrade(&cx)
2180                                        .ok_or_else(|| anyhow!("project dropped"))?;
2181                                    for reg in params.registrations {
2182                                        if reg.method == "workspace/didChangeWatchedFiles" {
2183                                            if let Some(options) = reg.register_options {
2184                                                let options = serde_json::from_value(options)?;
2185                                                this.update(&mut cx, |this, cx| {
2186                                                    this.on_lsp_did_change_watched_files(
2187                                                        server_id, options, cx,
2188                                                    );
2189                                                });
2190                                            }
2191                                        }
2192                                    }
2193                                    Ok(())
2194                                }
2195                            })
2196                            .detach();
2197
2198                        language_server
2199                            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2200                                let this = this.downgrade();
2201                                let adapter = adapter.clone();
2202                                let language_server = language_server.clone();
2203                                move |params, cx| {
2204                                    Self::on_lsp_workspace_edit(
2205                                        this,
2206                                        params,
2207                                        server_id,
2208                                        adapter.clone(),
2209                                        language_server.clone(),
2210                                        cx,
2211                                    )
2212                                }
2213                            })
2214                            .detach();
2215
2216                        let disk_based_diagnostics_progress_token =
2217                            adapter.disk_based_diagnostics_progress_token.clone();
2218
2219                        language_server
2220                            .on_notification::<lsp::notification::Progress, _>({
2221                                let this = this.downgrade();
2222                                move |params, mut cx| {
2223                                    if let Some(this) = this.upgrade(&cx) {
2224                                        this.update(&mut cx, |this, cx| {
2225                                            this.on_lsp_progress(
2226                                                params,
2227                                                server_id,
2228                                                disk_based_diagnostics_progress_token.clone(),
2229                                                cx,
2230                                            );
2231                                        });
2232                                    }
2233                                }
2234                            })
2235                            .detach();
2236
2237                        language_server
2238                            .notify::<lsp::notification::DidChangeConfiguration>(
2239                                lsp::DidChangeConfigurationParams {
2240                                    settings: workspace_config,
2241                                },
2242                            )
2243                            .ok();
2244
2245                        this.update(&mut cx, |this, cx| {
2246                            // If the language server for this key doesn't match the server id, don't store the
2247                            // server. Which will cause it to be dropped, killing the process
2248                            if this
2249                                .language_server_ids
2250                                .get(&key)
2251                                .map(|id| id != &server_id)
2252                                .unwrap_or(false)
2253                            {
2254                                return None;
2255                            }
2256
2257                            // Update language_servers collection with Running variant of LanguageServerState
2258                            // indicating that the server is up and running and ready
2259                            this.language_servers.insert(
2260                                server_id,
2261                                LanguageServerState::Running {
2262                                    adapter: adapter.clone(),
2263                                    language,
2264                                    watched_paths: Default::default(),
2265                                    server: language_server.clone(),
2266                                    simulate_disk_based_diagnostics_completion: None,
2267                                },
2268                            );
2269                            this.language_server_statuses.insert(
2270                                server_id,
2271                                LanguageServerStatus {
2272                                    name: language_server.name().to_string(),
2273                                    pending_work: Default::default(),
2274                                    has_pending_diagnostic_updates: false,
2275                                    progress_tokens: Default::default(),
2276                                },
2277                            );
2278
2279                            if let Some(project_id) = this.remote_id() {
2280                                this.client
2281                                    .send(proto::StartLanguageServer {
2282                                        project_id,
2283                                        server: Some(proto::LanguageServer {
2284                                            id: server_id as u64,
2285                                            name: language_server.name().to_string(),
2286                                        }),
2287                                    })
2288                                    .log_err();
2289                            }
2290
2291                            // Tell the language server about every open buffer in the worktree that matches the language.
2292                            for buffer in this.opened_buffers.values() {
2293                                if let Some(buffer_handle) = buffer.upgrade(cx) {
2294                                    let buffer = buffer_handle.read(cx);
2295                                    let file = if let Some(file) = File::from_dyn(buffer.file()) {
2296                                        file
2297                                    } else {
2298                                        continue;
2299                                    };
2300                                    let language = if let Some(language) = buffer.language() {
2301                                        language
2302                                    } else {
2303                                        continue;
2304                                    };
2305                                    if file.worktree.read(cx).id() != key.0
2306                                        || language.lsp_adapter().map(|a| a.name.clone())
2307                                            != Some(key.1.clone())
2308                                    {
2309                                        continue;
2310                                    }
2311
2312                                    let file = file.as_local()?;
2313                                    let versions = this
2314                                        .buffer_snapshots
2315                                        .entry(buffer.remote_id())
2316                                        .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2317
2318                                    let (version, initial_snapshot) = versions.last().unwrap();
2319                                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2320                                    language_server
2321                                        .notify::<lsp::notification::DidOpenTextDocument>(
2322                                            lsp::DidOpenTextDocumentParams {
2323                                                text_document: lsp::TextDocumentItem::new(
2324                                                    uri,
2325                                                    adapter
2326                                                        .language_ids
2327                                                        .get(language.name().as_ref())
2328                                                        .cloned()
2329                                                        .unwrap_or_default(),
2330                                                    *version,
2331                                                    initial_snapshot.text(),
2332                                                ),
2333                                            },
2334                                        )
2335                                        .log_err()?;
2336                                    buffer_handle.update(cx, |buffer, cx| {
2337                                        buffer.set_completion_triggers(
2338                                            language_server
2339                                                .capabilities()
2340                                                .completion_provider
2341                                                .as_ref()
2342                                                .and_then(|provider| {
2343                                                    provider.trigger_characters.clone()
2344                                                })
2345                                                .unwrap_or_default(),
2346                                            cx,
2347                                        )
2348                                    });
2349                                }
2350                            }
2351
2352                            cx.notify();
2353                            Some(language_server)
2354                        })
2355                    })),
2356                );
2357
2358                server_id
2359            });
2360    }
2361
2362    // Returns a list of all of the worktrees which no longer have a language server and the root path
2363    // for the stopped server
2364    fn stop_language_server(
2365        &mut self,
2366        worktree_id: WorktreeId,
2367        adapter_name: LanguageServerName,
2368        cx: &mut ModelContext<Self>,
2369    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2370        let key = (worktree_id, adapter_name);
2371        if let Some(server_id) = self.language_server_ids.remove(&key) {
2372            // Remove other entries for this language server as well
2373            let mut orphaned_worktrees = vec![worktree_id];
2374            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2375            for other_key in other_keys {
2376                if self.language_server_ids.get(&other_key) == Some(&server_id) {
2377                    self.language_server_ids.remove(&other_key);
2378                    orphaned_worktrees.push(other_key.0);
2379                }
2380            }
2381
2382            self.language_server_statuses.remove(&server_id);
2383            cx.notify();
2384
2385            let server_state = self.language_servers.remove(&server_id);
2386            cx.spawn_weak(|this, mut cx| async move {
2387                let mut root_path = None;
2388
2389                let server = match server_state {
2390                    Some(LanguageServerState::Starting(started_language_server)) => {
2391                        started_language_server.await
2392                    }
2393                    Some(LanguageServerState::Running { server, .. }) => Some(server),
2394                    None => None,
2395                };
2396
2397                if let Some(server) = server {
2398                    root_path = Some(server.root_path().clone());
2399                    if let Some(shutdown) = server.shutdown() {
2400                        shutdown.await;
2401                    }
2402                }
2403
2404                if let Some(this) = this.upgrade(&cx) {
2405                    this.update(&mut cx, |this, cx| {
2406                        this.language_server_statuses.remove(&server_id);
2407                        cx.notify();
2408                    });
2409                }
2410
2411                (root_path, orphaned_worktrees)
2412            })
2413        } else {
2414            Task::ready((None, Vec::new()))
2415        }
2416    }
2417
2418    pub fn restart_language_servers_for_buffers(
2419        &mut self,
2420        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2421        cx: &mut ModelContext<Self>,
2422    ) -> Option<()> {
2423        let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, Arc<Language>)> = buffers
2424            .into_iter()
2425            .filter_map(|buffer| {
2426                let buffer = buffer.read(cx);
2427                let file = File::from_dyn(buffer.file())?;
2428                let worktree = file.worktree.read(cx).as_local()?;
2429                let full_path = file.full_path(cx);
2430                let language = self
2431                    .languages
2432                    .language_for_file(&full_path, Some(buffer.as_rope()))
2433                    .now_or_never()?
2434                    .ok()?;
2435                Some((worktree.id(), worktree.abs_path().clone(), language))
2436            })
2437            .collect();
2438        for (worktree_id, worktree_abs_path, language) in language_server_lookup_info {
2439            self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2440        }
2441
2442        None
2443    }
2444
2445    fn restart_language_server(
2446        &mut self,
2447        worktree_id: WorktreeId,
2448        fallback_path: Arc<Path>,
2449        language: Arc<Language>,
2450        cx: &mut ModelContext<Self>,
2451    ) {
2452        let adapter = if let Some(adapter) = language.lsp_adapter() {
2453            adapter
2454        } else {
2455            return;
2456        };
2457
2458        let server_name = adapter.name.clone();
2459        let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2460        cx.spawn_weak(|this, mut cx| async move {
2461            let (original_root_path, orphaned_worktrees) = stop.await;
2462            if let Some(this) = this.upgrade(&cx) {
2463                this.update(&mut cx, |this, cx| {
2464                    // Attempt to restart using original server path. Fallback to passed in
2465                    // path if we could not retrieve the root path
2466                    let root_path = original_root_path
2467                        .map(|path_buf| Arc::from(path_buf.as_path()))
2468                        .unwrap_or(fallback_path);
2469
2470                    this.start_language_server(worktree_id, root_path, language, cx);
2471
2472                    // Lookup new server id and set it for each of the orphaned worktrees
2473                    if let Some(new_server_id) = this
2474                        .language_server_ids
2475                        .get(&(worktree_id, server_name.clone()))
2476                        .cloned()
2477                    {
2478                        for orphaned_worktree in orphaned_worktrees {
2479                            this.language_server_ids
2480                                .insert((orphaned_worktree, server_name.clone()), new_server_id);
2481                        }
2482                    }
2483                });
2484            }
2485        })
2486        .detach();
2487    }
2488
2489    fn on_lsp_progress(
2490        &mut self,
2491        progress: lsp::ProgressParams,
2492        server_id: usize,
2493        disk_based_diagnostics_progress_token: Option<String>,
2494        cx: &mut ModelContext<Self>,
2495    ) {
2496        let token = match progress.token {
2497            lsp::NumberOrString::String(token) => token,
2498            lsp::NumberOrString::Number(token) => {
2499                log::info!("skipping numeric progress token {}", token);
2500                return;
2501            }
2502        };
2503        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2504        let language_server_status =
2505            if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2506                status
2507            } else {
2508                return;
2509            };
2510
2511        if !language_server_status.progress_tokens.contains(&token) {
2512            return;
2513        }
2514
2515        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
2516            .as_ref()
2517            .map_or(false, |disk_based_token| {
2518                token.starts_with(disk_based_token)
2519            });
2520
2521        match progress {
2522            lsp::WorkDoneProgress::Begin(report) => {
2523                if is_disk_based_diagnostics_progress {
2524                    language_server_status.has_pending_diagnostic_updates = true;
2525                    self.disk_based_diagnostics_started(server_id, cx);
2526                    self.broadcast_language_server_update(
2527                        server_id,
2528                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2529                            proto::LspDiskBasedDiagnosticsUpdating {},
2530                        ),
2531                    );
2532                } else {
2533                    self.on_lsp_work_start(
2534                        server_id,
2535                        token.clone(),
2536                        LanguageServerProgress {
2537                            message: report.message.clone(),
2538                            percentage: report.percentage.map(|p| p as usize),
2539                            last_update_at: Instant::now(),
2540                        },
2541                        cx,
2542                    );
2543                    self.broadcast_language_server_update(
2544                        server_id,
2545                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2546                            token,
2547                            message: report.message,
2548                            percentage: report.percentage.map(|p| p as u32),
2549                        }),
2550                    );
2551                }
2552            }
2553            lsp::WorkDoneProgress::Report(report) => {
2554                if !is_disk_based_diagnostics_progress {
2555                    self.on_lsp_work_progress(
2556                        server_id,
2557                        token.clone(),
2558                        LanguageServerProgress {
2559                            message: report.message.clone(),
2560                            percentage: report.percentage.map(|p| p as usize),
2561                            last_update_at: Instant::now(),
2562                        },
2563                        cx,
2564                    );
2565                    self.broadcast_language_server_update(
2566                        server_id,
2567                        proto::update_language_server::Variant::WorkProgress(
2568                            proto::LspWorkProgress {
2569                                token,
2570                                message: report.message,
2571                                percentage: report.percentage.map(|p| p as u32),
2572                            },
2573                        ),
2574                    );
2575                }
2576            }
2577            lsp::WorkDoneProgress::End(_) => {
2578                language_server_status.progress_tokens.remove(&token);
2579
2580                if is_disk_based_diagnostics_progress {
2581                    language_server_status.has_pending_diagnostic_updates = false;
2582                    self.disk_based_diagnostics_finished(server_id, cx);
2583                    self.broadcast_language_server_update(
2584                        server_id,
2585                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2586                            proto::LspDiskBasedDiagnosticsUpdated {},
2587                        ),
2588                    );
2589                } else {
2590                    self.on_lsp_work_end(server_id, token.clone(), cx);
2591                    self.broadcast_language_server_update(
2592                        server_id,
2593                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2594                            token,
2595                        }),
2596                    );
2597                }
2598            }
2599        }
2600    }
2601
2602    fn on_lsp_work_start(
2603        &mut self,
2604        language_server_id: usize,
2605        token: String,
2606        progress: LanguageServerProgress,
2607        cx: &mut ModelContext<Self>,
2608    ) {
2609        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2610            status.pending_work.insert(token, progress);
2611            cx.notify();
2612        }
2613    }
2614
2615    fn on_lsp_work_progress(
2616        &mut self,
2617        language_server_id: usize,
2618        token: String,
2619        progress: LanguageServerProgress,
2620        cx: &mut ModelContext<Self>,
2621    ) {
2622        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2623            let entry = status
2624                .pending_work
2625                .entry(token)
2626                .or_insert(LanguageServerProgress {
2627                    message: Default::default(),
2628                    percentage: Default::default(),
2629                    last_update_at: progress.last_update_at,
2630                });
2631            if progress.message.is_some() {
2632                entry.message = progress.message;
2633            }
2634            if progress.percentage.is_some() {
2635                entry.percentage = progress.percentage;
2636            }
2637            entry.last_update_at = progress.last_update_at;
2638            cx.notify();
2639        }
2640    }
2641
2642    fn on_lsp_work_end(
2643        &mut self,
2644        language_server_id: usize,
2645        token: String,
2646        cx: &mut ModelContext<Self>,
2647    ) {
2648        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2649            status.pending_work.remove(&token);
2650            cx.notify();
2651        }
2652    }
2653
2654    fn on_lsp_did_change_watched_files(
2655        &mut self,
2656        language_server_id: usize,
2657        params: DidChangeWatchedFilesRegistrationOptions,
2658        cx: &mut ModelContext<Self>,
2659    ) {
2660        if let Some(LanguageServerState::Running { watched_paths, .. }) =
2661            self.language_servers.get_mut(&language_server_id)
2662        {
2663            watched_paths.clear();
2664            for watcher in params.watchers {
2665                watched_paths.add_pattern(&watcher.glob_pattern).log_err();
2666            }
2667            cx.notify();
2668        }
2669    }
2670
2671    async fn on_lsp_workspace_edit(
2672        this: WeakModelHandle<Self>,
2673        params: lsp::ApplyWorkspaceEditParams,
2674        server_id: usize,
2675        adapter: Arc<CachedLspAdapter>,
2676        language_server: Arc<LanguageServer>,
2677        mut cx: AsyncAppContext,
2678    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2679        let this = this
2680            .upgrade(&cx)
2681            .ok_or_else(|| anyhow!("project project closed"))?;
2682        let transaction = Self::deserialize_workspace_edit(
2683            this.clone(),
2684            params.edit,
2685            true,
2686            adapter.clone(),
2687            language_server.clone(),
2688            &mut cx,
2689        )
2690        .await
2691        .log_err();
2692        this.update(&mut cx, |this, _| {
2693            if let Some(transaction) = transaction {
2694                this.last_workspace_edits_by_language_server
2695                    .insert(server_id, transaction);
2696            }
2697        });
2698        Ok(lsp::ApplyWorkspaceEditResponse {
2699            applied: true,
2700            failed_change: None,
2701            failure_reason: None,
2702        })
2703    }
2704
2705    fn broadcast_language_server_update(
2706        &self,
2707        language_server_id: usize,
2708        event: proto::update_language_server::Variant,
2709    ) {
2710        if let Some(project_id) = self.remote_id() {
2711            self.client
2712                .send(proto::UpdateLanguageServer {
2713                    project_id,
2714                    language_server_id: language_server_id as u64,
2715                    variant: Some(event),
2716                })
2717                .log_err();
2718        }
2719    }
2720
2721    pub fn language_server_statuses(
2722        &self,
2723    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2724        self.language_server_statuses.values()
2725    }
2726
2727    pub fn update_diagnostics(
2728        &mut self,
2729        language_server_id: usize,
2730        mut params: lsp::PublishDiagnosticsParams,
2731        disk_based_sources: &[String],
2732        cx: &mut ModelContext<Self>,
2733    ) -> Result<()> {
2734        let abs_path = params
2735            .uri
2736            .to_file_path()
2737            .map_err(|_| anyhow!("URI is not a file"))?;
2738        let mut diagnostics = Vec::default();
2739        let mut primary_diagnostic_group_ids = HashMap::default();
2740        let mut sources_by_group_id = HashMap::default();
2741        let mut supporting_diagnostics = HashMap::default();
2742
2743        // Ensure that primary diagnostics are always the most severe
2744        params.diagnostics.sort_by_key(|item| item.severity);
2745
2746        for diagnostic in &params.diagnostics {
2747            let source = diagnostic.source.as_ref();
2748            let code = diagnostic.code.as_ref().map(|code| match code {
2749                lsp::NumberOrString::Number(code) => code.to_string(),
2750                lsp::NumberOrString::String(code) => code.clone(),
2751            });
2752            let range = range_from_lsp(diagnostic.range);
2753            let is_supporting = diagnostic
2754                .related_information
2755                .as_ref()
2756                .map_or(false, |infos| {
2757                    infos.iter().any(|info| {
2758                        primary_diagnostic_group_ids.contains_key(&(
2759                            source,
2760                            code.clone(),
2761                            range_from_lsp(info.location.range),
2762                        ))
2763                    })
2764                });
2765
2766            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2767                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2768            });
2769
2770            if is_supporting {
2771                supporting_diagnostics.insert(
2772                    (source, code.clone(), range),
2773                    (diagnostic.severity, is_unnecessary),
2774                );
2775            } else {
2776                let group_id = post_inc(&mut self.next_diagnostic_group_id);
2777                let is_disk_based =
2778                    source.map_or(false, |source| disk_based_sources.contains(source));
2779
2780                sources_by_group_id.insert(group_id, source);
2781                primary_diagnostic_group_ids
2782                    .insert((source, code.clone(), range.clone()), group_id);
2783
2784                diagnostics.push(DiagnosticEntry {
2785                    range,
2786                    diagnostic: Diagnostic {
2787                        code: code.clone(),
2788                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2789                        message: diagnostic.message.clone(),
2790                        group_id,
2791                        is_primary: true,
2792                        is_valid: true,
2793                        is_disk_based,
2794                        is_unnecessary,
2795                    },
2796                });
2797                if let Some(infos) = &diagnostic.related_information {
2798                    for info in infos {
2799                        if info.location.uri == params.uri && !info.message.is_empty() {
2800                            let range = range_from_lsp(info.location.range);
2801                            diagnostics.push(DiagnosticEntry {
2802                                range,
2803                                diagnostic: Diagnostic {
2804                                    code: code.clone(),
2805                                    severity: DiagnosticSeverity::INFORMATION,
2806                                    message: info.message.clone(),
2807                                    group_id,
2808                                    is_primary: false,
2809                                    is_valid: true,
2810                                    is_disk_based,
2811                                    is_unnecessary: false,
2812                                },
2813                            });
2814                        }
2815                    }
2816                }
2817            }
2818        }
2819
2820        for entry in &mut diagnostics {
2821            let diagnostic = &mut entry.diagnostic;
2822            if !diagnostic.is_primary {
2823                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2824                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2825                    source,
2826                    diagnostic.code.clone(),
2827                    entry.range.clone(),
2828                )) {
2829                    if let Some(severity) = severity {
2830                        diagnostic.severity = severity;
2831                    }
2832                    diagnostic.is_unnecessary = is_unnecessary;
2833                }
2834            }
2835        }
2836
2837        self.update_diagnostic_entries(
2838            language_server_id,
2839            abs_path,
2840            params.version,
2841            diagnostics,
2842            cx,
2843        )?;
2844        Ok(())
2845    }
2846
2847    pub fn update_diagnostic_entries(
2848        &mut self,
2849        language_server_id: usize,
2850        abs_path: PathBuf,
2851        version: Option<i32>,
2852        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2853        cx: &mut ModelContext<Project>,
2854    ) -> Result<(), anyhow::Error> {
2855        let (worktree, relative_path) = self
2856            .find_local_worktree(&abs_path, cx)
2857            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2858
2859        let project_path = ProjectPath {
2860            worktree_id: worktree.read(cx).id(),
2861            path: relative_path.into(),
2862        };
2863
2864        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2865            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2866        }
2867
2868        let updated = worktree.update(cx, |worktree, cx| {
2869            worktree
2870                .as_local_mut()
2871                .ok_or_else(|| anyhow!("not a local worktree"))?
2872                .update_diagnostics(
2873                    language_server_id,
2874                    project_path.path.clone(),
2875                    diagnostics,
2876                    cx,
2877                )
2878        })?;
2879        if updated {
2880            cx.emit(Event::DiagnosticsUpdated {
2881                language_server_id,
2882                path: project_path,
2883            });
2884        }
2885        Ok(())
2886    }
2887
2888    fn update_buffer_diagnostics(
2889        &mut self,
2890        buffer: &ModelHandle<Buffer>,
2891        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2892        version: Option<i32>,
2893        cx: &mut ModelContext<Self>,
2894    ) -> Result<()> {
2895        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2896            Ordering::Equal
2897                .then_with(|| b.is_primary.cmp(&a.is_primary))
2898                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2899                .then_with(|| a.severity.cmp(&b.severity))
2900                .then_with(|| a.message.cmp(&b.message))
2901        }
2902
2903        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2904
2905        diagnostics.sort_unstable_by(|a, b| {
2906            Ordering::Equal
2907                .then_with(|| a.range.start.cmp(&b.range.start))
2908                .then_with(|| b.range.end.cmp(&a.range.end))
2909                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2910        });
2911
2912        let mut sanitized_diagnostics = Vec::new();
2913        let edits_since_save = Patch::new(
2914            snapshot
2915                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
2916                .collect(),
2917        );
2918        for entry in diagnostics {
2919            let start;
2920            let end;
2921            if entry.diagnostic.is_disk_based {
2922                // Some diagnostics are based on files on disk instead of buffers'
2923                // current contents. Adjust these diagnostics' ranges to reflect
2924                // any unsaved edits.
2925                start = edits_since_save.old_to_new(entry.range.start);
2926                end = edits_since_save.old_to_new(entry.range.end);
2927            } else {
2928                start = entry.range.start;
2929                end = entry.range.end;
2930            }
2931
2932            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2933                ..snapshot.clip_point_utf16(end, Bias::Right);
2934
2935            // Expand empty ranges by one codepoint
2936            if range.start == range.end {
2937                // This will be go to the next boundary when being clipped
2938                range.end.column += 1;
2939                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
2940                if range.start == range.end && range.end.column > 0 {
2941                    range.start.column -= 1;
2942                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
2943                }
2944            }
2945
2946            sanitized_diagnostics.push(DiagnosticEntry {
2947                range,
2948                diagnostic: entry.diagnostic,
2949            });
2950        }
2951        drop(edits_since_save);
2952
2953        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2954        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2955        Ok(())
2956    }
2957
2958    pub fn reload_buffers(
2959        &self,
2960        buffers: HashSet<ModelHandle<Buffer>>,
2961        push_to_history: bool,
2962        cx: &mut ModelContext<Self>,
2963    ) -> Task<Result<ProjectTransaction>> {
2964        let mut local_buffers = Vec::new();
2965        let mut remote_buffers = None;
2966        for buffer_handle in buffers {
2967            let buffer = buffer_handle.read(cx);
2968            if buffer.is_dirty() {
2969                if let Some(file) = File::from_dyn(buffer.file()) {
2970                    if file.is_local() {
2971                        local_buffers.push(buffer_handle);
2972                    } else {
2973                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2974                    }
2975                }
2976            }
2977        }
2978
2979        let remote_buffers = self.remote_id().zip(remote_buffers);
2980        let client = self.client.clone();
2981
2982        cx.spawn(|this, mut cx| async move {
2983            let mut project_transaction = ProjectTransaction::default();
2984
2985            if let Some((project_id, remote_buffers)) = remote_buffers {
2986                let response = client
2987                    .request(proto::ReloadBuffers {
2988                        project_id,
2989                        buffer_ids: remote_buffers
2990                            .iter()
2991                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2992                            .collect(),
2993                    })
2994                    .await?
2995                    .transaction
2996                    .ok_or_else(|| anyhow!("missing transaction"))?;
2997                project_transaction = this
2998                    .update(&mut cx, |this, cx| {
2999                        this.deserialize_project_transaction(response, push_to_history, cx)
3000                    })
3001                    .await?;
3002            }
3003
3004            for buffer in local_buffers {
3005                let transaction = buffer
3006                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
3007                    .await?;
3008                buffer.update(&mut cx, |buffer, cx| {
3009                    if let Some(transaction) = transaction {
3010                        if !push_to_history {
3011                            buffer.forget_transaction(transaction.id);
3012                        }
3013                        project_transaction.0.insert(cx.handle(), transaction);
3014                    }
3015                });
3016            }
3017
3018            Ok(project_transaction)
3019        })
3020    }
3021
3022    pub fn format(
3023        &self,
3024        buffers: HashSet<ModelHandle<Buffer>>,
3025        push_to_history: bool,
3026        trigger: FormatTrigger,
3027        cx: &mut ModelContext<Project>,
3028    ) -> Task<Result<ProjectTransaction>> {
3029        if self.is_local() {
3030            let mut buffers_with_paths_and_servers = buffers
3031                .into_iter()
3032                .filter_map(|buffer_handle| {
3033                    let buffer = buffer_handle.read(cx);
3034                    let file = File::from_dyn(buffer.file())?;
3035                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3036                    let server = self
3037                        .language_server_for_buffer(buffer, cx)
3038                        .map(|s| s.1.clone());
3039                    Some((buffer_handle, buffer_abs_path, server))
3040                })
3041                .collect::<Vec<_>>();
3042
3043            cx.spawn(|this, mut cx| async move {
3044                // Do not allow multiple concurrent formatting requests for the
3045                // same buffer.
3046                this.update(&mut cx, |this, _| {
3047                    buffers_with_paths_and_servers
3048                        .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
3049                });
3050
3051                let _cleanup = defer({
3052                    let this = this.clone();
3053                    let mut cx = cx.clone();
3054                    let buffers = &buffers_with_paths_and_servers;
3055                    move || {
3056                        this.update(&mut cx, |this, _| {
3057                            for (buffer, _, _) in buffers {
3058                                this.buffers_being_formatted.remove(&buffer.id());
3059                            }
3060                        });
3061                    }
3062                });
3063
3064                let mut project_transaction = ProjectTransaction::default();
3065                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3066                    let (
3067                        format_on_save,
3068                        remove_trailing_whitespace,
3069                        ensure_final_newline,
3070                        formatter,
3071                        tab_size,
3072                    ) = buffer.read_with(&cx, |buffer, cx| {
3073                        let settings = cx.global::<Settings>();
3074                        let language_name = buffer.language().map(|language| language.name());
3075                        (
3076                            settings.format_on_save(language_name.as_deref()),
3077                            settings.remove_trailing_whitespace_on_save(language_name.as_deref()),
3078                            settings.ensure_final_newline_on_save(language_name.as_deref()),
3079                            settings.formatter(language_name.as_deref()),
3080                            settings.tab_size(language_name.as_deref()),
3081                        )
3082                    });
3083
3084                    // First, format buffer's whitespace according to the settings.
3085                    let trailing_whitespace_diff = if remove_trailing_whitespace {
3086                        Some(
3087                            buffer
3088                                .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3089                                .await,
3090                        )
3091                    } else {
3092                        None
3093                    };
3094                    let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3095                        buffer.finalize_last_transaction();
3096                        buffer.start_transaction();
3097                        if let Some(diff) = trailing_whitespace_diff {
3098                            buffer.apply_diff(diff, cx);
3099                        }
3100                        if ensure_final_newline {
3101                            buffer.ensure_final_newline(cx);
3102                        }
3103                        buffer.end_transaction(cx)
3104                    });
3105
3106                    // Currently, formatting operations are represented differently depending on
3107                    // whether they come from a language server or an external command.
3108                    enum FormatOperation {
3109                        Lsp(Vec<(Range<Anchor>, String)>),
3110                        External(Diff),
3111                    }
3112
3113                    // Apply language-specific formatting using either a language server
3114                    // or external command.
3115                    let mut format_operation = None;
3116                    match (formatter, format_on_save) {
3117                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3118
3119                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3120                        | (_, FormatOnSave::LanguageServer) => {
3121                            if let Some((language_server, buffer_abs_path)) =
3122                                language_server.as_ref().zip(buffer_abs_path.as_ref())
3123                            {
3124                                format_operation = Some(FormatOperation::Lsp(
3125                                    Self::format_via_lsp(
3126                                        &this,
3127                                        &buffer,
3128                                        buffer_abs_path,
3129                                        &language_server,
3130                                        tab_size,
3131                                        &mut cx,
3132                                    )
3133                                    .await
3134                                    .context("failed to format via language server")?,
3135                                ));
3136                            }
3137                        }
3138
3139                        (
3140                            Formatter::External { command, arguments },
3141                            FormatOnSave::On | FormatOnSave::Off,
3142                        )
3143                        | (_, FormatOnSave::External { command, arguments }) => {
3144                            if let Some(buffer_abs_path) = buffer_abs_path {
3145                                format_operation = Self::format_via_external_command(
3146                                    &buffer,
3147                                    &buffer_abs_path,
3148                                    &command,
3149                                    &arguments,
3150                                    &mut cx,
3151                                )
3152                                .await
3153                                .context(format!(
3154                                    "failed to format via external command {:?}",
3155                                    command
3156                                ))?
3157                                .map(FormatOperation::External);
3158                            }
3159                        }
3160                    };
3161
3162                    buffer.update(&mut cx, |b, cx| {
3163                        // If the buffer had its whitespace formatted and was edited while the language-specific
3164                        // formatting was being computed, avoid applying the language-specific formatting, because
3165                        // it can't be grouped with the whitespace formatting in the undo history.
3166                        if let Some(transaction_id) = whitespace_transaction_id {
3167                            if b.peek_undo_stack()
3168                                .map_or(true, |e| e.transaction_id() != transaction_id)
3169                            {
3170                                format_operation.take();
3171                            }
3172                        }
3173
3174                        // Apply any language-specific formatting, and group the two formatting operations
3175                        // in the buffer's undo history.
3176                        if let Some(operation) = format_operation {
3177                            match operation {
3178                                FormatOperation::Lsp(edits) => {
3179                                    b.edit(edits, None, cx);
3180                                }
3181                                FormatOperation::External(diff) => {
3182                                    b.apply_diff(diff, cx);
3183                                }
3184                            }
3185
3186                            if let Some(transaction_id) = whitespace_transaction_id {
3187                                b.group_until_transaction(transaction_id);
3188                            }
3189                        }
3190
3191                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
3192                            if !push_to_history {
3193                                b.forget_transaction(transaction.id);
3194                            }
3195                            project_transaction.0.insert(buffer.clone(), transaction);
3196                        }
3197                    });
3198                }
3199
3200                Ok(project_transaction)
3201            })
3202        } else {
3203            let remote_id = self.remote_id();
3204            let client = self.client.clone();
3205            cx.spawn(|this, mut cx| async move {
3206                let mut project_transaction = ProjectTransaction::default();
3207                if let Some(project_id) = remote_id {
3208                    let response = client
3209                        .request(proto::FormatBuffers {
3210                            project_id,
3211                            trigger: trigger as i32,
3212                            buffer_ids: buffers
3213                                .iter()
3214                                .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3215                                .collect(),
3216                        })
3217                        .await?
3218                        .transaction
3219                        .ok_or_else(|| anyhow!("missing transaction"))?;
3220                    project_transaction = this
3221                        .update(&mut cx, |this, cx| {
3222                            this.deserialize_project_transaction(response, push_to_history, cx)
3223                        })
3224                        .await?;
3225                }
3226                Ok(project_transaction)
3227            })
3228        }
3229    }
3230
3231    async fn format_via_lsp(
3232        this: &ModelHandle<Self>,
3233        buffer: &ModelHandle<Buffer>,
3234        abs_path: &Path,
3235        language_server: &Arc<LanguageServer>,
3236        tab_size: NonZeroU32,
3237        cx: &mut AsyncAppContext,
3238    ) -> Result<Vec<(Range<Anchor>, String)>> {
3239        let text_document =
3240            lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3241        let capabilities = &language_server.capabilities();
3242        let lsp_edits = if capabilities
3243            .document_formatting_provider
3244            .as_ref()
3245            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3246        {
3247            language_server
3248                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3249                    text_document,
3250                    options: lsp::FormattingOptions {
3251                        tab_size: tab_size.into(),
3252                        insert_spaces: true,
3253                        insert_final_newline: Some(true),
3254                        ..Default::default()
3255                    },
3256                    work_done_progress_params: Default::default(),
3257                })
3258                .await?
3259        } else if capabilities
3260            .document_range_formatting_provider
3261            .as_ref()
3262            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3263        {
3264            let buffer_start = lsp::Position::new(0, 0);
3265            let buffer_end =
3266                buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3267            language_server
3268                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3269                    text_document,
3270                    range: lsp::Range::new(buffer_start, buffer_end),
3271                    options: lsp::FormattingOptions {
3272                        tab_size: tab_size.into(),
3273                        insert_spaces: true,
3274                        insert_final_newline: Some(true),
3275                        ..Default::default()
3276                    },
3277                    work_done_progress_params: Default::default(),
3278                })
3279                .await?
3280        } else {
3281            None
3282        };
3283
3284        if let Some(lsp_edits) = lsp_edits {
3285            this.update(cx, |this, cx| {
3286                this.edits_from_lsp(buffer, lsp_edits, None, cx)
3287            })
3288            .await
3289        } else {
3290            Ok(Default::default())
3291        }
3292    }
3293
3294    async fn format_via_external_command(
3295        buffer: &ModelHandle<Buffer>,
3296        buffer_abs_path: &Path,
3297        command: &str,
3298        arguments: &[String],
3299        cx: &mut AsyncAppContext,
3300    ) -> Result<Option<Diff>> {
3301        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3302            let file = File::from_dyn(buffer.file())?;
3303            let worktree = file.worktree.read(cx).as_local()?;
3304            let mut worktree_path = worktree.abs_path().to_path_buf();
3305            if worktree.root_entry()?.is_file() {
3306                worktree_path.pop();
3307            }
3308            Some(worktree_path)
3309        });
3310
3311        if let Some(working_dir_path) = working_dir_path {
3312            let mut child =
3313                smol::process::Command::new(command)
3314                    .args(arguments.iter().map(|arg| {
3315                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3316                    }))
3317                    .current_dir(&working_dir_path)
3318                    .stdin(smol::process::Stdio::piped())
3319                    .stdout(smol::process::Stdio::piped())
3320                    .stderr(smol::process::Stdio::piped())
3321                    .spawn()?;
3322            let stdin = child
3323                .stdin
3324                .as_mut()
3325                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3326            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3327            for chunk in text.chunks() {
3328                stdin.write_all(chunk.as_bytes()).await?;
3329            }
3330            stdin.flush().await?;
3331
3332            let output = child.output().await?;
3333            if !output.status.success() {
3334                return Err(anyhow!(
3335                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3336                    output.status.code(),
3337                    String::from_utf8_lossy(&output.stdout),
3338                    String::from_utf8_lossy(&output.stderr),
3339                ));
3340            }
3341
3342            let stdout = String::from_utf8(output.stdout)?;
3343            Ok(Some(
3344                buffer
3345                    .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3346                    .await,
3347            ))
3348        } else {
3349            Ok(None)
3350        }
3351    }
3352
3353    pub fn definition<T: ToPointUtf16>(
3354        &self,
3355        buffer: &ModelHandle<Buffer>,
3356        position: T,
3357        cx: &mut ModelContext<Self>,
3358    ) -> Task<Result<Vec<LocationLink>>> {
3359        let position = position.to_point_utf16(buffer.read(cx));
3360        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3361    }
3362
3363    pub fn type_definition<T: ToPointUtf16>(
3364        &self,
3365        buffer: &ModelHandle<Buffer>,
3366        position: T,
3367        cx: &mut ModelContext<Self>,
3368    ) -> Task<Result<Vec<LocationLink>>> {
3369        let position = position.to_point_utf16(buffer.read(cx));
3370        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3371    }
3372
3373    pub fn references<T: ToPointUtf16>(
3374        &self,
3375        buffer: &ModelHandle<Buffer>,
3376        position: T,
3377        cx: &mut ModelContext<Self>,
3378    ) -> Task<Result<Vec<Location>>> {
3379        let position = position.to_point_utf16(buffer.read(cx));
3380        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3381    }
3382
3383    pub fn document_highlights<T: ToPointUtf16>(
3384        &self,
3385        buffer: &ModelHandle<Buffer>,
3386        position: T,
3387        cx: &mut ModelContext<Self>,
3388    ) -> Task<Result<Vec<DocumentHighlight>>> {
3389        let position = position.to_point_utf16(buffer.read(cx));
3390        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3391    }
3392
3393    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3394        if self.is_local() {
3395            let mut requests = Vec::new();
3396            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3397                let worktree_id = *worktree_id;
3398                if let Some(worktree) = self
3399                    .worktree_for_id(worktree_id, cx)
3400                    .and_then(|worktree| worktree.read(cx).as_local())
3401                {
3402                    if let Some(LanguageServerState::Running {
3403                        adapter,
3404                        language,
3405                        server,
3406                        ..
3407                    }) = self.language_servers.get(server_id)
3408                    {
3409                        let adapter = adapter.clone();
3410                        let language = language.clone();
3411                        let worktree_abs_path = worktree.abs_path().clone();
3412                        requests.push(
3413                            server
3414                                .request::<lsp::request::WorkspaceSymbol>(
3415                                    lsp::WorkspaceSymbolParams {
3416                                        query: query.to_string(),
3417                                        ..Default::default()
3418                                    },
3419                                )
3420                                .log_err()
3421                                .map(move |response| {
3422                                    (
3423                                        adapter,
3424                                        language,
3425                                        worktree_id,
3426                                        worktree_abs_path,
3427                                        response.unwrap_or_default(),
3428                                    )
3429                                }),
3430                        );
3431                    }
3432                }
3433            }
3434
3435            cx.spawn_weak(|this, cx| async move {
3436                let responses = futures::future::join_all(requests).await;
3437                let this = if let Some(this) = this.upgrade(&cx) {
3438                    this
3439                } else {
3440                    return Ok(Default::default());
3441                };
3442                let symbols = this.read_with(&cx, |this, cx| {
3443                    let mut symbols = Vec::new();
3444                    for (
3445                        adapter,
3446                        adapter_language,
3447                        source_worktree_id,
3448                        worktree_abs_path,
3449                        response,
3450                    ) in responses
3451                    {
3452                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3453                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3454                            let mut worktree_id = source_worktree_id;
3455                            let path;
3456                            if let Some((worktree, rel_path)) =
3457                                this.find_local_worktree(&abs_path, cx)
3458                            {
3459                                worktree_id = worktree.read(cx).id();
3460                                path = rel_path;
3461                            } else {
3462                                path = relativize_path(&worktree_abs_path, &abs_path);
3463                            }
3464
3465                            let project_path = ProjectPath {
3466                                worktree_id,
3467                                path: path.into(),
3468                            };
3469                            let signature = this.symbol_signature(&project_path);
3470                            let adapter_language = adapter_language.clone();
3471                            let language = this
3472                                .languages
3473                                .language_for_file(&project_path.path, None)
3474                                .unwrap_or_else(move |_| adapter_language);
3475                            let language_server_name = adapter.name.clone();
3476                            Some(async move {
3477                                let language = language.await;
3478                                let label = language
3479                                    .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3480                                    .await;
3481
3482                                Symbol {
3483                                    language_server_name,
3484                                    source_worktree_id,
3485                                    path: project_path,
3486                                    label: label.unwrap_or_else(|| {
3487                                        CodeLabel::plain(lsp_symbol.name.clone(), None)
3488                                    }),
3489                                    kind: lsp_symbol.kind,
3490                                    name: lsp_symbol.name,
3491                                    range: range_from_lsp(lsp_symbol.location.range),
3492                                    signature,
3493                                }
3494                            })
3495                        }));
3496                    }
3497                    symbols
3498                });
3499                Ok(futures::future::join_all(symbols).await)
3500            })
3501        } else if let Some(project_id) = self.remote_id() {
3502            let request = self.client.request(proto::GetProjectSymbols {
3503                project_id,
3504                query: query.to_string(),
3505            });
3506            cx.spawn_weak(|this, cx| async move {
3507                let response = request.await?;
3508                let mut symbols = Vec::new();
3509                if let Some(this) = this.upgrade(&cx) {
3510                    let new_symbols = this.read_with(&cx, |this, _| {
3511                        response
3512                            .symbols
3513                            .into_iter()
3514                            .map(|symbol| this.deserialize_symbol(symbol))
3515                            .collect::<Vec<_>>()
3516                    });
3517                    symbols = futures::future::join_all(new_symbols)
3518                        .await
3519                        .into_iter()
3520                        .filter_map(|symbol| symbol.log_err())
3521                        .collect::<Vec<_>>();
3522                }
3523                Ok(symbols)
3524            })
3525        } else {
3526            Task::ready(Ok(Default::default()))
3527        }
3528    }
3529
3530    pub fn open_buffer_for_symbol(
3531        &mut self,
3532        symbol: &Symbol,
3533        cx: &mut ModelContext<Self>,
3534    ) -> Task<Result<ModelHandle<Buffer>>> {
3535        if self.is_local() {
3536            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3537                symbol.source_worktree_id,
3538                symbol.language_server_name.clone(),
3539            )) {
3540                *id
3541            } else {
3542                return Task::ready(Err(anyhow!(
3543                    "language server for worktree and language not found"
3544                )));
3545            };
3546
3547            let worktree_abs_path = if let Some(worktree_abs_path) = self
3548                .worktree_for_id(symbol.path.worktree_id, cx)
3549                .and_then(|worktree| worktree.read(cx).as_local())
3550                .map(|local_worktree| local_worktree.abs_path())
3551            {
3552                worktree_abs_path
3553            } else {
3554                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3555            };
3556            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3557            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3558                uri
3559            } else {
3560                return Task::ready(Err(anyhow!("invalid symbol path")));
3561            };
3562
3563            self.open_local_buffer_via_lsp(
3564                symbol_uri,
3565                language_server_id,
3566                symbol.language_server_name.clone(),
3567                cx,
3568            )
3569        } else if let Some(project_id) = self.remote_id() {
3570            let request = self.client.request(proto::OpenBufferForSymbol {
3571                project_id,
3572                symbol: Some(serialize_symbol(symbol)),
3573            });
3574            cx.spawn(|this, mut cx| async move {
3575                let response = request.await?;
3576                this.update(&mut cx, |this, cx| {
3577                    this.wait_for_remote_buffer(response.buffer_id, cx)
3578                })
3579                .await
3580            })
3581        } else {
3582            Task::ready(Err(anyhow!("project does not have a remote id")))
3583        }
3584    }
3585
3586    pub fn hover<T: ToPointUtf16>(
3587        &self,
3588        buffer: &ModelHandle<Buffer>,
3589        position: T,
3590        cx: &mut ModelContext<Self>,
3591    ) -> Task<Result<Option<Hover>>> {
3592        let position = position.to_point_utf16(buffer.read(cx));
3593        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3594    }
3595
3596    pub fn completions<T: ToPointUtf16>(
3597        &self,
3598        buffer: &ModelHandle<Buffer>,
3599        position: T,
3600        cx: &mut ModelContext<Self>,
3601    ) -> Task<Result<Vec<Completion>>> {
3602        let position = position.to_point_utf16(buffer.read(cx));
3603        self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
3604    }
3605
3606    pub fn apply_additional_edits_for_completion(
3607        &self,
3608        buffer_handle: ModelHandle<Buffer>,
3609        completion: Completion,
3610        push_to_history: bool,
3611        cx: &mut ModelContext<Self>,
3612    ) -> Task<Result<Option<Transaction>>> {
3613        let buffer = buffer_handle.read(cx);
3614        let buffer_id = buffer.remote_id();
3615
3616        if self.is_local() {
3617            let lang_server = match self.language_server_for_buffer(buffer, cx) {
3618                Some((_, server)) => server.clone(),
3619                _ => return Task::ready(Ok(Default::default())),
3620            };
3621
3622            cx.spawn(|this, mut cx| async move {
3623                let resolved_completion = lang_server
3624                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3625                    .await?;
3626
3627                if let Some(edits) = resolved_completion.additional_text_edits {
3628                    let edits = this
3629                        .update(&mut cx, |this, cx| {
3630                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
3631                        })
3632                        .await?;
3633
3634                    buffer_handle.update(&mut cx, |buffer, cx| {
3635                        buffer.finalize_last_transaction();
3636                        buffer.start_transaction();
3637
3638                        for (range, text) in edits {
3639                            let primary = &completion.old_range;
3640                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
3641                                && primary.end.cmp(&range.start, buffer).is_ge();
3642                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
3643                                && range.end.cmp(&primary.end, buffer).is_ge();
3644
3645                            //Skip addtional edits which overlap with the primary completion edit
3646                            //https://github.com/zed-industries/zed/pull/1871
3647                            if !start_within && !end_within {
3648                                buffer.edit([(range, text)], None, cx);
3649                            }
3650                        }
3651
3652                        let transaction = if buffer.end_transaction(cx).is_some() {
3653                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3654                            if !push_to_history {
3655                                buffer.forget_transaction(transaction.id);
3656                            }
3657                            Some(transaction)
3658                        } else {
3659                            None
3660                        };
3661                        Ok(transaction)
3662                    })
3663                } else {
3664                    Ok(None)
3665                }
3666            })
3667        } else if let Some(project_id) = self.remote_id() {
3668            let client = self.client.clone();
3669            cx.spawn(|_, mut cx| async move {
3670                let response = client
3671                    .request(proto::ApplyCompletionAdditionalEdits {
3672                        project_id,
3673                        buffer_id,
3674                        completion: Some(language::proto::serialize_completion(&completion)),
3675                    })
3676                    .await?;
3677
3678                if let Some(transaction) = response.transaction {
3679                    let transaction = language::proto::deserialize_transaction(transaction)?;
3680                    buffer_handle
3681                        .update(&mut cx, |buffer, _| {
3682                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3683                        })
3684                        .await?;
3685                    if push_to_history {
3686                        buffer_handle.update(&mut cx, |buffer, _| {
3687                            buffer.push_transaction(transaction.clone(), Instant::now());
3688                        });
3689                    }
3690                    Ok(Some(transaction))
3691                } else {
3692                    Ok(None)
3693                }
3694            })
3695        } else {
3696            Task::ready(Err(anyhow!("project does not have a remote id")))
3697        }
3698    }
3699
3700    pub fn code_actions<T: Clone + ToOffset>(
3701        &self,
3702        buffer_handle: &ModelHandle<Buffer>,
3703        range: Range<T>,
3704        cx: &mut ModelContext<Self>,
3705    ) -> Task<Result<Vec<CodeAction>>> {
3706        let buffer = buffer_handle.read(cx);
3707        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3708        self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
3709    }
3710
3711    pub fn apply_code_action(
3712        &self,
3713        buffer_handle: ModelHandle<Buffer>,
3714        mut action: CodeAction,
3715        push_to_history: bool,
3716        cx: &mut ModelContext<Self>,
3717    ) -> Task<Result<ProjectTransaction>> {
3718        if self.is_local() {
3719            let buffer = buffer_handle.read(cx);
3720            let (lsp_adapter, lang_server) =
3721                if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3722                    (adapter.clone(), server.clone())
3723                } else {
3724                    return Task::ready(Ok(Default::default()));
3725                };
3726            let range = action.range.to_point_utf16(buffer);
3727
3728            cx.spawn(|this, mut cx| async move {
3729                if let Some(lsp_range) = action
3730                    .lsp_action
3731                    .data
3732                    .as_mut()
3733                    .and_then(|d| d.get_mut("codeActionParams"))
3734                    .and_then(|d| d.get_mut("range"))
3735                {
3736                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3737                    action.lsp_action = lang_server
3738                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3739                        .await?;
3740                } else {
3741                    let actions = this
3742                        .update(&mut cx, |this, cx| {
3743                            this.code_actions(&buffer_handle, action.range, cx)
3744                        })
3745                        .await?;
3746                    action.lsp_action = actions
3747                        .into_iter()
3748                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3749                        .ok_or_else(|| anyhow!("code action is outdated"))?
3750                        .lsp_action;
3751                }
3752
3753                if let Some(edit) = action.lsp_action.edit {
3754                    if edit.changes.is_some() || edit.document_changes.is_some() {
3755                        return Self::deserialize_workspace_edit(
3756                            this,
3757                            edit,
3758                            push_to_history,
3759                            lsp_adapter.clone(),
3760                            lang_server.clone(),
3761                            &mut cx,
3762                        )
3763                        .await;
3764                    }
3765                }
3766
3767                if let Some(command) = action.lsp_action.command {
3768                    this.update(&mut cx, |this, _| {
3769                        this.last_workspace_edits_by_language_server
3770                            .remove(&lang_server.server_id());
3771                    });
3772                    lang_server
3773                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3774                            command: command.command,
3775                            arguments: command.arguments.unwrap_or_default(),
3776                            ..Default::default()
3777                        })
3778                        .await?;
3779                    return Ok(this.update(&mut cx, |this, _| {
3780                        this.last_workspace_edits_by_language_server
3781                            .remove(&lang_server.server_id())
3782                            .unwrap_or_default()
3783                    }));
3784                }
3785
3786                Ok(ProjectTransaction::default())
3787            })
3788        } else if let Some(project_id) = self.remote_id() {
3789            let client = self.client.clone();
3790            let request = proto::ApplyCodeAction {
3791                project_id,
3792                buffer_id: buffer_handle.read(cx).remote_id(),
3793                action: Some(language::proto::serialize_code_action(&action)),
3794            };
3795            cx.spawn(|this, mut cx| async move {
3796                let response = client
3797                    .request(request)
3798                    .await?
3799                    .transaction
3800                    .ok_or_else(|| anyhow!("missing transaction"))?;
3801                this.update(&mut cx, |this, cx| {
3802                    this.deserialize_project_transaction(response, push_to_history, cx)
3803                })
3804                .await
3805            })
3806        } else {
3807            Task::ready(Err(anyhow!("project does not have a remote id")))
3808        }
3809    }
3810
3811    async fn deserialize_workspace_edit(
3812        this: ModelHandle<Self>,
3813        edit: lsp::WorkspaceEdit,
3814        push_to_history: bool,
3815        lsp_adapter: Arc<CachedLspAdapter>,
3816        language_server: Arc<LanguageServer>,
3817        cx: &mut AsyncAppContext,
3818    ) -> Result<ProjectTransaction> {
3819        let fs = this.read_with(cx, |this, _| this.fs.clone());
3820        let mut operations = Vec::new();
3821        if let Some(document_changes) = edit.document_changes {
3822            match document_changes {
3823                lsp::DocumentChanges::Edits(edits) => {
3824                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3825                }
3826                lsp::DocumentChanges::Operations(ops) => operations = ops,
3827            }
3828        } else if let Some(changes) = edit.changes {
3829            operations.extend(changes.into_iter().map(|(uri, edits)| {
3830                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3831                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3832                        uri,
3833                        version: None,
3834                    },
3835                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3836                })
3837            }));
3838        }
3839
3840        let mut project_transaction = ProjectTransaction::default();
3841        for operation in operations {
3842            match operation {
3843                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3844                    let abs_path = op
3845                        .uri
3846                        .to_file_path()
3847                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3848
3849                    if let Some(parent_path) = abs_path.parent() {
3850                        fs.create_dir(parent_path).await?;
3851                    }
3852                    if abs_path.ends_with("/") {
3853                        fs.create_dir(&abs_path).await?;
3854                    } else {
3855                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3856                            .await?;
3857                    }
3858                }
3859                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3860                    let source_abs_path = op
3861                        .old_uri
3862                        .to_file_path()
3863                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3864                    let target_abs_path = op
3865                        .new_uri
3866                        .to_file_path()
3867                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3868                    fs.rename(
3869                        &source_abs_path,
3870                        &target_abs_path,
3871                        op.options.map(Into::into).unwrap_or_default(),
3872                    )
3873                    .await?;
3874                }
3875                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3876                    let abs_path = op
3877                        .uri
3878                        .to_file_path()
3879                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3880                    let options = op.options.map(Into::into).unwrap_or_default();
3881                    if abs_path.ends_with("/") {
3882                        fs.remove_dir(&abs_path, options).await?;
3883                    } else {
3884                        fs.remove_file(&abs_path, options).await?;
3885                    }
3886                }
3887                lsp::DocumentChangeOperation::Edit(op) => {
3888                    let buffer_to_edit = this
3889                        .update(cx, |this, cx| {
3890                            this.open_local_buffer_via_lsp(
3891                                op.text_document.uri,
3892                                language_server.server_id(),
3893                                lsp_adapter.name.clone(),
3894                                cx,
3895                            )
3896                        })
3897                        .await?;
3898
3899                    let edits = this
3900                        .update(cx, |this, cx| {
3901                            let edits = op.edits.into_iter().map(|edit| match edit {
3902                                lsp::OneOf::Left(edit) => edit,
3903                                lsp::OneOf::Right(edit) => edit.text_edit,
3904                            });
3905                            this.edits_from_lsp(
3906                                &buffer_to_edit,
3907                                edits,
3908                                op.text_document.version,
3909                                cx,
3910                            )
3911                        })
3912                        .await?;
3913
3914                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3915                        buffer.finalize_last_transaction();
3916                        buffer.start_transaction();
3917                        for (range, text) in edits {
3918                            buffer.edit([(range, text)], None, cx);
3919                        }
3920                        let transaction = if buffer.end_transaction(cx).is_some() {
3921                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3922                            if !push_to_history {
3923                                buffer.forget_transaction(transaction.id);
3924                            }
3925                            Some(transaction)
3926                        } else {
3927                            None
3928                        };
3929
3930                        transaction
3931                    });
3932                    if let Some(transaction) = transaction {
3933                        project_transaction.0.insert(buffer_to_edit, transaction);
3934                    }
3935                }
3936            }
3937        }
3938
3939        Ok(project_transaction)
3940    }
3941
3942    pub fn prepare_rename<T: ToPointUtf16>(
3943        &self,
3944        buffer: ModelHandle<Buffer>,
3945        position: T,
3946        cx: &mut ModelContext<Self>,
3947    ) -> Task<Result<Option<Range<Anchor>>>> {
3948        let position = position.to_point_utf16(buffer.read(cx));
3949        self.request_lsp(buffer, PrepareRename { position }, cx)
3950    }
3951
3952    pub fn perform_rename<T: ToPointUtf16>(
3953        &self,
3954        buffer: ModelHandle<Buffer>,
3955        position: T,
3956        new_name: String,
3957        push_to_history: bool,
3958        cx: &mut ModelContext<Self>,
3959    ) -> Task<Result<ProjectTransaction>> {
3960        let position = position.to_point_utf16(buffer.read(cx));
3961        self.request_lsp(
3962            buffer,
3963            PerformRename {
3964                position,
3965                new_name,
3966                push_to_history,
3967            },
3968            cx,
3969        )
3970    }
3971
3972    #[allow(clippy::type_complexity)]
3973    pub fn search(
3974        &self,
3975        query: SearchQuery,
3976        cx: &mut ModelContext<Self>,
3977    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
3978        if self.is_local() {
3979            let snapshots = self
3980                .visible_worktrees(cx)
3981                .filter_map(|tree| {
3982                    let tree = tree.read(cx).as_local()?;
3983                    Some(tree.snapshot())
3984                })
3985                .collect::<Vec<_>>();
3986
3987            let background = cx.background().clone();
3988            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
3989            if path_count == 0 {
3990                return Task::ready(Ok(Default::default()));
3991            }
3992            let workers = background.num_cpus().min(path_count);
3993            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
3994            cx.background()
3995                .spawn({
3996                    let fs = self.fs.clone();
3997                    let background = cx.background().clone();
3998                    let query = query.clone();
3999                    async move {
4000                        let fs = &fs;
4001                        let query = &query;
4002                        let matching_paths_tx = &matching_paths_tx;
4003                        let paths_per_worker = (path_count + workers - 1) / workers;
4004                        let snapshots = &snapshots;
4005                        background
4006                            .scoped(|scope| {
4007                                for worker_ix in 0..workers {
4008                                    let worker_start_ix = worker_ix * paths_per_worker;
4009                                    let worker_end_ix = worker_start_ix + paths_per_worker;
4010                                    scope.spawn(async move {
4011                                        let mut snapshot_start_ix = 0;
4012                                        let mut abs_path = PathBuf::new();
4013                                        for snapshot in snapshots {
4014                                            let snapshot_end_ix =
4015                                                snapshot_start_ix + snapshot.visible_file_count();
4016                                            if worker_end_ix <= snapshot_start_ix {
4017                                                break;
4018                                            } else if worker_start_ix > snapshot_end_ix {
4019                                                snapshot_start_ix = snapshot_end_ix;
4020                                                continue;
4021                                            } else {
4022                                                let start_in_snapshot = worker_start_ix
4023                                                    .saturating_sub(snapshot_start_ix);
4024                                                let end_in_snapshot =
4025                                                    cmp::min(worker_end_ix, snapshot_end_ix)
4026                                                        - snapshot_start_ix;
4027
4028                                                for entry in snapshot
4029                                                    .files(false, start_in_snapshot)
4030                                                    .take(end_in_snapshot - start_in_snapshot)
4031                                                {
4032                                                    if matching_paths_tx.is_closed() {
4033                                                        break;
4034                                                    }
4035
4036                                                    abs_path.clear();
4037                                                    abs_path.push(&snapshot.abs_path());
4038                                                    abs_path.push(&entry.path);
4039                                                    let matches = if let Some(file) =
4040                                                        fs.open_sync(&abs_path).await.log_err()
4041                                                    {
4042                                                        query.detect(file).unwrap_or(false)
4043                                                    } else {
4044                                                        false
4045                                                    };
4046
4047                                                    if matches {
4048                                                        let project_path =
4049                                                            (snapshot.id(), entry.path.clone());
4050                                                        if matching_paths_tx
4051                                                            .send(project_path)
4052                                                            .await
4053                                                            .is_err()
4054                                                        {
4055                                                            break;
4056                                                        }
4057                                                    }
4058                                                }
4059
4060                                                snapshot_start_ix = snapshot_end_ix;
4061                                            }
4062                                        }
4063                                    });
4064                                }
4065                            })
4066                            .await;
4067                    }
4068                })
4069                .detach();
4070
4071            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4072            let open_buffers = self
4073                .opened_buffers
4074                .values()
4075                .filter_map(|b| b.upgrade(cx))
4076                .collect::<HashSet<_>>();
4077            cx.spawn(|this, cx| async move {
4078                for buffer in &open_buffers {
4079                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4080                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4081                }
4082
4083                let open_buffers = Rc::new(RefCell::new(open_buffers));
4084                while let Some(project_path) = matching_paths_rx.next().await {
4085                    if buffers_tx.is_closed() {
4086                        break;
4087                    }
4088
4089                    let this = this.clone();
4090                    let open_buffers = open_buffers.clone();
4091                    let buffers_tx = buffers_tx.clone();
4092                    cx.spawn(|mut cx| async move {
4093                        if let Some(buffer) = this
4094                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4095                            .await
4096                            .log_err()
4097                        {
4098                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4099                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4100                                buffers_tx.send((buffer, snapshot)).await?;
4101                            }
4102                        }
4103
4104                        Ok::<_, anyhow::Error>(())
4105                    })
4106                    .detach();
4107                }
4108
4109                Ok::<_, anyhow::Error>(())
4110            })
4111            .detach_and_log_err(cx);
4112
4113            let background = cx.background().clone();
4114            cx.background().spawn(async move {
4115                let query = &query;
4116                let mut matched_buffers = Vec::new();
4117                for _ in 0..workers {
4118                    matched_buffers.push(HashMap::default());
4119                }
4120                background
4121                    .scoped(|scope| {
4122                        for worker_matched_buffers in matched_buffers.iter_mut() {
4123                            let mut buffers_rx = buffers_rx.clone();
4124                            scope.spawn(async move {
4125                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4126                                    let buffer_matches = query
4127                                        .search(snapshot.as_rope())
4128                                        .await
4129                                        .iter()
4130                                        .map(|range| {
4131                                            snapshot.anchor_before(range.start)
4132                                                ..snapshot.anchor_after(range.end)
4133                                        })
4134                                        .collect::<Vec<_>>();
4135                                    if !buffer_matches.is_empty() {
4136                                        worker_matched_buffers
4137                                            .insert(buffer.clone(), buffer_matches);
4138                                    }
4139                                }
4140                            });
4141                        }
4142                    })
4143                    .await;
4144                Ok(matched_buffers.into_iter().flatten().collect())
4145            })
4146        } else if let Some(project_id) = self.remote_id() {
4147            let request = self.client.request(query.to_proto(project_id));
4148            cx.spawn(|this, mut cx| async move {
4149                let response = request.await?;
4150                let mut result = HashMap::default();
4151                for location in response.locations {
4152                    let target_buffer = this
4153                        .update(&mut cx, |this, cx| {
4154                            this.wait_for_remote_buffer(location.buffer_id, cx)
4155                        })
4156                        .await?;
4157                    let start = location
4158                        .start
4159                        .and_then(deserialize_anchor)
4160                        .ok_or_else(|| anyhow!("missing target start"))?;
4161                    let end = location
4162                        .end
4163                        .and_then(deserialize_anchor)
4164                        .ok_or_else(|| anyhow!("missing target end"))?;
4165                    result
4166                        .entry(target_buffer)
4167                        .or_insert(Vec::new())
4168                        .push(start..end)
4169                }
4170                Ok(result)
4171            })
4172        } else {
4173            Task::ready(Ok(Default::default()))
4174        }
4175    }
4176
4177    fn request_lsp<R: LspCommand>(
4178        &self,
4179        buffer_handle: ModelHandle<Buffer>,
4180        request: R,
4181        cx: &mut ModelContext<Self>,
4182    ) -> Task<Result<R::Response>>
4183    where
4184        <R::LspRequest as lsp::request::Request>::Result: Send,
4185    {
4186        let buffer = buffer_handle.read(cx);
4187        if self.is_local() {
4188            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4189            if let Some((file, language_server)) = file.zip(
4190                self.language_server_for_buffer(buffer, cx)
4191                    .map(|(_, server)| server.clone()),
4192            ) {
4193                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
4194                return cx.spawn(|this, cx| async move {
4195                    if !request.check_capabilities(language_server.capabilities()) {
4196                        return Ok(Default::default());
4197                    }
4198
4199                    let response = language_server
4200                        .request::<R::LspRequest>(lsp_params)
4201                        .await
4202                        .context("lsp request failed")?;
4203                    request
4204                        .response_from_lsp(response, this, buffer_handle, cx)
4205                        .await
4206                });
4207            }
4208        } else if let Some(project_id) = self.remote_id() {
4209            let rpc = self.client.clone();
4210            let message = request.to_proto(project_id, buffer);
4211            return cx.spawn_weak(|this, cx| async move {
4212                // Ensure the project is still alive by the time the task
4213                // is scheduled.
4214                this.upgrade(&cx)
4215                    .ok_or_else(|| anyhow!("project dropped"))?;
4216
4217                let response = rpc.request(message).await?;
4218
4219                let this = this
4220                    .upgrade(&cx)
4221                    .ok_or_else(|| anyhow!("project dropped"))?;
4222                if this.read_with(&cx, |this, _| this.is_read_only()) {
4223                    Err(anyhow!("disconnected before completing request"))
4224                } else {
4225                    request
4226                        .response_from_proto(response, this, buffer_handle, cx)
4227                        .await
4228                }
4229            });
4230        }
4231        Task::ready(Ok(Default::default()))
4232    }
4233
4234    pub fn find_or_create_local_worktree(
4235        &mut self,
4236        abs_path: impl AsRef<Path>,
4237        visible: bool,
4238        cx: &mut ModelContext<Self>,
4239    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4240        let abs_path = abs_path.as_ref();
4241        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4242            Task::ready(Ok((tree, relative_path)))
4243        } else {
4244            let worktree = self.create_local_worktree(abs_path, visible, cx);
4245            cx.foreground()
4246                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4247        }
4248    }
4249
4250    pub fn find_local_worktree(
4251        &self,
4252        abs_path: &Path,
4253        cx: &AppContext,
4254    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4255        for tree in &self.worktrees {
4256            if let Some(tree) = tree.upgrade(cx) {
4257                if let Some(relative_path) = tree
4258                    .read(cx)
4259                    .as_local()
4260                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4261                {
4262                    return Some((tree.clone(), relative_path.into()));
4263                }
4264            }
4265        }
4266        None
4267    }
4268
4269    pub fn is_shared(&self) -> bool {
4270        match &self.client_state {
4271            Some(ProjectClientState::Local { .. }) => true,
4272            _ => false,
4273        }
4274    }
4275
4276    fn create_local_worktree(
4277        &mut self,
4278        abs_path: impl AsRef<Path>,
4279        visible: bool,
4280        cx: &mut ModelContext<Self>,
4281    ) -> Task<Result<ModelHandle<Worktree>>> {
4282        let fs = self.fs.clone();
4283        let client = self.client.clone();
4284        let next_entry_id = self.next_entry_id.clone();
4285        let path: Arc<Path> = abs_path.as_ref().into();
4286        let task = self
4287            .loading_local_worktrees
4288            .entry(path.clone())
4289            .or_insert_with(|| {
4290                cx.spawn(|project, mut cx| {
4291                    async move {
4292                        let worktree = Worktree::local(
4293                            client.clone(),
4294                            path.clone(),
4295                            visible,
4296                            fs,
4297                            next_entry_id,
4298                            &mut cx,
4299                        )
4300                        .await;
4301
4302                        project.update(&mut cx, |project, _| {
4303                            project.loading_local_worktrees.remove(&path);
4304                        });
4305
4306                        let worktree = worktree?;
4307                        project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
4308                        Ok(worktree)
4309                    }
4310                    .map_err(Arc::new)
4311                })
4312                .shared()
4313            })
4314            .clone();
4315        cx.foreground().spawn(async move {
4316            match task.await {
4317                Ok(worktree) => Ok(worktree),
4318                Err(err) => Err(anyhow!("{}", err)),
4319            }
4320        })
4321    }
4322
4323    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4324        self.worktrees.retain(|worktree| {
4325            if let Some(worktree) = worktree.upgrade(cx) {
4326                let id = worktree.read(cx).id();
4327                if id == id_to_remove {
4328                    cx.emit(Event::WorktreeRemoved(id));
4329                    false
4330                } else {
4331                    true
4332                }
4333            } else {
4334                false
4335            }
4336        });
4337        self.metadata_changed(cx);
4338    }
4339
4340    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4341        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4342        if worktree.read(cx).is_local() {
4343            cx.subscribe(worktree, |this, worktree, event, cx| match event {
4344                worktree::Event::UpdatedEntries(changes) => {
4345                    this.update_local_worktree_buffers(&worktree, cx);
4346                    this.update_local_worktree_language_servers(&worktree, changes, cx);
4347                }
4348                worktree::Event::UpdatedGitRepositories(updated_repos) => {
4349                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4350                }
4351            })
4352            .detach();
4353        }
4354
4355        let push_strong_handle = {
4356            let worktree = worktree.read(cx);
4357            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4358        };
4359        if push_strong_handle {
4360            self.worktrees
4361                .push(WorktreeHandle::Strong(worktree.clone()));
4362        } else {
4363            self.worktrees
4364                .push(WorktreeHandle::Weak(worktree.downgrade()));
4365        }
4366
4367        cx.observe_release(worktree, |this, worktree, cx| {
4368            let _ = this.remove_worktree(worktree.id(), cx);
4369        })
4370        .detach();
4371
4372        cx.emit(Event::WorktreeAdded);
4373        self.metadata_changed(cx);
4374    }
4375
4376    fn update_local_worktree_buffers(
4377        &mut self,
4378        worktree_handle: &ModelHandle<Worktree>,
4379        cx: &mut ModelContext<Self>,
4380    ) {
4381        let snapshot = worktree_handle.read(cx).snapshot();
4382        let mut buffers_to_delete = Vec::new();
4383        let mut renamed_buffers = Vec::new();
4384        for (buffer_id, buffer) in &self.opened_buffers {
4385            if let Some(buffer) = buffer.upgrade(cx) {
4386                buffer.update(cx, |buffer, cx| {
4387                    if let Some(old_file) = File::from_dyn(buffer.file()) {
4388                        if old_file.worktree != *worktree_handle {
4389                            return;
4390                        }
4391
4392                        let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id)
4393                        {
4394                            File {
4395                                is_local: true,
4396                                entry_id: entry.id,
4397                                mtime: entry.mtime,
4398                                path: entry.path.clone(),
4399                                worktree: worktree_handle.clone(),
4400                                is_deleted: false,
4401                            }
4402                        } else if let Some(entry) =
4403                            snapshot.entry_for_path(old_file.path().as_ref())
4404                        {
4405                            File {
4406                                is_local: true,
4407                                entry_id: entry.id,
4408                                mtime: entry.mtime,
4409                                path: entry.path.clone(),
4410                                worktree: worktree_handle.clone(),
4411                                is_deleted: false,
4412                            }
4413                        } else {
4414                            File {
4415                                is_local: true,
4416                                entry_id: old_file.entry_id,
4417                                path: old_file.path().clone(),
4418                                mtime: old_file.mtime(),
4419                                worktree: worktree_handle.clone(),
4420                                is_deleted: true,
4421                            }
4422                        };
4423
4424                        let old_path = old_file.abs_path(cx);
4425                        if new_file.abs_path(cx) != old_path {
4426                            renamed_buffers.push((cx.handle(), old_path));
4427                        }
4428
4429                        if new_file != *old_file {
4430                            if let Some(project_id) = self.remote_id() {
4431                                self.client
4432                                    .send(proto::UpdateBufferFile {
4433                                        project_id,
4434                                        buffer_id: *buffer_id as u64,
4435                                        file: Some(new_file.to_proto()),
4436                                    })
4437                                    .log_err();
4438                            }
4439
4440                            buffer.file_updated(Arc::new(new_file), cx).detach();
4441                        }
4442                    }
4443                });
4444            } else {
4445                buffers_to_delete.push(*buffer_id);
4446            }
4447        }
4448
4449        for buffer_id in buffers_to_delete {
4450            self.opened_buffers.remove(&buffer_id);
4451        }
4452
4453        for (buffer, old_path) in renamed_buffers {
4454            self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4455            self.detect_language_for_buffer(&buffer, cx);
4456            self.register_buffer_with_language_server(&buffer, cx);
4457        }
4458    }
4459
4460    fn update_local_worktree_language_servers(
4461        &mut self,
4462        worktree_handle: &ModelHandle<Worktree>,
4463        changes: &HashMap<Arc<Path>, PathChange>,
4464        cx: &mut ModelContext<Self>,
4465    ) {
4466        let worktree_id = worktree_handle.read(cx).id();
4467        let abs_path = worktree_handle.read(cx).abs_path();
4468        for ((server_worktree_id, _), server_id) in &self.language_server_ids {
4469            if *server_worktree_id == worktree_id {
4470                if let Some(server) = self.language_servers.get(server_id) {
4471                    if let LanguageServerState::Running {
4472                        server,
4473                        watched_paths,
4474                        ..
4475                    } = server
4476                    {
4477                        let params = lsp::DidChangeWatchedFilesParams {
4478                            changes: changes
4479                                .iter()
4480                                .filter_map(|(path, change)| {
4481                                    let path = abs_path.join(path);
4482                                    if watched_paths.matches(&path) {
4483                                        Some(lsp::FileEvent {
4484                                            uri: lsp::Url::from_file_path(path).unwrap(),
4485                                            typ: match change {
4486                                                PathChange::Added => lsp::FileChangeType::CREATED,
4487                                                PathChange::Removed => lsp::FileChangeType::DELETED,
4488                                                PathChange::Updated
4489                                                | PathChange::AddedOrUpdated => {
4490                                                    lsp::FileChangeType::CHANGED
4491                                                }
4492                                            },
4493                                        })
4494                                    } else {
4495                                        None
4496                                    }
4497                                })
4498                                .collect(),
4499                        };
4500
4501                        if !params.changes.is_empty() {
4502                            server
4503                                .notify::<lsp::notification::DidChangeWatchedFiles>(params)
4504                                .log_err();
4505                        }
4506                    }
4507                }
4508            }
4509        }
4510    }
4511
4512    fn update_local_worktree_buffers_git_repos(
4513        &mut self,
4514        worktree: ModelHandle<Worktree>,
4515        repos: &[GitRepositoryEntry],
4516        cx: &mut ModelContext<Self>,
4517    ) {
4518        for (_, buffer) in &self.opened_buffers {
4519            if let Some(buffer) = buffer.upgrade(cx) {
4520                let file = match File::from_dyn(buffer.read(cx).file()) {
4521                    Some(file) => file,
4522                    None => continue,
4523                };
4524                if file.worktree != worktree {
4525                    continue;
4526                }
4527
4528                let path = file.path().clone();
4529
4530                let repo = match repos.iter().find(|repo| repo.manages(&path)) {
4531                    Some(repo) => repo.clone(),
4532                    None => return,
4533                };
4534
4535                let relative_repo = match path.strip_prefix(repo.content_path) {
4536                    Ok(relative_repo) => relative_repo.to_owned(),
4537                    Err(_) => return,
4538                };
4539
4540                let remote_id = self.remote_id();
4541                let client = self.client.clone();
4542
4543                cx.spawn(|_, mut cx| async move {
4544                    let diff_base = cx
4545                        .background()
4546                        .spawn(async move { repo.repo.lock().load_index_text(&relative_repo) })
4547                        .await;
4548
4549                    let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4550                        buffer.set_diff_base(diff_base.clone(), cx);
4551                        buffer.remote_id()
4552                    });
4553
4554                    if let Some(project_id) = remote_id {
4555                        client
4556                            .send(proto::UpdateDiffBase {
4557                                project_id,
4558                                buffer_id: buffer_id as u64,
4559                                diff_base,
4560                            })
4561                            .log_err();
4562                    }
4563                })
4564                .detach();
4565            }
4566        }
4567    }
4568
4569    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4570        let new_active_entry = entry.and_then(|project_path| {
4571            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4572            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4573            Some(entry.id)
4574        });
4575        if new_active_entry != self.active_entry {
4576            self.active_entry = new_active_entry;
4577            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4578        }
4579    }
4580
4581    pub fn language_servers_running_disk_based_diagnostics(
4582        &self,
4583    ) -> impl Iterator<Item = usize> + '_ {
4584        self.language_server_statuses
4585            .iter()
4586            .filter_map(|(id, status)| {
4587                if status.has_pending_diagnostic_updates {
4588                    Some(*id)
4589                } else {
4590                    None
4591                }
4592            })
4593    }
4594
4595    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4596        let mut summary = DiagnosticSummary::default();
4597        for (_, path_summary) in self.diagnostic_summaries(cx) {
4598            summary.error_count += path_summary.error_count;
4599            summary.warning_count += path_summary.warning_count;
4600        }
4601        summary
4602    }
4603
4604    pub fn diagnostic_summaries<'a>(
4605        &'a self,
4606        cx: &'a AppContext,
4607    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4608        self.visible_worktrees(cx).flat_map(move |worktree| {
4609            let worktree = worktree.read(cx);
4610            let worktree_id = worktree.id();
4611            worktree
4612                .diagnostic_summaries()
4613                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4614        })
4615    }
4616
4617    pub fn disk_based_diagnostics_started(
4618        &mut self,
4619        language_server_id: usize,
4620        cx: &mut ModelContext<Self>,
4621    ) {
4622        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4623    }
4624
4625    pub fn disk_based_diagnostics_finished(
4626        &mut self,
4627        language_server_id: usize,
4628        cx: &mut ModelContext<Self>,
4629    ) {
4630        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4631    }
4632
4633    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4634        self.active_entry
4635    }
4636
4637    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4638        self.worktree_for_id(path.worktree_id, cx)?
4639            .read(cx)
4640            .entry_for_path(&path.path)
4641            .cloned()
4642    }
4643
4644    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4645        let worktree = self.worktree_for_entry(entry_id, cx)?;
4646        let worktree = worktree.read(cx);
4647        let worktree_id = worktree.id();
4648        let path = worktree.entry_for_id(entry_id)?.path.clone();
4649        Some(ProjectPath { worktree_id, path })
4650    }
4651
4652    // RPC message handlers
4653
4654    async fn handle_unshare_project(
4655        this: ModelHandle<Self>,
4656        _: TypedEnvelope<proto::UnshareProject>,
4657        _: Arc<Client>,
4658        mut cx: AsyncAppContext,
4659    ) -> Result<()> {
4660        this.update(&mut cx, |this, cx| {
4661            if this.is_local() {
4662                this.unshare(cx)?;
4663            } else {
4664                this.disconnected_from_host(cx);
4665            }
4666            Ok(())
4667        })
4668    }
4669
4670    async fn handle_add_collaborator(
4671        this: ModelHandle<Self>,
4672        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4673        _: Arc<Client>,
4674        mut cx: AsyncAppContext,
4675    ) -> Result<()> {
4676        let collaborator = envelope
4677            .payload
4678            .collaborator
4679            .take()
4680            .ok_or_else(|| anyhow!("empty collaborator"))?;
4681
4682        let collaborator = Collaborator::from_proto(collaborator)?;
4683        this.update(&mut cx, |this, cx| {
4684            this.shared_buffers.remove(&collaborator.peer_id);
4685            this.collaborators
4686                .insert(collaborator.peer_id, collaborator);
4687            cx.notify();
4688        });
4689
4690        Ok(())
4691    }
4692
4693    async fn handle_update_project_collaborator(
4694        this: ModelHandle<Self>,
4695        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4696        _: Arc<Client>,
4697        mut cx: AsyncAppContext,
4698    ) -> Result<()> {
4699        let old_peer_id = envelope
4700            .payload
4701            .old_peer_id
4702            .ok_or_else(|| anyhow!("missing old peer id"))?;
4703        let new_peer_id = envelope
4704            .payload
4705            .new_peer_id
4706            .ok_or_else(|| anyhow!("missing new peer id"))?;
4707        this.update(&mut cx, |this, cx| {
4708            let collaborator = this
4709                .collaborators
4710                .remove(&old_peer_id)
4711                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4712            let is_host = collaborator.replica_id == 0;
4713            this.collaborators.insert(new_peer_id, collaborator);
4714
4715            let buffers = this.shared_buffers.remove(&old_peer_id);
4716            log::info!(
4717                "peer {} became {}. moving buffers {:?}",
4718                old_peer_id,
4719                new_peer_id,
4720                &buffers
4721            );
4722            if let Some(buffers) = buffers {
4723                this.shared_buffers.insert(new_peer_id, buffers);
4724            }
4725
4726            if is_host {
4727                this.opened_buffers
4728                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
4729                this.buffer_changes_tx
4730                    .unbounded_send(BufferMessage::Resync)
4731                    .unwrap();
4732            }
4733
4734            cx.emit(Event::CollaboratorUpdated {
4735                old_peer_id,
4736                new_peer_id,
4737            });
4738            cx.notify();
4739            Ok(())
4740        })
4741    }
4742
4743    async fn handle_remove_collaborator(
4744        this: ModelHandle<Self>,
4745        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4746        _: Arc<Client>,
4747        mut cx: AsyncAppContext,
4748    ) -> Result<()> {
4749        this.update(&mut cx, |this, cx| {
4750            let peer_id = envelope
4751                .payload
4752                .peer_id
4753                .ok_or_else(|| anyhow!("invalid peer id"))?;
4754            let replica_id = this
4755                .collaborators
4756                .remove(&peer_id)
4757                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4758                .replica_id;
4759            for buffer in this.opened_buffers.values() {
4760                if let Some(buffer) = buffer.upgrade(cx) {
4761                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4762                }
4763            }
4764            this.shared_buffers.remove(&peer_id);
4765
4766            cx.emit(Event::CollaboratorLeft(peer_id));
4767            cx.notify();
4768            Ok(())
4769        })
4770    }
4771
4772    async fn handle_update_project(
4773        this: ModelHandle<Self>,
4774        envelope: TypedEnvelope<proto::UpdateProject>,
4775        _: Arc<Client>,
4776        mut cx: AsyncAppContext,
4777    ) -> Result<()> {
4778        this.update(&mut cx, |this, cx| {
4779            // Don't handle messages that were sent before the response to us joining the project
4780            if envelope.message_id > this.join_project_response_message_id {
4781                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4782            }
4783            Ok(())
4784        })
4785    }
4786
4787    async fn handle_update_worktree(
4788        this: ModelHandle<Self>,
4789        envelope: TypedEnvelope<proto::UpdateWorktree>,
4790        _: Arc<Client>,
4791        mut cx: AsyncAppContext,
4792    ) -> Result<()> {
4793        this.update(&mut cx, |this, cx| {
4794            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4795            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4796                worktree.update(cx, |worktree, _| {
4797                    let worktree = worktree.as_remote_mut().unwrap();
4798                    worktree.update_from_remote(envelope.payload);
4799                });
4800            }
4801            Ok(())
4802        })
4803    }
4804
4805    async fn handle_create_project_entry(
4806        this: ModelHandle<Self>,
4807        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4808        _: Arc<Client>,
4809        mut cx: AsyncAppContext,
4810    ) -> Result<proto::ProjectEntryResponse> {
4811        let worktree = this.update(&mut cx, |this, cx| {
4812            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4813            this.worktree_for_id(worktree_id, cx)
4814                .ok_or_else(|| anyhow!("worktree not found"))
4815        })?;
4816        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4817        let entry = worktree
4818            .update(&mut cx, |worktree, cx| {
4819                let worktree = worktree.as_local_mut().unwrap();
4820                let path = PathBuf::from(envelope.payload.path);
4821                worktree.create_entry(path, envelope.payload.is_directory, cx)
4822            })
4823            .await?;
4824        Ok(proto::ProjectEntryResponse {
4825            entry: Some((&entry).into()),
4826            worktree_scan_id: worktree_scan_id as u64,
4827        })
4828    }
4829
4830    async fn handle_rename_project_entry(
4831        this: ModelHandle<Self>,
4832        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4833        _: Arc<Client>,
4834        mut cx: AsyncAppContext,
4835    ) -> Result<proto::ProjectEntryResponse> {
4836        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4837        let worktree = this.read_with(&cx, |this, cx| {
4838            this.worktree_for_entry(entry_id, cx)
4839                .ok_or_else(|| anyhow!("worktree not found"))
4840        })?;
4841        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4842        let entry = worktree
4843            .update(&mut cx, |worktree, cx| {
4844                let new_path = PathBuf::from(envelope.payload.new_path);
4845                worktree
4846                    .as_local_mut()
4847                    .unwrap()
4848                    .rename_entry(entry_id, new_path, cx)
4849                    .ok_or_else(|| anyhow!("invalid entry"))
4850            })?
4851            .await?;
4852        Ok(proto::ProjectEntryResponse {
4853            entry: Some((&entry).into()),
4854            worktree_scan_id: worktree_scan_id as u64,
4855        })
4856    }
4857
4858    async fn handle_copy_project_entry(
4859        this: ModelHandle<Self>,
4860        envelope: TypedEnvelope<proto::CopyProjectEntry>,
4861        _: Arc<Client>,
4862        mut cx: AsyncAppContext,
4863    ) -> Result<proto::ProjectEntryResponse> {
4864        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4865        let worktree = this.read_with(&cx, |this, cx| {
4866            this.worktree_for_entry(entry_id, cx)
4867                .ok_or_else(|| anyhow!("worktree not found"))
4868        })?;
4869        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4870        let entry = worktree
4871            .update(&mut cx, |worktree, cx| {
4872                let new_path = PathBuf::from(envelope.payload.new_path);
4873                worktree
4874                    .as_local_mut()
4875                    .unwrap()
4876                    .copy_entry(entry_id, new_path, cx)
4877                    .ok_or_else(|| anyhow!("invalid entry"))
4878            })?
4879            .await?;
4880        Ok(proto::ProjectEntryResponse {
4881            entry: Some((&entry).into()),
4882            worktree_scan_id: worktree_scan_id as u64,
4883        })
4884    }
4885
4886    async fn handle_delete_project_entry(
4887        this: ModelHandle<Self>,
4888        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4889        _: Arc<Client>,
4890        mut cx: AsyncAppContext,
4891    ) -> Result<proto::ProjectEntryResponse> {
4892        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4893        let worktree = this.read_with(&cx, |this, cx| {
4894            this.worktree_for_entry(entry_id, cx)
4895                .ok_or_else(|| anyhow!("worktree not found"))
4896        })?;
4897        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4898        worktree
4899            .update(&mut cx, |worktree, cx| {
4900                worktree
4901                    .as_local_mut()
4902                    .unwrap()
4903                    .delete_entry(entry_id, cx)
4904                    .ok_or_else(|| anyhow!("invalid entry"))
4905            })?
4906            .await?;
4907        Ok(proto::ProjectEntryResponse {
4908            entry: None,
4909            worktree_scan_id: worktree_scan_id as u64,
4910        })
4911    }
4912
4913    async fn handle_update_diagnostic_summary(
4914        this: ModelHandle<Self>,
4915        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4916        _: Arc<Client>,
4917        mut cx: AsyncAppContext,
4918    ) -> Result<()> {
4919        this.update(&mut cx, |this, cx| {
4920            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4921            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4922                if let Some(summary) = envelope.payload.summary {
4923                    let project_path = ProjectPath {
4924                        worktree_id,
4925                        path: Path::new(&summary.path).into(),
4926                    };
4927                    worktree.update(cx, |worktree, _| {
4928                        worktree
4929                            .as_remote_mut()
4930                            .unwrap()
4931                            .update_diagnostic_summary(project_path.path.clone(), &summary);
4932                    });
4933                    cx.emit(Event::DiagnosticsUpdated {
4934                        language_server_id: summary.language_server_id as usize,
4935                        path: project_path,
4936                    });
4937                }
4938            }
4939            Ok(())
4940        })
4941    }
4942
4943    async fn handle_start_language_server(
4944        this: ModelHandle<Self>,
4945        envelope: TypedEnvelope<proto::StartLanguageServer>,
4946        _: Arc<Client>,
4947        mut cx: AsyncAppContext,
4948    ) -> Result<()> {
4949        let server = envelope
4950            .payload
4951            .server
4952            .ok_or_else(|| anyhow!("invalid server"))?;
4953        this.update(&mut cx, |this, cx| {
4954            this.language_server_statuses.insert(
4955                server.id as usize,
4956                LanguageServerStatus {
4957                    name: server.name,
4958                    pending_work: Default::default(),
4959                    has_pending_diagnostic_updates: false,
4960                    progress_tokens: Default::default(),
4961                },
4962            );
4963            cx.notify();
4964        });
4965        Ok(())
4966    }
4967
4968    async fn handle_update_language_server(
4969        this: ModelHandle<Self>,
4970        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
4971        _: Arc<Client>,
4972        mut cx: AsyncAppContext,
4973    ) -> Result<()> {
4974        this.update(&mut cx, |this, cx| {
4975            let language_server_id = envelope.payload.language_server_id as usize;
4976
4977            match envelope
4978                .payload
4979                .variant
4980                .ok_or_else(|| anyhow!("invalid variant"))?
4981            {
4982                proto::update_language_server::Variant::WorkStart(payload) => {
4983                    this.on_lsp_work_start(
4984                        language_server_id,
4985                        payload.token,
4986                        LanguageServerProgress {
4987                            message: payload.message,
4988                            percentage: payload.percentage.map(|p| p as usize),
4989                            last_update_at: Instant::now(),
4990                        },
4991                        cx,
4992                    );
4993                }
4994
4995                proto::update_language_server::Variant::WorkProgress(payload) => {
4996                    this.on_lsp_work_progress(
4997                        language_server_id,
4998                        payload.token,
4999                        LanguageServerProgress {
5000                            message: payload.message,
5001                            percentage: payload.percentage.map(|p| p as usize),
5002                            last_update_at: Instant::now(),
5003                        },
5004                        cx,
5005                    );
5006                }
5007
5008                proto::update_language_server::Variant::WorkEnd(payload) => {
5009                    this.on_lsp_work_end(language_server_id, payload.token, cx);
5010                }
5011
5012                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5013                    this.disk_based_diagnostics_started(language_server_id, cx);
5014                }
5015
5016                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5017                    this.disk_based_diagnostics_finished(language_server_id, cx)
5018                }
5019            }
5020
5021            Ok(())
5022        })
5023    }
5024
5025    async fn handle_update_buffer(
5026        this: ModelHandle<Self>,
5027        envelope: TypedEnvelope<proto::UpdateBuffer>,
5028        _: Arc<Client>,
5029        mut cx: AsyncAppContext,
5030    ) -> Result<proto::Ack> {
5031        this.update(&mut cx, |this, cx| {
5032            let payload = envelope.payload.clone();
5033            let buffer_id = payload.buffer_id;
5034            let ops = payload
5035                .operations
5036                .into_iter()
5037                .map(language::proto::deserialize_operation)
5038                .collect::<Result<Vec<_>, _>>()?;
5039            let is_remote = this.is_remote();
5040            match this.opened_buffers.entry(buffer_id) {
5041                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5042                    OpenBuffer::Strong(buffer) => {
5043                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5044                    }
5045                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5046                    OpenBuffer::Weak(_) => {}
5047                },
5048                hash_map::Entry::Vacant(e) => {
5049                    assert!(
5050                        is_remote,
5051                        "received buffer update from {:?}",
5052                        envelope.original_sender_id
5053                    );
5054                    e.insert(OpenBuffer::Operations(ops));
5055                }
5056            }
5057            Ok(proto::Ack {})
5058        })
5059    }
5060
5061    async fn handle_create_buffer_for_peer(
5062        this: ModelHandle<Self>,
5063        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5064        _: Arc<Client>,
5065        mut cx: AsyncAppContext,
5066    ) -> Result<()> {
5067        this.update(&mut cx, |this, cx| {
5068            match envelope
5069                .payload
5070                .variant
5071                .ok_or_else(|| anyhow!("missing variant"))?
5072            {
5073                proto::create_buffer_for_peer::Variant::State(mut state) => {
5074                    let mut buffer_file = None;
5075                    if let Some(file) = state.file.take() {
5076                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
5077                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5078                            anyhow!("no worktree found for id {}", file.worktree_id)
5079                        })?;
5080                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5081                            as Arc<dyn language::File>);
5082                    }
5083
5084                    let buffer_id = state.id;
5085                    let buffer = cx.add_model(|_| {
5086                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5087                    });
5088                    this.incomplete_remote_buffers
5089                        .insert(buffer_id, Some(buffer));
5090                }
5091                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5092                    let buffer = this
5093                        .incomplete_remote_buffers
5094                        .get(&chunk.buffer_id)
5095                        .cloned()
5096                        .flatten()
5097                        .ok_or_else(|| {
5098                            anyhow!(
5099                                "received chunk for buffer {} without initial state",
5100                                chunk.buffer_id
5101                            )
5102                        })?;
5103                    let operations = chunk
5104                        .operations
5105                        .into_iter()
5106                        .map(language::proto::deserialize_operation)
5107                        .collect::<Result<Vec<_>>>()?;
5108                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5109
5110                    if chunk.is_last {
5111                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5112                        this.register_buffer(&buffer, cx)?;
5113                    }
5114                }
5115            }
5116
5117            Ok(())
5118        })
5119    }
5120
5121    async fn handle_update_diff_base(
5122        this: ModelHandle<Self>,
5123        envelope: TypedEnvelope<proto::UpdateDiffBase>,
5124        _: Arc<Client>,
5125        mut cx: AsyncAppContext,
5126    ) -> Result<()> {
5127        this.update(&mut cx, |this, cx| {
5128            let buffer_id = envelope.payload.buffer_id;
5129            let diff_base = envelope.payload.diff_base;
5130            if let Some(buffer) = this
5131                .opened_buffers
5132                .get_mut(&buffer_id)
5133                .and_then(|b| b.upgrade(cx))
5134                .or_else(|| {
5135                    this.incomplete_remote_buffers
5136                        .get(&buffer_id)
5137                        .cloned()
5138                        .flatten()
5139                })
5140            {
5141                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5142            }
5143            Ok(())
5144        })
5145    }
5146
5147    async fn handle_update_buffer_file(
5148        this: ModelHandle<Self>,
5149        envelope: TypedEnvelope<proto::UpdateBufferFile>,
5150        _: Arc<Client>,
5151        mut cx: AsyncAppContext,
5152    ) -> Result<()> {
5153        let buffer_id = envelope.payload.buffer_id;
5154
5155        this.update(&mut cx, |this, cx| {
5156            let payload = envelope.payload.clone();
5157            if let Some(buffer) = this
5158                .opened_buffers
5159                .get(&buffer_id)
5160                .and_then(|b| b.upgrade(cx))
5161                .or_else(|| {
5162                    this.incomplete_remote_buffers
5163                        .get(&buffer_id)
5164                        .cloned()
5165                        .flatten()
5166                })
5167            {
5168                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5169                let worktree = this
5170                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5171                    .ok_or_else(|| anyhow!("no such worktree"))?;
5172                let file = File::from_proto(file, worktree, cx)?;
5173                buffer.update(cx, |buffer, cx| {
5174                    buffer.file_updated(Arc::new(file), cx).detach();
5175                });
5176                this.detect_language_for_buffer(&buffer, cx);
5177            }
5178            Ok(())
5179        })
5180    }
5181
5182    async fn handle_save_buffer(
5183        this: ModelHandle<Self>,
5184        envelope: TypedEnvelope<proto::SaveBuffer>,
5185        _: Arc<Client>,
5186        mut cx: AsyncAppContext,
5187    ) -> Result<proto::BufferSaved> {
5188        let buffer_id = envelope.payload.buffer_id;
5189        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5190            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5191            let buffer = this
5192                .opened_buffers
5193                .get(&buffer_id)
5194                .and_then(|buffer| buffer.upgrade(cx))
5195                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5196            anyhow::Ok((project_id, buffer))
5197        })?;
5198        buffer
5199            .update(&mut cx, |buffer, _| {
5200                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
5201            })
5202            .await?;
5203        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
5204
5205        let (saved_version, fingerprint, mtime) = this
5206            .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5207            .await?;
5208        Ok(proto::BufferSaved {
5209            project_id,
5210            buffer_id,
5211            version: serialize_version(&saved_version),
5212            mtime: Some(mtime.into()),
5213            fingerprint: language::proto::serialize_fingerprint(fingerprint),
5214        })
5215    }
5216
5217    async fn handle_reload_buffers(
5218        this: ModelHandle<Self>,
5219        envelope: TypedEnvelope<proto::ReloadBuffers>,
5220        _: Arc<Client>,
5221        mut cx: AsyncAppContext,
5222    ) -> Result<proto::ReloadBuffersResponse> {
5223        let sender_id = envelope.original_sender_id()?;
5224        let reload = this.update(&mut cx, |this, cx| {
5225            let mut buffers = HashSet::default();
5226            for buffer_id in &envelope.payload.buffer_ids {
5227                buffers.insert(
5228                    this.opened_buffers
5229                        .get(buffer_id)
5230                        .and_then(|buffer| buffer.upgrade(cx))
5231                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5232                );
5233            }
5234            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5235        })?;
5236
5237        let project_transaction = reload.await?;
5238        let project_transaction = this.update(&mut cx, |this, cx| {
5239            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5240        });
5241        Ok(proto::ReloadBuffersResponse {
5242            transaction: Some(project_transaction),
5243        })
5244    }
5245
5246    async fn handle_synchronize_buffers(
5247        this: ModelHandle<Self>,
5248        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5249        _: Arc<Client>,
5250        mut cx: AsyncAppContext,
5251    ) -> Result<proto::SynchronizeBuffersResponse> {
5252        let project_id = envelope.payload.project_id;
5253        let mut response = proto::SynchronizeBuffersResponse {
5254            buffers: Default::default(),
5255        };
5256
5257        this.update(&mut cx, |this, cx| {
5258            let Some(guest_id) = envelope.original_sender_id else {
5259                log::error!("missing original_sender_id on SynchronizeBuffers request");
5260                return;
5261            };
5262
5263            this.shared_buffers.entry(guest_id).or_default().clear();
5264            for buffer in envelope.payload.buffers {
5265                let buffer_id = buffer.id;
5266                let remote_version = language::proto::deserialize_version(&buffer.version);
5267                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5268                    this.shared_buffers
5269                        .entry(guest_id)
5270                        .or_default()
5271                        .insert(buffer_id);
5272
5273                    let buffer = buffer.read(cx);
5274                    response.buffers.push(proto::BufferVersion {
5275                        id: buffer_id,
5276                        version: language::proto::serialize_version(&buffer.version),
5277                    });
5278
5279                    let operations = buffer.serialize_ops(Some(remote_version), cx);
5280                    let client = this.client.clone();
5281                    if let Some(file) = buffer.file() {
5282                        client
5283                            .send(proto::UpdateBufferFile {
5284                                project_id,
5285                                buffer_id: buffer_id as u64,
5286                                file: Some(file.to_proto()),
5287                            })
5288                            .log_err();
5289                    }
5290
5291                    client
5292                        .send(proto::UpdateDiffBase {
5293                            project_id,
5294                            buffer_id: buffer_id as u64,
5295                            diff_base: buffer.diff_base().map(Into::into),
5296                        })
5297                        .log_err();
5298
5299                    client
5300                        .send(proto::BufferReloaded {
5301                            project_id,
5302                            buffer_id,
5303                            version: language::proto::serialize_version(buffer.saved_version()),
5304                            mtime: Some(buffer.saved_mtime().into()),
5305                            fingerprint: language::proto::serialize_fingerprint(
5306                                buffer.saved_version_fingerprint(),
5307                            ),
5308                            line_ending: language::proto::serialize_line_ending(
5309                                buffer.line_ending(),
5310                            ) as i32,
5311                        })
5312                        .log_err();
5313
5314                    cx.background()
5315                        .spawn(
5316                            async move {
5317                                let operations = operations.await;
5318                                for chunk in split_operations(operations) {
5319                                    client
5320                                        .request(proto::UpdateBuffer {
5321                                            project_id,
5322                                            buffer_id,
5323                                            operations: chunk,
5324                                        })
5325                                        .await?;
5326                                }
5327                                anyhow::Ok(())
5328                            }
5329                            .log_err(),
5330                        )
5331                        .detach();
5332                }
5333            }
5334        });
5335
5336        Ok(response)
5337    }
5338
5339    async fn handle_format_buffers(
5340        this: ModelHandle<Self>,
5341        envelope: TypedEnvelope<proto::FormatBuffers>,
5342        _: Arc<Client>,
5343        mut cx: AsyncAppContext,
5344    ) -> Result<proto::FormatBuffersResponse> {
5345        let sender_id = envelope.original_sender_id()?;
5346        let format = this.update(&mut cx, |this, cx| {
5347            let mut buffers = HashSet::default();
5348            for buffer_id in &envelope.payload.buffer_ids {
5349                buffers.insert(
5350                    this.opened_buffers
5351                        .get(buffer_id)
5352                        .and_then(|buffer| buffer.upgrade(cx))
5353                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5354                );
5355            }
5356            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5357            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5358        })?;
5359
5360        let project_transaction = format.await?;
5361        let project_transaction = this.update(&mut cx, |this, cx| {
5362            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5363        });
5364        Ok(proto::FormatBuffersResponse {
5365            transaction: Some(project_transaction),
5366        })
5367    }
5368
5369    async fn handle_apply_additional_edits_for_completion(
5370        this: ModelHandle<Self>,
5371        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5372        _: Arc<Client>,
5373        mut cx: AsyncAppContext,
5374    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5375        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5376            let buffer = this
5377                .opened_buffers
5378                .get(&envelope.payload.buffer_id)
5379                .and_then(|buffer| buffer.upgrade(cx))
5380                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5381            let language = buffer.read(cx).language();
5382            let completion = language::proto::deserialize_completion(
5383                envelope
5384                    .payload
5385                    .completion
5386                    .ok_or_else(|| anyhow!("invalid completion"))?,
5387                language.cloned(),
5388            );
5389            Ok::<_, anyhow::Error>((buffer, completion))
5390        })?;
5391
5392        let completion = completion.await?;
5393
5394        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5395            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5396        });
5397
5398        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5399            transaction: apply_additional_edits
5400                .await?
5401                .as_ref()
5402                .map(language::proto::serialize_transaction),
5403        })
5404    }
5405
5406    async fn handle_apply_code_action(
5407        this: ModelHandle<Self>,
5408        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5409        _: Arc<Client>,
5410        mut cx: AsyncAppContext,
5411    ) -> Result<proto::ApplyCodeActionResponse> {
5412        let sender_id = envelope.original_sender_id()?;
5413        let action = language::proto::deserialize_code_action(
5414            envelope
5415                .payload
5416                .action
5417                .ok_or_else(|| anyhow!("invalid action"))?,
5418        )?;
5419        let apply_code_action = this.update(&mut cx, |this, cx| {
5420            let buffer = this
5421                .opened_buffers
5422                .get(&envelope.payload.buffer_id)
5423                .and_then(|buffer| buffer.upgrade(cx))
5424                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5425            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5426        })?;
5427
5428        let project_transaction = apply_code_action.await?;
5429        let project_transaction = this.update(&mut cx, |this, cx| {
5430            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5431        });
5432        Ok(proto::ApplyCodeActionResponse {
5433            transaction: Some(project_transaction),
5434        })
5435    }
5436
5437    async fn handle_lsp_command<T: LspCommand>(
5438        this: ModelHandle<Self>,
5439        envelope: TypedEnvelope<T::ProtoRequest>,
5440        _: Arc<Client>,
5441        mut cx: AsyncAppContext,
5442    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5443    where
5444        <T::LspRequest as lsp::request::Request>::Result: Send,
5445    {
5446        let sender_id = envelope.original_sender_id()?;
5447        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5448        let buffer_handle = this.read_with(&cx, |this, _| {
5449            this.opened_buffers
5450                .get(&buffer_id)
5451                .and_then(|buffer| buffer.upgrade(&cx))
5452                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5453        })?;
5454        let request = T::from_proto(
5455            envelope.payload,
5456            this.clone(),
5457            buffer_handle.clone(),
5458            cx.clone(),
5459        )
5460        .await?;
5461        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5462        let response = this
5463            .update(&mut cx, |this, cx| {
5464                this.request_lsp(buffer_handle, request, cx)
5465            })
5466            .await?;
5467        this.update(&mut cx, |this, cx| {
5468            Ok(T::response_to_proto(
5469                response,
5470                this,
5471                sender_id,
5472                &buffer_version,
5473                cx,
5474            ))
5475        })
5476    }
5477
5478    async fn handle_get_project_symbols(
5479        this: ModelHandle<Self>,
5480        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5481        _: Arc<Client>,
5482        mut cx: AsyncAppContext,
5483    ) -> Result<proto::GetProjectSymbolsResponse> {
5484        let symbols = this
5485            .update(&mut cx, |this, cx| {
5486                this.symbols(&envelope.payload.query, cx)
5487            })
5488            .await?;
5489
5490        Ok(proto::GetProjectSymbolsResponse {
5491            symbols: symbols.iter().map(serialize_symbol).collect(),
5492        })
5493    }
5494
5495    async fn handle_search_project(
5496        this: ModelHandle<Self>,
5497        envelope: TypedEnvelope<proto::SearchProject>,
5498        _: Arc<Client>,
5499        mut cx: AsyncAppContext,
5500    ) -> Result<proto::SearchProjectResponse> {
5501        let peer_id = envelope.original_sender_id()?;
5502        let query = SearchQuery::from_proto(envelope.payload)?;
5503        let result = this
5504            .update(&mut cx, |this, cx| this.search(query, cx))
5505            .await?;
5506
5507        this.update(&mut cx, |this, cx| {
5508            let mut locations = Vec::new();
5509            for (buffer, ranges) in result {
5510                for range in ranges {
5511                    let start = serialize_anchor(&range.start);
5512                    let end = serialize_anchor(&range.end);
5513                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5514                    locations.push(proto::Location {
5515                        buffer_id,
5516                        start: Some(start),
5517                        end: Some(end),
5518                    });
5519                }
5520            }
5521            Ok(proto::SearchProjectResponse { locations })
5522        })
5523    }
5524
5525    async fn handle_open_buffer_for_symbol(
5526        this: ModelHandle<Self>,
5527        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5528        _: Arc<Client>,
5529        mut cx: AsyncAppContext,
5530    ) -> Result<proto::OpenBufferForSymbolResponse> {
5531        let peer_id = envelope.original_sender_id()?;
5532        let symbol = envelope
5533            .payload
5534            .symbol
5535            .ok_or_else(|| anyhow!("invalid symbol"))?;
5536        let symbol = this
5537            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5538            .await?;
5539        let symbol = this.read_with(&cx, |this, _| {
5540            let signature = this.symbol_signature(&symbol.path);
5541            if signature == symbol.signature {
5542                Ok(symbol)
5543            } else {
5544                Err(anyhow!("invalid symbol signature"))
5545            }
5546        })?;
5547        let buffer = this
5548            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5549            .await?;
5550
5551        Ok(proto::OpenBufferForSymbolResponse {
5552            buffer_id: this.update(&mut cx, |this, cx| {
5553                this.create_buffer_for_peer(&buffer, peer_id, cx)
5554            }),
5555        })
5556    }
5557
5558    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5559        let mut hasher = Sha256::new();
5560        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5561        hasher.update(project_path.path.to_string_lossy().as_bytes());
5562        hasher.update(self.nonce.to_be_bytes());
5563        hasher.finalize().as_slice().try_into().unwrap()
5564    }
5565
5566    async fn handle_open_buffer_by_id(
5567        this: ModelHandle<Self>,
5568        envelope: TypedEnvelope<proto::OpenBufferById>,
5569        _: Arc<Client>,
5570        mut cx: AsyncAppContext,
5571    ) -> Result<proto::OpenBufferResponse> {
5572        let peer_id = envelope.original_sender_id()?;
5573        let buffer = this
5574            .update(&mut cx, |this, cx| {
5575                this.open_buffer_by_id(envelope.payload.id, cx)
5576            })
5577            .await?;
5578        this.update(&mut cx, |this, cx| {
5579            Ok(proto::OpenBufferResponse {
5580                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5581            })
5582        })
5583    }
5584
5585    async fn handle_open_buffer_by_path(
5586        this: ModelHandle<Self>,
5587        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5588        _: Arc<Client>,
5589        mut cx: AsyncAppContext,
5590    ) -> Result<proto::OpenBufferResponse> {
5591        let peer_id = envelope.original_sender_id()?;
5592        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5593        let open_buffer = this.update(&mut cx, |this, cx| {
5594            this.open_buffer(
5595                ProjectPath {
5596                    worktree_id,
5597                    path: PathBuf::from(envelope.payload.path).into(),
5598                },
5599                cx,
5600            )
5601        });
5602
5603        let buffer = open_buffer.await?;
5604        this.update(&mut cx, |this, cx| {
5605            Ok(proto::OpenBufferResponse {
5606                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5607            })
5608        })
5609    }
5610
5611    fn serialize_project_transaction_for_peer(
5612        &mut self,
5613        project_transaction: ProjectTransaction,
5614        peer_id: proto::PeerId,
5615        cx: &mut AppContext,
5616    ) -> proto::ProjectTransaction {
5617        let mut serialized_transaction = proto::ProjectTransaction {
5618            buffer_ids: Default::default(),
5619            transactions: Default::default(),
5620        };
5621        for (buffer, transaction) in project_transaction.0 {
5622            serialized_transaction
5623                .buffer_ids
5624                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5625            serialized_transaction
5626                .transactions
5627                .push(language::proto::serialize_transaction(&transaction));
5628        }
5629        serialized_transaction
5630    }
5631
5632    fn deserialize_project_transaction(
5633        &mut self,
5634        message: proto::ProjectTransaction,
5635        push_to_history: bool,
5636        cx: &mut ModelContext<Self>,
5637    ) -> Task<Result<ProjectTransaction>> {
5638        cx.spawn(|this, mut cx| async move {
5639            let mut project_transaction = ProjectTransaction::default();
5640            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5641            {
5642                let buffer = this
5643                    .update(&mut cx, |this, cx| {
5644                        this.wait_for_remote_buffer(buffer_id, cx)
5645                    })
5646                    .await?;
5647                let transaction = language::proto::deserialize_transaction(transaction)?;
5648                project_transaction.0.insert(buffer, transaction);
5649            }
5650
5651            for (buffer, transaction) in &project_transaction.0 {
5652                buffer
5653                    .update(&mut cx, |buffer, _| {
5654                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5655                    })
5656                    .await?;
5657
5658                if push_to_history {
5659                    buffer.update(&mut cx, |buffer, _| {
5660                        buffer.push_transaction(transaction.clone(), Instant::now());
5661                    });
5662                }
5663            }
5664
5665            Ok(project_transaction)
5666        })
5667    }
5668
5669    fn create_buffer_for_peer(
5670        &mut self,
5671        buffer: &ModelHandle<Buffer>,
5672        peer_id: proto::PeerId,
5673        cx: &mut AppContext,
5674    ) -> u64 {
5675        let buffer_id = buffer.read(cx).remote_id();
5676        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
5677            updates_tx
5678                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
5679                .ok();
5680        }
5681        buffer_id
5682    }
5683
5684    fn wait_for_remote_buffer(
5685        &mut self,
5686        id: u64,
5687        cx: &mut ModelContext<Self>,
5688    ) -> Task<Result<ModelHandle<Buffer>>> {
5689        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5690
5691        cx.spawn_weak(|this, mut cx| async move {
5692            let buffer = loop {
5693                let Some(this) = this.upgrade(&cx) else {
5694                    return Err(anyhow!("project dropped"));
5695                };
5696                let buffer = this.read_with(&cx, |this, cx| {
5697                    this.opened_buffers
5698                        .get(&id)
5699                        .and_then(|buffer| buffer.upgrade(cx))
5700                });
5701                if let Some(buffer) = buffer {
5702                    break buffer;
5703                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5704                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
5705                }
5706
5707                this.update(&mut cx, |this, _| {
5708                    this.incomplete_remote_buffers.entry(id).or_default();
5709                });
5710                drop(this);
5711                opened_buffer_rx
5712                    .next()
5713                    .await
5714                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5715            };
5716            buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5717            Ok(buffer)
5718        })
5719    }
5720
5721    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
5722        let project_id = match self.client_state.as_ref() {
5723            Some(ProjectClientState::Remote {
5724                sharing_has_stopped,
5725                remote_id,
5726                ..
5727            }) => {
5728                if *sharing_has_stopped {
5729                    return Task::ready(Err(anyhow!(
5730                        "can't synchronize remote buffers on a readonly project"
5731                    )));
5732                } else {
5733                    *remote_id
5734                }
5735            }
5736            Some(ProjectClientState::Local { .. }) | None => {
5737                return Task::ready(Err(anyhow!(
5738                    "can't synchronize remote buffers on a local project"
5739                )))
5740            }
5741        };
5742
5743        let client = self.client.clone();
5744        cx.spawn(|this, cx| async move {
5745            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
5746                let buffers = this
5747                    .opened_buffers
5748                    .iter()
5749                    .filter_map(|(id, buffer)| {
5750                        let buffer = buffer.upgrade(cx)?;
5751                        Some(proto::BufferVersion {
5752                            id: *id,
5753                            version: language::proto::serialize_version(&buffer.read(cx).version),
5754                        })
5755                    })
5756                    .collect();
5757                let incomplete_buffer_ids = this
5758                    .incomplete_remote_buffers
5759                    .keys()
5760                    .copied()
5761                    .collect::<Vec<_>>();
5762
5763                (buffers, incomplete_buffer_ids)
5764            });
5765            let response = client
5766                .request(proto::SynchronizeBuffers {
5767                    project_id,
5768                    buffers,
5769                })
5770                .await?;
5771
5772            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
5773                let client = client.clone();
5774                let buffer_id = buffer.id;
5775                let remote_version = language::proto::deserialize_version(&buffer.version);
5776                this.read_with(&cx, |this, cx| {
5777                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5778                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
5779                        cx.background().spawn(async move {
5780                            let operations = operations.await;
5781                            for chunk in split_operations(operations) {
5782                                client
5783                                    .request(proto::UpdateBuffer {
5784                                        project_id,
5785                                        buffer_id,
5786                                        operations: chunk,
5787                                    })
5788                                    .await?;
5789                            }
5790                            anyhow::Ok(())
5791                        })
5792                    } else {
5793                        Task::ready(Ok(()))
5794                    }
5795                })
5796            });
5797
5798            // Any incomplete buffers have open requests waiting. Request that the host sends
5799            // creates these buffers for us again to unblock any waiting futures.
5800            for id in incomplete_buffer_ids {
5801                cx.background()
5802                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
5803                    .detach();
5804            }
5805
5806            futures::future::join_all(send_updates_for_buffers)
5807                .await
5808                .into_iter()
5809                .collect()
5810        })
5811    }
5812
5813    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
5814        self.worktrees(cx)
5815            .map(|worktree| {
5816                let worktree = worktree.read(cx);
5817                proto::WorktreeMetadata {
5818                    id: worktree.id().to_proto(),
5819                    root_name: worktree.root_name().into(),
5820                    visible: worktree.is_visible(),
5821                    abs_path: worktree.abs_path().to_string_lossy().into(),
5822                }
5823            })
5824            .collect()
5825    }
5826
5827    fn set_worktrees_from_proto(
5828        &mut self,
5829        worktrees: Vec<proto::WorktreeMetadata>,
5830        cx: &mut ModelContext<Project>,
5831    ) -> Result<()> {
5832        let replica_id = self.replica_id();
5833        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
5834
5835        let mut old_worktrees_by_id = self
5836            .worktrees
5837            .drain(..)
5838            .filter_map(|worktree| {
5839                let worktree = worktree.upgrade(cx)?;
5840                Some((worktree.read(cx).id(), worktree))
5841            })
5842            .collect::<HashMap<_, _>>();
5843
5844        for worktree in worktrees {
5845            if let Some(old_worktree) =
5846                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
5847            {
5848                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
5849            } else {
5850                let worktree =
5851                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
5852                let _ = self.add_worktree(&worktree, cx);
5853            }
5854        }
5855
5856        self.metadata_changed(cx);
5857        for (id, _) in old_worktrees_by_id {
5858            cx.emit(Event::WorktreeRemoved(id));
5859        }
5860
5861        Ok(())
5862    }
5863
5864    fn set_collaborators_from_proto(
5865        &mut self,
5866        messages: Vec<proto::Collaborator>,
5867        cx: &mut ModelContext<Self>,
5868    ) -> Result<()> {
5869        let mut collaborators = HashMap::default();
5870        for message in messages {
5871            let collaborator = Collaborator::from_proto(message)?;
5872            collaborators.insert(collaborator.peer_id, collaborator);
5873        }
5874        for old_peer_id in self.collaborators.keys() {
5875            if !collaborators.contains_key(old_peer_id) {
5876                cx.emit(Event::CollaboratorLeft(*old_peer_id));
5877            }
5878        }
5879        self.collaborators = collaborators;
5880        Ok(())
5881    }
5882
5883    fn deserialize_symbol(
5884        &self,
5885        serialized_symbol: proto::Symbol,
5886    ) -> impl Future<Output = Result<Symbol>> {
5887        let languages = self.languages.clone();
5888        async move {
5889            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5890            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5891            let start = serialized_symbol
5892                .start
5893                .ok_or_else(|| anyhow!("invalid start"))?;
5894            let end = serialized_symbol
5895                .end
5896                .ok_or_else(|| anyhow!("invalid end"))?;
5897            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5898            let path = ProjectPath {
5899                worktree_id,
5900                path: PathBuf::from(serialized_symbol.path).into(),
5901            };
5902            let language = languages
5903                .language_for_file(&path.path, None)
5904                .await
5905                .log_err();
5906            Ok(Symbol {
5907                language_server_name: LanguageServerName(
5908                    serialized_symbol.language_server_name.into(),
5909                ),
5910                source_worktree_id,
5911                path,
5912                label: {
5913                    match language {
5914                        Some(language) => {
5915                            language
5916                                .label_for_symbol(&serialized_symbol.name, kind)
5917                                .await
5918                        }
5919                        None => None,
5920                    }
5921                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5922                },
5923
5924                name: serialized_symbol.name,
5925                range: Unclipped(PointUtf16::new(start.row, start.column))
5926                    ..Unclipped(PointUtf16::new(end.row, end.column)),
5927                kind,
5928                signature: serialized_symbol
5929                    .signature
5930                    .try_into()
5931                    .map_err(|_| anyhow!("invalid signature"))?,
5932            })
5933        }
5934    }
5935
5936    async fn handle_buffer_saved(
5937        this: ModelHandle<Self>,
5938        envelope: TypedEnvelope<proto::BufferSaved>,
5939        _: Arc<Client>,
5940        mut cx: AsyncAppContext,
5941    ) -> Result<()> {
5942        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
5943        let version = deserialize_version(&envelope.payload.version);
5944        let mtime = envelope
5945            .payload
5946            .mtime
5947            .ok_or_else(|| anyhow!("missing mtime"))?
5948            .into();
5949
5950        this.update(&mut cx, |this, cx| {
5951            let buffer = this
5952                .opened_buffers
5953                .get(&envelope.payload.buffer_id)
5954                .and_then(|buffer| buffer.upgrade(cx))
5955                .or_else(|| {
5956                    this.incomplete_remote_buffers
5957                        .get(&envelope.payload.buffer_id)
5958                        .and_then(|b| b.clone())
5959                });
5960            if let Some(buffer) = buffer {
5961                buffer.update(cx, |buffer, cx| {
5962                    buffer.did_save(version, fingerprint, mtime, cx);
5963                });
5964            }
5965            Ok(())
5966        })
5967    }
5968
5969    async fn handle_buffer_reloaded(
5970        this: ModelHandle<Self>,
5971        envelope: TypedEnvelope<proto::BufferReloaded>,
5972        _: Arc<Client>,
5973        mut cx: AsyncAppContext,
5974    ) -> Result<()> {
5975        let payload = envelope.payload;
5976        let version = deserialize_version(&payload.version);
5977        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
5978        let line_ending = deserialize_line_ending(
5979            proto::LineEnding::from_i32(payload.line_ending)
5980                .ok_or_else(|| anyhow!("missing line ending"))?,
5981        );
5982        let mtime = payload
5983            .mtime
5984            .ok_or_else(|| anyhow!("missing mtime"))?
5985            .into();
5986        this.update(&mut cx, |this, cx| {
5987            let buffer = this
5988                .opened_buffers
5989                .get(&payload.buffer_id)
5990                .and_then(|buffer| buffer.upgrade(cx))
5991                .or_else(|| {
5992                    this.incomplete_remote_buffers
5993                        .get(&payload.buffer_id)
5994                        .cloned()
5995                        .flatten()
5996                });
5997            if let Some(buffer) = buffer {
5998                buffer.update(cx, |buffer, cx| {
5999                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6000                });
6001            }
6002            Ok(())
6003        })
6004    }
6005
6006    #[allow(clippy::type_complexity)]
6007    fn edits_from_lsp(
6008        &mut self,
6009        buffer: &ModelHandle<Buffer>,
6010        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6011        version: Option<i32>,
6012        cx: &mut ModelContext<Self>,
6013    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6014        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
6015        cx.background().spawn(async move {
6016            let snapshot = snapshot?;
6017            let mut lsp_edits = lsp_edits
6018                .into_iter()
6019                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6020                .collect::<Vec<_>>();
6021            lsp_edits.sort_by_key(|(range, _)| range.start);
6022
6023            let mut lsp_edits = lsp_edits.into_iter().peekable();
6024            let mut edits = Vec::new();
6025            while let Some((range, mut new_text)) = lsp_edits.next() {
6026                // Clip invalid ranges provided by the language server.
6027                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6028                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
6029
6030                // Combine any LSP edits that are adjacent.
6031                //
6032                // Also, combine LSP edits that are separated from each other by only
6033                // a newline. This is important because for some code actions,
6034                // Rust-analyzer rewrites the entire buffer via a series of edits that
6035                // are separated by unchanged newline characters.
6036                //
6037                // In order for the diffing logic below to work properly, any edits that
6038                // cancel each other out must be combined into one.
6039                while let Some((next_range, next_text)) = lsp_edits.peek() {
6040                    if next_range.start.0 > range.end {
6041                        if next_range.start.0.row > range.end.row + 1
6042                            || next_range.start.0.column > 0
6043                            || snapshot.clip_point_utf16(
6044                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6045                                Bias::Left,
6046                            ) > range.end
6047                        {
6048                            break;
6049                        }
6050                        new_text.push('\n');
6051                    }
6052                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6053                    new_text.push_str(next_text);
6054                    lsp_edits.next();
6055                }
6056
6057                // For multiline edits, perform a diff of the old and new text so that
6058                // we can identify the changes more precisely, preserving the locations
6059                // of any anchors positioned in the unchanged regions.
6060                if range.end.row > range.start.row {
6061                    let mut offset = range.start.to_offset(&snapshot);
6062                    let old_text = snapshot.text_for_range(range).collect::<String>();
6063
6064                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6065                    let mut moved_since_edit = true;
6066                    for change in diff.iter_all_changes() {
6067                        let tag = change.tag();
6068                        let value = change.value();
6069                        match tag {
6070                            ChangeTag::Equal => {
6071                                offset += value.len();
6072                                moved_since_edit = true;
6073                            }
6074                            ChangeTag::Delete => {
6075                                let start = snapshot.anchor_after(offset);
6076                                let end = snapshot.anchor_before(offset + value.len());
6077                                if moved_since_edit {
6078                                    edits.push((start..end, String::new()));
6079                                } else {
6080                                    edits.last_mut().unwrap().0.end = end;
6081                                }
6082                                offset += value.len();
6083                                moved_since_edit = false;
6084                            }
6085                            ChangeTag::Insert => {
6086                                if moved_since_edit {
6087                                    let anchor = snapshot.anchor_after(offset);
6088                                    edits.push((anchor..anchor, value.to_string()));
6089                                } else {
6090                                    edits.last_mut().unwrap().1.push_str(value);
6091                                }
6092                                moved_since_edit = false;
6093                            }
6094                        }
6095                    }
6096                } else if range.end == range.start {
6097                    let anchor = snapshot.anchor_after(range.start);
6098                    edits.push((anchor..anchor, new_text));
6099                } else {
6100                    let edit_start = snapshot.anchor_after(range.start);
6101                    let edit_end = snapshot.anchor_before(range.end);
6102                    edits.push((edit_start..edit_end, new_text));
6103                }
6104            }
6105
6106            Ok(edits)
6107        })
6108    }
6109
6110    fn buffer_snapshot_for_lsp_version(
6111        &mut self,
6112        buffer: &ModelHandle<Buffer>,
6113        version: Option<i32>,
6114        cx: &AppContext,
6115    ) -> Result<TextBufferSnapshot> {
6116        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6117
6118        if let Some(version) = version {
6119            let buffer_id = buffer.read(cx).remote_id();
6120            let snapshots = self
6121                .buffer_snapshots
6122                .get_mut(&buffer_id)
6123                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
6124            let found_snapshot = snapshots
6125                .binary_search_by_key(&version, |e| e.0)
6126                .map(|ix| snapshots[ix].1.clone())
6127                .map_err(|_| {
6128                    anyhow!(
6129                        "snapshot not found for buffer {} at version {}",
6130                        buffer_id,
6131                        version
6132                    )
6133                })?;
6134            snapshots.retain(|(snapshot_version, _)| {
6135                snapshot_version + OLD_VERSIONS_TO_RETAIN >= version
6136            });
6137            Ok(found_snapshot)
6138        } else {
6139            Ok((buffer.read(cx)).text_snapshot())
6140        }
6141    }
6142
6143    fn language_server_for_buffer(
6144        &self,
6145        buffer: &Buffer,
6146        cx: &AppContext,
6147    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6148        let server_id = self.language_server_id_for_buffer(buffer, cx)?;
6149        let server = self.language_servers.get(&server_id)?;
6150        if let LanguageServerState::Running {
6151            adapter, server, ..
6152        } = server
6153        {
6154            Some((adapter, server))
6155        } else {
6156            None
6157        }
6158    }
6159
6160    fn language_server_id_for_buffer(&self, buffer: &Buffer, cx: &AppContext) -> Option<usize> {
6161        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6162            let name = language.lsp_adapter()?.name.clone();
6163            let worktree_id = file.worktree_id(cx);
6164            let key = (worktree_id, name);
6165            self.language_server_ids.get(&key).copied()
6166        } else {
6167            None
6168        }
6169    }
6170}
6171
6172impl WorktreeHandle {
6173    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6174        match self {
6175            WorktreeHandle::Strong(handle) => Some(handle.clone()),
6176            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6177        }
6178    }
6179}
6180
6181impl OpenBuffer {
6182    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6183        match self {
6184            OpenBuffer::Strong(handle) => Some(handle.clone()),
6185            OpenBuffer::Weak(handle) => handle.upgrade(cx),
6186            OpenBuffer::Operations(_) => None,
6187        }
6188    }
6189}
6190
6191pub struct PathMatchCandidateSet {
6192    pub snapshot: Snapshot,
6193    pub include_ignored: bool,
6194    pub include_root_name: bool,
6195}
6196
6197impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6198    type Candidates = PathMatchCandidateSetIter<'a>;
6199
6200    fn id(&self) -> usize {
6201        self.snapshot.id().to_usize()
6202    }
6203
6204    fn len(&self) -> usize {
6205        if self.include_ignored {
6206            self.snapshot.file_count()
6207        } else {
6208            self.snapshot.visible_file_count()
6209        }
6210    }
6211
6212    fn prefix(&self) -> Arc<str> {
6213        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6214            self.snapshot.root_name().into()
6215        } else if self.include_root_name {
6216            format!("{}/", self.snapshot.root_name()).into()
6217        } else {
6218            "".into()
6219        }
6220    }
6221
6222    fn candidates(&'a self, start: usize) -> Self::Candidates {
6223        PathMatchCandidateSetIter {
6224            traversal: self.snapshot.files(self.include_ignored, start),
6225        }
6226    }
6227}
6228
6229pub struct PathMatchCandidateSetIter<'a> {
6230    traversal: Traversal<'a>,
6231}
6232
6233impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6234    type Item = fuzzy::PathMatchCandidate<'a>;
6235
6236    fn next(&mut self) -> Option<Self::Item> {
6237        self.traversal.next().map(|entry| {
6238            if let EntryKind::File(char_bag) = entry.kind {
6239                fuzzy::PathMatchCandidate {
6240                    path: &entry.path,
6241                    char_bag,
6242                }
6243            } else {
6244                unreachable!()
6245            }
6246        })
6247    }
6248}
6249
6250impl Entity for Project {
6251    type Event = Event;
6252
6253    fn release(&mut self, cx: &mut gpui::AppContext) {
6254        match &self.client_state {
6255            Some(ProjectClientState::Local { .. }) => {
6256                let _ = self.unshare_internal(cx);
6257            }
6258            Some(ProjectClientState::Remote { remote_id, .. }) => {
6259                let _ = self.client.send(proto::LeaveProject {
6260                    project_id: *remote_id,
6261                });
6262                self.disconnected_from_host_internal(cx);
6263            }
6264            _ => {}
6265        }
6266    }
6267
6268    fn app_will_quit(
6269        &mut self,
6270        _: &mut AppContext,
6271    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6272        let shutdown_futures = self
6273            .language_servers
6274            .drain()
6275            .map(|(_, server_state)| async {
6276                match server_state {
6277                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6278                    LanguageServerState::Starting(starting_server) => {
6279                        starting_server.await?.shutdown()?.await
6280                    }
6281                }
6282            })
6283            .collect::<Vec<_>>();
6284
6285        Some(
6286            async move {
6287                futures::future::join_all(shutdown_futures).await;
6288            }
6289            .boxed(),
6290        )
6291    }
6292}
6293
6294impl Collaborator {
6295    fn from_proto(message: proto::Collaborator) -> Result<Self> {
6296        Ok(Self {
6297            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6298            replica_id: message.replica_id as ReplicaId,
6299        })
6300    }
6301}
6302
6303impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6304    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6305        Self {
6306            worktree_id,
6307            path: path.as_ref().into(),
6308        }
6309    }
6310}
6311
6312fn split_operations(
6313    mut operations: Vec<proto::Operation>,
6314) -> impl Iterator<Item = Vec<proto::Operation>> {
6315    #[cfg(any(test, feature = "test-support"))]
6316    const CHUNK_SIZE: usize = 5;
6317
6318    #[cfg(not(any(test, feature = "test-support")))]
6319    const CHUNK_SIZE: usize = 100;
6320
6321    let mut done = false;
6322    std::iter::from_fn(move || {
6323        if done {
6324            return None;
6325        }
6326
6327        let operations = operations
6328            .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6329            .collect::<Vec<_>>();
6330        if operations.is_empty() {
6331            done = true;
6332        }
6333        Some(operations)
6334    })
6335}
6336
6337fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6338    proto::Symbol {
6339        language_server_name: symbol.language_server_name.0.to_string(),
6340        source_worktree_id: symbol.source_worktree_id.to_proto(),
6341        worktree_id: symbol.path.worktree_id.to_proto(),
6342        path: symbol.path.path.to_string_lossy().to_string(),
6343        name: symbol.name.clone(),
6344        kind: unsafe { mem::transmute(symbol.kind) },
6345        start: Some(proto::PointUtf16 {
6346            row: symbol.range.start.0.row,
6347            column: symbol.range.start.0.column,
6348        }),
6349        end: Some(proto::PointUtf16 {
6350            row: symbol.range.end.0.row,
6351            column: symbol.range.end.0.column,
6352        }),
6353        signature: symbol.signature.to_vec(),
6354    }
6355}
6356
6357fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6358    let mut path_components = path.components();
6359    let mut base_components = base.components();
6360    let mut components: Vec<Component> = Vec::new();
6361    loop {
6362        match (path_components.next(), base_components.next()) {
6363            (None, None) => break,
6364            (Some(a), None) => {
6365                components.push(a);
6366                components.extend(path_components.by_ref());
6367                break;
6368            }
6369            (None, _) => components.push(Component::ParentDir),
6370            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6371            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6372            (Some(a), Some(_)) => {
6373                components.push(Component::ParentDir);
6374                for _ in base_components {
6375                    components.push(Component::ParentDir);
6376                }
6377                components.push(a);
6378                components.extend(path_components.by_ref());
6379                break;
6380            }
6381        }
6382    }
6383    components.iter().map(|c| c.as_os_str()).collect()
6384}
6385
6386impl Item for Buffer {
6387    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6388        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6389    }
6390
6391    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6392        File::from_dyn(self.file()).map(|file| ProjectPath {
6393            worktree_id: file.worktree_id(cx),
6394            path: file.path().clone(),
6395        })
6396    }
6397}