project.rs

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