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