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