project.rs

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