project.rs

    1pub mod connection_manager;
    2pub mod debounced_delay;
    3pub mod lsp_command;
    4pub mod lsp_ext_command;
    5mod prettier_support;
    6pub mod project_settings;
    7pub mod search;
    8mod task_inventory;
    9pub mod terminals;
   10
   11#[cfg(test)]
   12mod project_tests;
   13pub mod search_history;
   14
   15use anyhow::{anyhow, bail, Context as _, Result};
   16use async_trait::async_trait;
   17use client::{
   18    proto, Client, Collaborator, PendingEntitySubscription, ProjectId, RemoteProjectId,
   19    TypedEnvelope, UserStore,
   20};
   21use clock::ReplicaId;
   22use collections::{hash_map, BTreeMap, HashMap, HashSet, VecDeque};
   23use copilot::Copilot;
   24use debounced_delay::DebouncedDelay;
   25use futures::{
   26    channel::{
   27        mpsc::{self, UnboundedReceiver},
   28        oneshot,
   29    },
   30    future::{join_all, try_join_all, Shared},
   31    select,
   32    stream::FuturesUnordered,
   33    AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
   34};
   35use git::{blame::Blame, repository::GitRepository};
   36use globset::{Glob, GlobSet, GlobSetBuilder};
   37use gpui::{
   38    AnyModel, AppContext, AsyncAppContext, BackgroundExecutor, BorrowAppContext, Context, Entity,
   39    EventEmitter, Model, ModelContext, PromptLevel, Task, WeakModel,
   40};
   41use itertools::Itertools;
   42use language::{
   43    language_settings::{language_settings, FormatOnSave, Formatter, InlayHintKind},
   44    markdown, point_to_lsp, prepare_completion_documentation,
   45    proto::{
   46        deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
   47        serialize_version, split_operations,
   48    },
   49    range_from_lsp, Bias, Buffer, BufferSnapshot, CachedLspAdapter, Capability, CodeLabel,
   50    Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Documentation, Event as BufferEvent,
   51    File as _, Language, LanguageRegistry, LanguageServerName, LocalFile, LspAdapterDelegate,
   52    Operation, Patch, PendingLanguageServer, PointUtf16, TextBufferSnapshot, ToOffset,
   53    ToPointUtf16, Transaction, Unclipped,
   54};
   55use log::error;
   56use lsp::{
   57    DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
   58    DocumentHighlightKind, LanguageServer, LanguageServerBinary, LanguageServerId,
   59    LspRequestFuture, MessageActionItem, OneOf, ServerCapabilities, ServerHealthStatus,
   60    ServerStatus,
   61};
   62use lsp_command::*;
   63use node_runtime::NodeRuntime;
   64use parking_lot::{Mutex, RwLock};
   65use postage::watch;
   66use prettier_support::{DefaultPrettier, PrettierInstance};
   67use project_settings::{LspSettings, ProjectSettings};
   68use rand::prelude::*;
   69use search_history::SearchHistory;
   70use worktree::LocalSnapshot;
   71
   72use rpc::{ErrorCode, ErrorExt as _};
   73use search::SearchQuery;
   74use serde::Serialize;
   75use settings::{watch_config_file, Settings, SettingsLocation, SettingsStore};
   76use sha2::{Digest, Sha256};
   77use similar::{ChangeTag, TextDiff};
   78use smol::channel::{Receiver, Sender};
   79use smol::lock::Semaphore;
   80use std::{
   81    cmp::{self, Ordering},
   82    convert::TryInto,
   83    env,
   84    ffi::OsStr,
   85    hash::Hash,
   86    io, iter, mem,
   87    num::NonZeroU32,
   88    ops::Range,
   89    path::{self, Component, Path, PathBuf},
   90    process::Stdio,
   91    str::{self, FromStr},
   92    sync::{
   93        atomic::{AtomicUsize, Ordering::SeqCst},
   94        Arc,
   95    },
   96    time::{Duration, Instant},
   97};
   98use task::static_source::{StaticSource, TrackedFile};
   99use terminals::Terminals;
  100use text::{Anchor, BufferId};
  101use util::{
  102    debug_panic, defer,
  103    http::{HttpClient, Url},
  104    maybe, merge_json_value_into, parse_env_output,
  105    paths::{
  106        LOCAL_SETTINGS_RELATIVE_PATH, LOCAL_TASKS_RELATIVE_PATH, LOCAL_VSCODE_TASKS_RELATIVE_PATH,
  107    },
  108    post_inc, ResultExt, TryFutureExt as _,
  109};
  110use worktree::{Snapshot, Traversal};
  111
  112pub use fs::*;
  113pub use language::Location;
  114#[cfg(any(test, feature = "test-support"))]
  115pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
  116pub use task_inventory::{Inventory, TaskSourceKind};
  117pub use worktree::{
  118    DiagnosticSummary, Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId,
  119    RepositoryEntry, UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId,
  120    WorktreeSettings, FS_WATCH_LATENCY,
  121};
  122
  123const MAX_SERVER_REINSTALL_ATTEMPT_COUNT: u64 = 4;
  124const SERVER_REINSTALL_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  125const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
  126pub const SERVER_PROGRESS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  127
  128const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
  129
  130pub trait Item {
  131    fn try_open(
  132        project: &Model<Project>,
  133        path: &ProjectPath,
  134        cx: &mut AppContext,
  135    ) -> Option<Task<Result<Model<Self>>>>
  136    where
  137        Self: Sized;
  138    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  139    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
  140}
  141
  142#[derive(Clone)]
  143pub enum OpenedBufferEvent {
  144    Disconnected,
  145    Ok(BufferId),
  146    Err(BufferId, Arc<anyhow::Error>),
  147}
  148
  149/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
  150/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
  151/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
  152///
  153/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
  154pub struct Project {
  155    worktrees: Vec<WorktreeHandle>,
  156    active_entry: Option<ProjectEntryId>,
  157    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
  158    pending_language_server_update: Option<BufferOrderedMessage>,
  159    flush_language_server_update: Option<Task<()>>,
  160
  161    languages: Arc<LanguageRegistry>,
  162    supplementary_language_servers:
  163        HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
  164    language_servers: HashMap<LanguageServerId, LanguageServerState>,
  165    language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
  166    language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
  167    last_formatting_failure: Option<String>,
  168    last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
  169    language_server_watched_paths: HashMap<LanguageServerId, HashMap<WorktreeId, GlobSet>>,
  170    client: Arc<client::Client>,
  171    next_entry_id: Arc<AtomicUsize>,
  172    join_project_response_message_id: u32,
  173    next_diagnostic_group_id: usize,
  174    user_store: Model<UserStore>,
  175    fs: Arc<dyn Fs>,
  176    client_state: ProjectClientState,
  177    collaborators: HashMap<proto::PeerId, Collaborator>,
  178    client_subscriptions: Vec<client::Subscription>,
  179    _subscriptions: Vec<gpui::Subscription>,
  180    loading_buffers: HashMap<BufferId, Vec<oneshot::Sender<Result<Model<Buffer>, anyhow::Error>>>>,
  181    incomplete_remote_buffers: HashMap<BufferId, Model<Buffer>>,
  182    shared_buffers: HashMap<proto::PeerId, HashSet<BufferId>>,
  183    #[allow(clippy::type_complexity)]
  184    loading_buffers_by_path: HashMap<
  185        ProjectPath,
  186        postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
  187    >,
  188    #[allow(clippy::type_complexity)]
  189    loading_local_worktrees:
  190        HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
  191    opened_buffers: HashMap<BufferId, OpenBuffer>,
  192    local_buffer_ids_by_path: HashMap<ProjectPath, BufferId>,
  193    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
  194    buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
  195    buffers_being_formatted: HashSet<BufferId>,
  196    buffers_needing_diff: HashSet<WeakModel<Buffer>>,
  197    git_diff_debouncer: DebouncedDelay,
  198    nonce: u128,
  199    _maintain_buffer_languages: Task<()>,
  200    _maintain_workspace_config: Task<Result<()>>,
  201    terminals: Terminals,
  202    copilot_lsp_subscription: Option<gpui::Subscription>,
  203    copilot_log_subscription: Option<lsp::Subscription>,
  204    current_lsp_settings: HashMap<Arc<str>, LspSettings>,
  205    node: Option<Arc<dyn NodeRuntime>>,
  206    default_prettier: DefaultPrettier,
  207    prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
  208    prettier_instances: HashMap<PathBuf, PrettierInstance>,
  209    tasks: Model<Inventory>,
  210    hosted_project_id: Option<ProjectId>,
  211    remote_project_id: Option<client::RemoteProjectId>,
  212    search_history: SearchHistory,
  213}
  214
  215pub enum LanguageServerToQuery {
  216    Primary,
  217    Other(LanguageServerId),
  218}
  219
  220struct LspBufferSnapshot {
  221    version: i32,
  222    snapshot: TextBufferSnapshot,
  223}
  224
  225/// Message ordered with respect to buffer operations
  226#[derive(Debug)]
  227enum BufferOrderedMessage {
  228    Operation {
  229        buffer_id: BufferId,
  230        operation: proto::Operation,
  231    },
  232    LanguageServerUpdate {
  233        language_server_id: LanguageServerId,
  234        message: proto::update_language_server::Variant,
  235    },
  236    Resync,
  237}
  238
  239#[derive(Debug)]
  240enum LocalProjectUpdate {
  241    WorktreesChanged,
  242    CreateBufferForPeer {
  243        peer_id: proto::PeerId,
  244        buffer_id: BufferId,
  245    },
  246}
  247
  248enum OpenBuffer {
  249    Strong(Model<Buffer>),
  250    Weak(WeakModel<Buffer>),
  251    Operations(Vec<Operation>),
  252}
  253
  254#[derive(Clone)]
  255enum WorktreeHandle {
  256    Strong(Model<Worktree>),
  257    Weak(WeakModel<Worktree>),
  258}
  259
  260#[derive(Debug)]
  261enum ProjectClientState {
  262    Local,
  263    Shared {
  264        remote_id: u64,
  265        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
  266        _send_updates: Task<Result<()>>,
  267    },
  268    Remote {
  269        sharing_has_stopped: bool,
  270        capability: Capability,
  271        remote_id: u64,
  272        replica_id: ReplicaId,
  273        in_room: bool,
  274    },
  275}
  276
  277/// A prompt requested by LSP server.
  278#[derive(Clone, Debug)]
  279pub struct LanguageServerPromptRequest {
  280    pub level: PromptLevel,
  281    pub message: String,
  282    pub actions: Vec<MessageActionItem>,
  283    pub lsp_name: String,
  284    response_channel: Sender<MessageActionItem>,
  285}
  286
  287impl LanguageServerPromptRequest {
  288    pub async fn respond(self, index: usize) -> Option<()> {
  289        if let Some(response) = self.actions.into_iter().nth(index) {
  290            self.response_channel.send(response).await.ok()
  291        } else {
  292            None
  293        }
  294    }
  295}
  296impl PartialEq for LanguageServerPromptRequest {
  297    fn eq(&self, other: &Self) -> bool {
  298        self.message == other.message && self.actions == other.actions
  299    }
  300}
  301
  302#[derive(Clone, Debug, PartialEq)]
  303pub enum Event {
  304    LanguageServerAdded(LanguageServerId),
  305    LanguageServerRemoved(LanguageServerId),
  306    LanguageServerLog(LanguageServerId, String),
  307    Notification(String),
  308    LanguageServerPrompt(LanguageServerPromptRequest),
  309    LanguageNotFound(Model<Buffer>),
  310    ActiveEntryChanged(Option<ProjectEntryId>),
  311    ActivateProjectPanel,
  312    WorktreeAdded,
  313    WorktreeRemoved(WorktreeId),
  314    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
  315    WorktreeUpdatedGitRepositories,
  316    DiskBasedDiagnosticsStarted {
  317        language_server_id: LanguageServerId,
  318    },
  319    DiskBasedDiagnosticsFinished {
  320        language_server_id: LanguageServerId,
  321    },
  322    DiagnosticsUpdated {
  323        path: ProjectPath,
  324        language_server_id: LanguageServerId,
  325    },
  326    RemoteIdChanged(Option<u64>),
  327    DisconnectedFromHost,
  328    Closed,
  329    DeletedEntry(ProjectEntryId),
  330    CollaboratorUpdated {
  331        old_peer_id: proto::PeerId,
  332        new_peer_id: proto::PeerId,
  333    },
  334    CollaboratorJoined(proto::PeerId),
  335    CollaboratorLeft(proto::PeerId),
  336    RefreshInlayHints,
  337    RevealInProjectPanel(ProjectEntryId),
  338}
  339
  340pub enum LanguageServerState {
  341    Starting(Task<Option<Arc<LanguageServer>>>),
  342
  343    Running {
  344        language: Arc<Language>,
  345        adapter: Arc<CachedLspAdapter>,
  346        server: Arc<LanguageServer>,
  347        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
  348    },
  349}
  350
  351#[derive(Clone, Debug, Serialize)]
  352pub struct LanguageServerStatus {
  353    pub name: String,
  354    pub pending_work: BTreeMap<String, LanguageServerProgress>,
  355    pub has_pending_diagnostic_updates: bool,
  356    progress_tokens: HashSet<String>,
  357}
  358
  359#[derive(Clone, Debug, Serialize)]
  360pub struct LanguageServerProgress {
  361    pub message: Option<String>,
  362    pub percentage: Option<usize>,
  363    #[serde(skip_serializing)]
  364    pub last_update_at: Instant,
  365}
  366
  367#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
  368pub struct ProjectPath {
  369    pub worktree_id: WorktreeId,
  370    pub path: Arc<Path>,
  371}
  372
  373#[derive(Debug, Clone, PartialEq, Eq)]
  374pub struct InlayHint {
  375    pub position: language::Anchor,
  376    pub label: InlayHintLabel,
  377    pub kind: Option<InlayHintKind>,
  378    pub padding_left: bool,
  379    pub padding_right: bool,
  380    pub tooltip: Option<InlayHintTooltip>,
  381    pub resolve_state: ResolveState,
  382}
  383
  384/// A completion provided by a language server
  385#[derive(Clone, Debug)]
  386pub struct Completion {
  387    /// The range of the buffer that will be replaced.
  388    pub old_range: Range<Anchor>,
  389    /// The new text that will be inserted.
  390    pub new_text: String,
  391    /// A label for this completion that is shown in the menu.
  392    pub label: CodeLabel,
  393    /// The id of the language server that produced this completion.
  394    pub server_id: LanguageServerId,
  395    /// The documentation for this completion.
  396    pub documentation: Option<Documentation>,
  397    /// The raw completion provided by the language server.
  398    pub lsp_completion: lsp::CompletionItem,
  399}
  400
  401/// A completion provided by a language server
  402#[derive(Clone, Debug)]
  403struct CoreCompletion {
  404    old_range: Range<Anchor>,
  405    new_text: String,
  406    server_id: LanguageServerId,
  407    lsp_completion: lsp::CompletionItem,
  408}
  409
  410/// A code action provided by a language server.
  411#[derive(Clone, Debug)]
  412pub struct CodeAction {
  413    /// The id of the language server that produced this code action.
  414    pub server_id: LanguageServerId,
  415    /// The range of the buffer where this code action is applicable.
  416    pub range: Range<Anchor>,
  417    /// The raw code action provided by the language server.
  418    pub lsp_action: lsp::CodeAction,
  419}
  420
  421#[derive(Debug, Clone, PartialEq, Eq)]
  422pub enum ResolveState {
  423    Resolved,
  424    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
  425    Resolving,
  426}
  427
  428impl InlayHint {
  429    pub fn text(&self) -> String {
  430        match &self.label {
  431            InlayHintLabel::String(s) => s.to_owned(),
  432            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
  433        }
  434    }
  435}
  436
  437#[derive(Debug, Clone, PartialEq, Eq)]
  438pub enum InlayHintLabel {
  439    String(String),
  440    LabelParts(Vec<InlayHintLabelPart>),
  441}
  442
  443#[derive(Debug, Clone, PartialEq, Eq)]
  444pub struct InlayHintLabelPart {
  445    pub value: String,
  446    pub tooltip: Option<InlayHintLabelPartTooltip>,
  447    pub location: Option<(LanguageServerId, lsp::Location)>,
  448}
  449
  450#[derive(Debug, Clone, PartialEq, Eq)]
  451pub enum InlayHintTooltip {
  452    String(String),
  453    MarkupContent(MarkupContent),
  454}
  455
  456#[derive(Debug, Clone, PartialEq, Eq)]
  457pub enum InlayHintLabelPartTooltip {
  458    String(String),
  459    MarkupContent(MarkupContent),
  460}
  461
  462#[derive(Debug, Clone, PartialEq, Eq)]
  463pub struct MarkupContent {
  464    pub kind: HoverBlockKind,
  465    pub value: String,
  466}
  467
  468#[derive(Debug, Clone)]
  469pub struct LocationLink {
  470    pub origin: Option<Location>,
  471    pub target: Location,
  472}
  473
  474#[derive(Debug)]
  475pub struct DocumentHighlight {
  476    pub range: Range<language::Anchor>,
  477    pub kind: DocumentHighlightKind,
  478}
  479
  480#[derive(Clone, Debug)]
  481pub struct Symbol {
  482    pub language_server_name: LanguageServerName,
  483    pub source_worktree_id: WorktreeId,
  484    pub path: ProjectPath,
  485    pub label: CodeLabel,
  486    pub name: String,
  487    pub kind: lsp::SymbolKind,
  488    pub range: Range<Unclipped<PointUtf16>>,
  489    pub signature: [u8; 32],
  490}
  491
  492#[derive(Clone, Debug)]
  493struct CoreSymbol {
  494    pub language_server_name: LanguageServerName,
  495    pub source_worktree_id: WorktreeId,
  496    pub path: ProjectPath,
  497    pub name: String,
  498    pub kind: lsp::SymbolKind,
  499    pub range: Range<Unclipped<PointUtf16>>,
  500    pub signature: [u8; 32],
  501}
  502
  503#[derive(Clone, Debug, PartialEq)]
  504pub struct HoverBlock {
  505    pub text: String,
  506    pub kind: HoverBlockKind,
  507}
  508
  509#[derive(Clone, Debug, PartialEq, Eq)]
  510pub enum HoverBlockKind {
  511    PlainText,
  512    Markdown,
  513    Code { language: String },
  514}
  515
  516#[derive(Debug, Clone)]
  517pub struct Hover {
  518    pub contents: Vec<HoverBlock>,
  519    pub range: Option<Range<language::Anchor>>,
  520    pub language: Option<Arc<Language>>,
  521}
  522
  523impl Hover {
  524    pub fn is_empty(&self) -> bool {
  525        self.contents.iter().all(|block| block.text.is_empty())
  526    }
  527}
  528
  529#[derive(Default)]
  530pub struct ProjectTransaction(pub HashMap<Model<Buffer>, language::Transaction>);
  531
  532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  533pub enum FormatTrigger {
  534    Save,
  535    Manual,
  536}
  537
  538// Currently, formatting operations are represented differently depending on
  539// whether they come from a language server or an external command.
  540enum FormatOperation {
  541    Lsp(Vec<(Range<Anchor>, String)>),
  542    External(Diff),
  543    Prettier(Diff),
  544}
  545
  546impl FormatTrigger {
  547    fn from_proto(value: i32) -> FormatTrigger {
  548        match value {
  549            0 => FormatTrigger::Save,
  550            1 => FormatTrigger::Manual,
  551            _ => FormatTrigger::Save,
  552        }
  553    }
  554}
  555
  556#[derive(Clone, Debug, PartialEq)]
  557enum SearchMatchCandidate {
  558    OpenBuffer {
  559        buffer: Model<Buffer>,
  560        // This might be an unnamed file without representation on filesystem
  561        path: Option<Arc<Path>>,
  562    },
  563    Path {
  564        worktree_id: WorktreeId,
  565        is_ignored: bool,
  566        path: Arc<Path>,
  567    },
  568}
  569
  570impl SearchMatchCandidate {
  571    fn path(&self) -> Option<Arc<Path>> {
  572        match self {
  573            SearchMatchCandidate::OpenBuffer { path, .. } => path.clone(),
  574            SearchMatchCandidate::Path { path, .. } => Some(path.clone()),
  575        }
  576    }
  577
  578    fn is_ignored(&self) -> bool {
  579        matches!(
  580            self,
  581            SearchMatchCandidate::Path {
  582                is_ignored: true,
  583                ..
  584            }
  585        )
  586    }
  587}
  588
  589pub enum SearchResult {
  590    Buffer {
  591        buffer: Model<Buffer>,
  592        ranges: Vec<Range<Anchor>>,
  593    },
  594    LimitReached,
  595}
  596
  597impl Project {
  598    pub fn init_settings(cx: &mut AppContext) {
  599        WorktreeSettings::register(cx);
  600        ProjectSettings::register(cx);
  601    }
  602
  603    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
  604        connection_manager::init(client.clone(), cx);
  605        Self::init_settings(cx);
  606
  607        client.add_model_message_handler(Self::handle_add_collaborator);
  608        client.add_model_message_handler(Self::handle_update_project_collaborator);
  609        client.add_model_message_handler(Self::handle_remove_collaborator);
  610        client.add_model_message_handler(Self::handle_buffer_reloaded);
  611        client.add_model_message_handler(Self::handle_buffer_saved);
  612        client.add_model_message_handler(Self::handle_start_language_server);
  613        client.add_model_message_handler(Self::handle_update_language_server);
  614        client.add_model_message_handler(Self::handle_update_project);
  615        client.add_model_message_handler(Self::handle_unshare_project);
  616        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
  617        client.add_model_message_handler(Self::handle_update_buffer_file);
  618        client.add_model_request_handler(Self::handle_update_buffer);
  619        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
  620        client.add_model_message_handler(Self::handle_update_worktree);
  621        client.add_model_message_handler(Self::handle_update_worktree_settings);
  622        client.add_model_request_handler(Self::handle_create_project_entry);
  623        client.add_model_request_handler(Self::handle_rename_project_entry);
  624        client.add_model_request_handler(Self::handle_copy_project_entry);
  625        client.add_model_request_handler(Self::handle_delete_project_entry);
  626        client.add_model_request_handler(Self::handle_expand_project_entry);
  627        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
  628        client.add_model_request_handler(Self::handle_resolve_completion_documentation);
  629        client.add_model_request_handler(Self::handle_apply_code_action);
  630        client.add_model_request_handler(Self::handle_on_type_formatting);
  631        client.add_model_request_handler(Self::handle_inlay_hints);
  632        client.add_model_request_handler(Self::handle_resolve_inlay_hint);
  633        client.add_model_request_handler(Self::handle_refresh_inlay_hints);
  634        client.add_model_request_handler(Self::handle_reload_buffers);
  635        client.add_model_request_handler(Self::handle_synchronize_buffers);
  636        client.add_model_request_handler(Self::handle_format_buffers);
  637        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
  638        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
  639        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
  640        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
  641        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
  642        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
  643        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
  644        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
  645        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
  646        client.add_model_request_handler(Self::handle_search_project);
  647        client.add_model_request_handler(Self::handle_get_project_symbols);
  648        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
  649        client.add_model_request_handler(Self::handle_open_buffer_by_id);
  650        client.add_model_request_handler(Self::handle_open_buffer_by_path);
  651        client.add_model_request_handler(Self::handle_save_buffer);
  652        client.add_model_message_handler(Self::handle_update_diff_base);
  653        client.add_model_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
  654        client.add_model_request_handler(Self::handle_blame_buffer);
  655        client.add_model_request_handler(Self::handle_multi_lsp_query);
  656    }
  657
  658    pub fn local(
  659        client: Arc<Client>,
  660        node: Arc<dyn NodeRuntime>,
  661        user_store: Model<UserStore>,
  662        languages: Arc<LanguageRegistry>,
  663        fs: Arc<dyn Fs>,
  664        cx: &mut AppContext,
  665    ) -> Model<Self> {
  666        cx.new_model(|cx: &mut ModelContext<Self>| {
  667            let (tx, rx) = mpsc::unbounded();
  668            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
  669                .detach();
  670            let copilot_lsp_subscription =
  671                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
  672            let tasks = Inventory::new(cx);
  673
  674            Self {
  675                worktrees: Vec::new(),
  676                buffer_ordered_messages_tx: tx,
  677                flush_language_server_update: None,
  678                pending_language_server_update: None,
  679                collaborators: Default::default(),
  680                opened_buffers: Default::default(),
  681                shared_buffers: Default::default(),
  682                loading_buffers_by_path: Default::default(),
  683                loading_local_worktrees: Default::default(),
  684                local_buffer_ids_by_path: Default::default(),
  685                local_buffer_ids_by_entry_id: Default::default(),
  686                buffer_snapshots: Default::default(),
  687                join_project_response_message_id: 0,
  688                client_state: ProjectClientState::Local,
  689                loading_buffers: HashMap::default(),
  690                incomplete_remote_buffers: HashMap::default(),
  691                client_subscriptions: Vec::new(),
  692                _subscriptions: vec![
  693                    cx.observe_global::<SettingsStore>(Self::on_settings_changed),
  694                    cx.on_release(Self::release),
  695                    cx.on_app_quit(Self::shutdown_language_servers),
  696                ],
  697                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
  698                _maintain_workspace_config: Self::maintain_workspace_config(cx),
  699                active_entry: None,
  700                languages,
  701                client,
  702                user_store,
  703                fs,
  704                next_entry_id: Default::default(),
  705                next_diagnostic_group_id: Default::default(),
  706                supplementary_language_servers: HashMap::default(),
  707                language_servers: Default::default(),
  708                language_server_ids: HashMap::default(),
  709                language_server_statuses: Default::default(),
  710                last_formatting_failure: None,
  711                last_workspace_edits_by_language_server: Default::default(),
  712                language_server_watched_paths: HashMap::default(),
  713                buffers_being_formatted: Default::default(),
  714                buffers_needing_diff: Default::default(),
  715                git_diff_debouncer: DebouncedDelay::new(),
  716                nonce: StdRng::from_entropy().gen(),
  717                terminals: Terminals {
  718                    local_handles: Vec::new(),
  719                },
  720                copilot_lsp_subscription,
  721                copilot_log_subscription: None,
  722                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
  723                node: Some(node),
  724                default_prettier: DefaultPrettier::default(),
  725                prettiers_per_worktree: HashMap::default(),
  726                prettier_instances: HashMap::default(),
  727                tasks,
  728                hosted_project_id: None,
  729                remote_project_id: None,
  730                search_history: Self::new_search_history(),
  731            }
  732        })
  733    }
  734
  735    pub async fn remote(
  736        remote_id: u64,
  737        client: Arc<Client>,
  738        user_store: Model<UserStore>,
  739        languages: Arc<LanguageRegistry>,
  740        fs: Arc<dyn Fs>,
  741        cx: AsyncAppContext,
  742    ) -> Result<Model<Self>> {
  743        let project =
  744            Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
  745        cx.update(|cx| {
  746            connection_manager::Manager::global(cx).update(cx, |manager, cx| {
  747                manager.maintain_project_connection(&project, cx)
  748            })
  749        })?;
  750        Ok(project)
  751    }
  752
  753    pub async fn in_room(
  754        remote_id: u64,
  755        client: Arc<Client>,
  756        user_store: Model<UserStore>,
  757        languages: Arc<LanguageRegistry>,
  758        fs: Arc<dyn Fs>,
  759        cx: AsyncAppContext,
  760    ) -> Result<Model<Self>> {
  761        client.authenticate_and_connect(true, &cx).await?;
  762
  763        let subscription = client.subscribe_to_entity(remote_id)?;
  764        let response = client
  765            .request_envelope(proto::JoinProject {
  766                project_id: remote_id,
  767            })
  768            .await?;
  769        Self::from_join_project_response(
  770            response,
  771            subscription,
  772            client,
  773            user_store,
  774            languages,
  775            fs,
  776            cx,
  777        )
  778        .await
  779    }
  780
  781    async fn from_join_project_response(
  782        response: TypedEnvelope<proto::JoinProjectResponse>,
  783        subscription: PendingEntitySubscription<Project>,
  784        client: Arc<Client>,
  785        user_store: Model<UserStore>,
  786        languages: Arc<LanguageRegistry>,
  787        fs: Arc<dyn Fs>,
  788        mut cx: AsyncAppContext,
  789    ) -> Result<Model<Self>> {
  790        let remote_id = response.payload.project_id;
  791        let role = response.payload.role();
  792        let this = cx.new_model(|cx| {
  793            let replica_id = response.payload.replica_id as ReplicaId;
  794            let tasks = Inventory::new(cx);
  795            // BIG CAUTION NOTE: The order in which we initialize fields here matters and it should match what's done in Self::local.
  796            // Otherwise, you might run into issues where worktree id on remote is different than what's on local host.
  797            // That's because Worktree's identifier is entity id, which should probably be changed.
  798            let mut worktrees = Vec::new();
  799            for worktree in response.payload.worktrees {
  800                let worktree =
  801                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
  802                worktrees.push(worktree);
  803            }
  804
  805            let (tx, rx) = mpsc::unbounded();
  806            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
  807                .detach();
  808            let copilot_lsp_subscription =
  809                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
  810            let mut this = Self {
  811                worktrees: Vec::new(),
  812                buffer_ordered_messages_tx: tx,
  813                pending_language_server_update: None,
  814                flush_language_server_update: None,
  815                loading_buffers_by_path: Default::default(),
  816                loading_buffers: Default::default(),
  817                shared_buffers: Default::default(),
  818                incomplete_remote_buffers: Default::default(),
  819                loading_local_worktrees: Default::default(),
  820                local_buffer_ids_by_path: Default::default(),
  821                local_buffer_ids_by_entry_id: Default::default(),
  822                active_entry: None,
  823                collaborators: Default::default(),
  824                join_project_response_message_id: response.message_id,
  825                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
  826                _maintain_workspace_config: Self::maintain_workspace_config(cx),
  827                languages,
  828                user_store: user_store.clone(),
  829                fs,
  830                next_entry_id: Default::default(),
  831                next_diagnostic_group_id: Default::default(),
  832                client_subscriptions: Default::default(),
  833                _subscriptions: vec![
  834                    cx.on_release(Self::release),
  835                    cx.on_app_quit(Self::shutdown_language_servers),
  836                ],
  837                client: client.clone(),
  838                client_state: ProjectClientState::Remote {
  839                    sharing_has_stopped: false,
  840                    capability: Capability::ReadWrite,
  841                    remote_id,
  842                    replica_id,
  843                    in_room: response.payload.remote_project_id.is_none(),
  844                },
  845                supplementary_language_servers: HashMap::default(),
  846                language_servers: Default::default(),
  847                language_server_ids: HashMap::default(),
  848                language_server_statuses: response
  849                    .payload
  850                    .language_servers
  851                    .into_iter()
  852                    .map(|server| {
  853                        (
  854                            LanguageServerId(server.id as usize),
  855                            LanguageServerStatus {
  856                                name: server.name,
  857                                pending_work: Default::default(),
  858                                has_pending_diagnostic_updates: false,
  859                                progress_tokens: Default::default(),
  860                            },
  861                        )
  862                    })
  863                    .collect(),
  864                last_formatting_failure: None,
  865                last_workspace_edits_by_language_server: Default::default(),
  866                language_server_watched_paths: HashMap::default(),
  867                opened_buffers: Default::default(),
  868                buffers_being_formatted: Default::default(),
  869                buffers_needing_diff: Default::default(),
  870                git_diff_debouncer: DebouncedDelay::new(),
  871                buffer_snapshots: Default::default(),
  872                nonce: StdRng::from_entropy().gen(),
  873                terminals: Terminals {
  874                    local_handles: Vec::new(),
  875                },
  876                copilot_lsp_subscription,
  877                copilot_log_subscription: None,
  878                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
  879                node: None,
  880                default_prettier: DefaultPrettier::default(),
  881                prettiers_per_worktree: HashMap::default(),
  882                prettier_instances: HashMap::default(),
  883                tasks,
  884                hosted_project_id: None,
  885                remote_project_id: response
  886                    .payload
  887                    .remote_project_id
  888                    .map(|remote_project_id| RemoteProjectId(remote_project_id)),
  889                search_history: Self::new_search_history(),
  890            };
  891            this.set_role(role, cx);
  892            for worktree in worktrees {
  893                let _ = this.add_worktree(&worktree, cx);
  894            }
  895            this
  896        })?;
  897        let subscription = subscription.set_model(&this, &mut cx);
  898
  899        let user_ids = response
  900            .payload
  901            .collaborators
  902            .iter()
  903            .map(|peer| peer.user_id)
  904            .collect();
  905        user_store
  906            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
  907            .await?;
  908
  909        this.update(&mut cx, |this, cx| {
  910            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
  911            this.client_subscriptions.push(subscription);
  912            anyhow::Ok(())
  913        })??;
  914
  915        Ok(this)
  916    }
  917
  918    pub async fn hosted(
  919        remote_id: ProjectId,
  920        user_store: Model<UserStore>,
  921        client: Arc<Client>,
  922        languages: Arc<LanguageRegistry>,
  923        fs: Arc<dyn Fs>,
  924        cx: AsyncAppContext,
  925    ) -> Result<Model<Self>> {
  926        client.authenticate_and_connect(true, &cx).await?;
  927
  928        let subscription = client.subscribe_to_entity(remote_id.0)?;
  929        let response = client
  930            .request_envelope(proto::JoinHostedProject {
  931                project_id: remote_id.0,
  932            })
  933            .await?;
  934        Self::from_join_project_response(
  935            response,
  936            subscription,
  937            client,
  938            user_store,
  939            languages,
  940            fs,
  941            cx,
  942        )
  943        .await
  944    }
  945
  946    fn new_search_history() -> SearchHistory {
  947        SearchHistory::new(
  948            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
  949            search_history::QueryInsertionBehavior::AlwaysInsert,
  950        )
  951    }
  952
  953    fn release(&mut self, cx: &mut AppContext) {
  954        match &self.client_state {
  955            ProjectClientState::Local => {}
  956            ProjectClientState::Shared { .. } => {
  957                let _ = self.unshare_internal(cx);
  958            }
  959            ProjectClientState::Remote { remote_id, .. } => {
  960                let _ = self.client.send(proto::LeaveProject {
  961                    project_id: *remote_id,
  962                });
  963                self.disconnected_from_host_internal(cx);
  964            }
  965        }
  966    }
  967
  968    fn shutdown_language_servers(
  969        &mut self,
  970        _cx: &mut ModelContext<Self>,
  971    ) -> impl Future<Output = ()> {
  972        let shutdown_futures = self
  973            .language_servers
  974            .drain()
  975            .map(|(_, server_state)| async {
  976                use LanguageServerState::*;
  977                match server_state {
  978                    Running { server, .. } => server.shutdown()?.await,
  979                    Starting(task) => task.await?.shutdown()?.await,
  980                }
  981            })
  982            .collect::<Vec<_>>();
  983
  984        async move {
  985            futures::future::join_all(shutdown_futures).await;
  986        }
  987    }
  988
  989    #[cfg(any(test, feature = "test-support"))]
  990    pub async fn example(
  991        root_paths: impl IntoIterator<Item = &Path>,
  992        cx: &mut AsyncAppContext,
  993    ) -> Model<Project> {
  994        use clock::FakeSystemClock;
  995
  996        let fs = Arc::new(RealFs::default());
  997        let languages = LanguageRegistry::test(cx.background_executor().clone());
  998        let clock = Arc::new(FakeSystemClock::default());
  999        let http_client = util::http::FakeHttpClient::with_404_response();
 1000        let client = cx
 1001            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
 1002            .unwrap();
 1003        let user_store = cx
 1004            .new_model(|cx| UserStore::new(client.clone(), cx))
 1005            .unwrap();
 1006        let project = cx
 1007            .update(|cx| {
 1008                Project::local(
 1009                    client,
 1010                    node_runtime::FakeNodeRuntime::new(),
 1011                    user_store,
 1012                    Arc::new(languages),
 1013                    fs,
 1014                    cx,
 1015                )
 1016            })
 1017            .unwrap();
 1018        for path in root_paths {
 1019            let (tree, _) = project
 1020                .update(cx, |project, cx| {
 1021                    project.find_or_create_local_worktree(path, true, cx)
 1022                })
 1023                .unwrap()
 1024                .await
 1025                .unwrap();
 1026            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 1027                .unwrap()
 1028                .await;
 1029        }
 1030        project
 1031    }
 1032
 1033    #[cfg(any(test, feature = "test-support"))]
 1034    pub async fn test(
 1035        fs: Arc<dyn Fs>,
 1036        root_paths: impl IntoIterator<Item = &Path>,
 1037        cx: &mut gpui::TestAppContext,
 1038    ) -> Model<Project> {
 1039        use clock::FakeSystemClock;
 1040
 1041        let languages = LanguageRegistry::test(cx.executor());
 1042        let clock = Arc::new(FakeSystemClock::default());
 1043        let http_client = util::http::FakeHttpClient::with_404_response();
 1044        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
 1045        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
 1046        let project = cx.update(|cx| {
 1047            Project::local(
 1048                client,
 1049                node_runtime::FakeNodeRuntime::new(),
 1050                user_store,
 1051                Arc::new(languages),
 1052                fs,
 1053                cx,
 1054            )
 1055        });
 1056        for path in root_paths {
 1057            let (tree, _) = project
 1058                .update(cx, |project, cx| {
 1059                    project.find_or_create_local_worktree(path, true, cx)
 1060                })
 1061                .await
 1062                .unwrap();
 1063            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 1064                .await;
 1065        }
 1066        project
 1067    }
 1068
 1069    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 1070        let mut language_servers_to_start = Vec::new();
 1071        let mut language_formatters_to_check = Vec::new();
 1072        for buffer in self.opened_buffers.values() {
 1073            if let Some(buffer) = buffer.upgrade() {
 1074                let buffer = buffer.read(cx);
 1075                let buffer_file = File::from_dyn(buffer.file());
 1076                let buffer_language = buffer.language();
 1077                let settings = language_settings(buffer_language, buffer.file(), cx);
 1078                if let Some(language) = buffer_language {
 1079                    if settings.enable_language_server {
 1080                        if let Some(file) = buffer_file {
 1081                            language_servers_to_start
 1082                                .push((file.worktree.clone(), Arc::clone(language)));
 1083                        }
 1084                    }
 1085                    language_formatters_to_check.push((
 1086                        buffer_file.map(|f| f.worktree_id(cx)),
 1087                        Arc::clone(language),
 1088                        settings.clone(),
 1089                    ));
 1090                }
 1091            }
 1092        }
 1093
 1094        let mut language_servers_to_stop = Vec::new();
 1095        let mut language_servers_to_restart = Vec::new();
 1096        let languages = self.languages.to_vec();
 1097
 1098        let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
 1099        let current_lsp_settings = &self.current_lsp_settings;
 1100        for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 1101            let language = languages.iter().find_map(|l| {
 1102                let adapter = self
 1103                    .languages
 1104                    .lsp_adapters(l)
 1105                    .iter()
 1106                    .find(|adapter| &adapter.name == started_lsp_name)?
 1107                    .clone();
 1108                Some((l, adapter))
 1109            });
 1110            if let Some((language, adapter)) = language {
 1111                let worktree = self.worktree_for_id(*worktree_id, cx);
 1112                let file = worktree.as_ref().and_then(|tree| {
 1113                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
 1114                });
 1115                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
 1116                    language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 1117                } else if let Some(worktree) = worktree {
 1118                    let server_name = &adapter.name.0;
 1119                    match (
 1120                        current_lsp_settings.get(server_name),
 1121                        new_lsp_settings.get(server_name),
 1122                    ) {
 1123                        (None, None) => {}
 1124                        (Some(_), None) | (None, Some(_)) => {
 1125                            language_servers_to_restart.push((worktree, Arc::clone(language)));
 1126                        }
 1127                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
 1128                            if current_lsp_settings != new_lsp_settings {
 1129                                language_servers_to_restart.push((worktree, Arc::clone(language)));
 1130                            }
 1131                        }
 1132                    }
 1133                }
 1134            }
 1135        }
 1136        self.current_lsp_settings = new_lsp_settings;
 1137
 1138        // Stop all newly-disabled language servers.
 1139        for (worktree_id, adapter_name) in language_servers_to_stop {
 1140            self.stop_language_server(worktree_id, adapter_name, cx)
 1141                .detach();
 1142        }
 1143
 1144        let mut prettier_plugins_by_worktree = HashMap::default();
 1145        for (worktree, language, settings) in language_formatters_to_check {
 1146            if let Some(plugins) =
 1147                prettier_support::prettier_plugins_for_language(&language, &settings)
 1148            {
 1149                prettier_plugins_by_worktree
 1150                    .entry(worktree)
 1151                    .or_insert_with(|| HashSet::default())
 1152                    .extend(plugins.iter().cloned());
 1153            }
 1154        }
 1155        for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
 1156            self.install_default_prettier(worktree, prettier_plugins.into_iter(), cx);
 1157        }
 1158
 1159        // Start all the newly-enabled language servers.
 1160        for (worktree, language) in language_servers_to_start {
 1161            self.start_language_servers(&worktree, language, cx);
 1162        }
 1163
 1164        // Restart all language servers with changed initialization options.
 1165        for (worktree, language) in language_servers_to_restart {
 1166            self.restart_language_servers(worktree, language, cx);
 1167        }
 1168
 1169        if self.copilot_lsp_subscription.is_none() {
 1170            if let Some(copilot) = Copilot::global(cx) {
 1171                for buffer in self.opened_buffers.values() {
 1172                    if let Some(buffer) = buffer.upgrade() {
 1173                        self.register_buffer_with_copilot(&buffer, cx);
 1174                    }
 1175                }
 1176                self.copilot_lsp_subscription = Some(subscribe_for_copilot_events(&copilot, cx));
 1177            }
 1178        }
 1179
 1180        cx.notify();
 1181    }
 1182
 1183    pub fn buffer_for_id(&self, remote_id: BufferId) -> Option<Model<Buffer>> {
 1184        self.opened_buffers
 1185            .get(&remote_id)
 1186            .and_then(|buffer| buffer.upgrade())
 1187    }
 1188
 1189    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 1190        &self.languages
 1191    }
 1192
 1193    pub fn client(&self) -> Arc<Client> {
 1194        self.client.clone()
 1195    }
 1196
 1197    pub fn user_store(&self) -> Model<UserStore> {
 1198        self.user_store.clone()
 1199    }
 1200
 1201    pub fn node_runtime(&self) -> Option<&Arc<dyn NodeRuntime>> {
 1202        self.node.as_ref()
 1203    }
 1204
 1205    pub fn opened_buffers(&self) -> Vec<Model<Buffer>> {
 1206        self.opened_buffers
 1207            .values()
 1208            .filter_map(|b| b.upgrade())
 1209            .collect()
 1210    }
 1211
 1212    #[cfg(any(test, feature = "test-support"))]
 1213    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 1214        let path = path.into();
 1215        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 1216            self.opened_buffers.iter().any(|(_, buffer)| {
 1217                if let Some(buffer) = buffer.upgrade() {
 1218                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 1219                        if file.worktree == worktree && file.path() == &path.path {
 1220                            return true;
 1221                        }
 1222                    }
 1223                }
 1224                false
 1225            })
 1226        } else {
 1227            false
 1228        }
 1229    }
 1230
 1231    pub fn fs(&self) -> &Arc<dyn Fs> {
 1232        &self.fs
 1233    }
 1234
 1235    pub fn remote_id(&self) -> Option<u64> {
 1236        match self.client_state {
 1237            ProjectClientState::Local => None,
 1238            ProjectClientState::Shared { remote_id, .. }
 1239            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
 1240        }
 1241    }
 1242
 1243    pub fn hosted_project_id(&self) -> Option<ProjectId> {
 1244        self.hosted_project_id
 1245    }
 1246
 1247    pub fn remote_project_id(&self) -> Option<RemoteProjectId> {
 1248        self.remote_project_id
 1249    }
 1250
 1251    pub fn replica_id(&self) -> ReplicaId {
 1252        match self.client_state {
 1253            ProjectClientState::Remote { replica_id, .. } => replica_id,
 1254            _ => 0,
 1255        }
 1256    }
 1257
 1258    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
 1259        if let ProjectClientState::Shared { updates_tx, .. } = &mut self.client_state {
 1260            updates_tx
 1261                .unbounded_send(LocalProjectUpdate::WorktreesChanged)
 1262                .ok();
 1263        }
 1264        cx.notify();
 1265    }
 1266
 1267    pub fn task_inventory(&self) -> &Model<Inventory> {
 1268        &self.tasks
 1269    }
 1270
 1271    pub fn search_history(&self) -> &SearchHistory {
 1272        &self.search_history
 1273    }
 1274
 1275    pub fn search_history_mut(&mut self) -> &mut SearchHistory {
 1276        &mut self.search_history
 1277    }
 1278
 1279    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
 1280        &self.collaborators
 1281    }
 1282
 1283    pub fn host(&self) -> Option<&Collaborator> {
 1284        self.collaborators.values().find(|c| c.replica_id == 0)
 1285    }
 1286
 1287    /// Collect all worktrees, including ones that don't appear in the project panel
 1288    pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Model<Worktree>> {
 1289        self.worktrees
 1290            .iter()
 1291            .filter_map(move |worktree| worktree.upgrade())
 1292    }
 1293
 1294    /// Collect all user-visible worktrees, the ones that appear in the project panel
 1295    pub fn visible_worktrees<'a>(
 1296        &'a self,
 1297        cx: &'a AppContext,
 1298    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
 1299        self.worktrees.iter().filter_map(|worktree| {
 1300            worktree.upgrade().and_then(|worktree| {
 1301                if worktree.read(cx).is_visible() {
 1302                    Some(worktree)
 1303                } else {
 1304                    None
 1305                }
 1306            })
 1307        })
 1308    }
 1309
 1310    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
 1311        self.visible_worktrees(cx)
 1312            .map(|tree| tree.read(cx).root_name())
 1313    }
 1314
 1315    pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
 1316        self.worktrees()
 1317            .find(|worktree| worktree.read(cx).id() == id)
 1318    }
 1319
 1320    pub fn worktree_for_entry(
 1321        &self,
 1322        entry_id: ProjectEntryId,
 1323        cx: &AppContext,
 1324    ) -> Option<Model<Worktree>> {
 1325        self.worktrees()
 1326            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 1327    }
 1328
 1329    pub fn worktree_id_for_entry(
 1330        &self,
 1331        entry_id: ProjectEntryId,
 1332        cx: &AppContext,
 1333    ) -> Option<WorktreeId> {
 1334        self.worktree_for_entry(entry_id, cx)
 1335            .map(|worktree| worktree.read(cx).id())
 1336    }
 1337
 1338    pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
 1339        paths
 1340            .iter()
 1341            .map(|path| self.visibility_for_path(path, cx))
 1342            .max()
 1343            .flatten()
 1344    }
 1345
 1346    pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
 1347        self.worktrees()
 1348            .filter_map(|worktree| {
 1349                let worktree = worktree.read(cx);
 1350                worktree
 1351                    .as_local()?
 1352                    .contains_abs_path(path)
 1353                    .then(|| worktree.is_visible())
 1354            })
 1355            .max()
 1356    }
 1357
 1358    pub fn create_entry(
 1359        &mut self,
 1360        project_path: impl Into<ProjectPath>,
 1361        is_directory: bool,
 1362        cx: &mut ModelContext<Self>,
 1363    ) -> Task<Result<Option<Entry>>> {
 1364        let project_path = project_path.into();
 1365        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
 1366            return Task::ready(Ok(None));
 1367        };
 1368        if self.is_local() {
 1369            worktree.update(cx, |worktree, cx| {
 1370                worktree
 1371                    .as_local_mut()
 1372                    .unwrap()
 1373                    .create_entry(project_path.path, is_directory, cx)
 1374            })
 1375        } else {
 1376            let client = self.client.clone();
 1377            let project_id = self.remote_id().unwrap();
 1378            cx.spawn(move |_, mut cx| async move {
 1379                let response = client
 1380                    .request(proto::CreateProjectEntry {
 1381                        worktree_id: project_path.worktree_id.to_proto(),
 1382                        project_id,
 1383                        path: project_path.path.to_string_lossy().into(),
 1384                        is_directory,
 1385                    })
 1386                    .await?;
 1387                match response.entry {
 1388                    Some(entry) => worktree
 1389                        .update(&mut cx, |worktree, cx| {
 1390                            worktree.as_remote_mut().unwrap().insert_entry(
 1391                                entry,
 1392                                response.worktree_scan_id as usize,
 1393                                cx,
 1394                            )
 1395                        })?
 1396                        .await
 1397                        .map(Some),
 1398                    None => Ok(None),
 1399                }
 1400            })
 1401        }
 1402    }
 1403
 1404    pub fn copy_entry(
 1405        &mut self,
 1406        entry_id: ProjectEntryId,
 1407        new_path: impl Into<Arc<Path>>,
 1408        cx: &mut ModelContext<Self>,
 1409    ) -> Task<Result<Option<Entry>>> {
 1410        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
 1411            return Task::ready(Ok(None));
 1412        };
 1413        let new_path = new_path.into();
 1414        if self.is_local() {
 1415            worktree.update(cx, |worktree, cx| {
 1416                worktree
 1417                    .as_local_mut()
 1418                    .unwrap()
 1419                    .copy_entry(entry_id, new_path, cx)
 1420            })
 1421        } else {
 1422            let client = self.client.clone();
 1423            let project_id = self.remote_id().unwrap();
 1424
 1425            cx.spawn(move |_, mut cx| async move {
 1426                let response = client
 1427                    .request(proto::CopyProjectEntry {
 1428                        project_id,
 1429                        entry_id: entry_id.to_proto(),
 1430                        new_path: new_path.to_string_lossy().into(),
 1431                    })
 1432                    .await?;
 1433                match response.entry {
 1434                    Some(entry) => worktree
 1435                        .update(&mut cx, |worktree, cx| {
 1436                            worktree.as_remote_mut().unwrap().insert_entry(
 1437                                entry,
 1438                                response.worktree_scan_id as usize,
 1439                                cx,
 1440                            )
 1441                        })?
 1442                        .await
 1443                        .map(Some),
 1444                    None => Ok(None),
 1445                }
 1446            })
 1447        }
 1448    }
 1449
 1450    pub fn rename_entry(
 1451        &mut self,
 1452        entry_id: ProjectEntryId,
 1453        new_path: impl Into<Arc<Path>>,
 1454        cx: &mut ModelContext<Self>,
 1455    ) -> Task<Result<Option<Entry>>> {
 1456        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
 1457            return Task::ready(Ok(None));
 1458        };
 1459        let new_path = new_path.into();
 1460        if self.is_local() {
 1461            worktree.update(cx, |worktree, cx| {
 1462                worktree
 1463                    .as_local_mut()
 1464                    .unwrap()
 1465                    .rename_entry(entry_id, new_path, cx)
 1466            })
 1467        } else {
 1468            let client = self.client.clone();
 1469            let project_id = self.remote_id().unwrap();
 1470
 1471            cx.spawn(move |_, mut cx| async move {
 1472                let response = client
 1473                    .request(proto::RenameProjectEntry {
 1474                        project_id,
 1475                        entry_id: entry_id.to_proto(),
 1476                        new_path: new_path.to_string_lossy().into(),
 1477                    })
 1478                    .await?;
 1479                match response.entry {
 1480                    Some(entry) => worktree
 1481                        .update(&mut cx, |worktree, cx| {
 1482                            worktree.as_remote_mut().unwrap().insert_entry(
 1483                                entry,
 1484                                response.worktree_scan_id as usize,
 1485                                cx,
 1486                            )
 1487                        })?
 1488                        .await
 1489                        .map(Some),
 1490                    None => Ok(None),
 1491                }
 1492            })
 1493        }
 1494    }
 1495
 1496    pub fn delete_entry(
 1497        &mut self,
 1498        entry_id: ProjectEntryId,
 1499        cx: &mut ModelContext<Self>,
 1500    ) -> Option<Task<Result<()>>> {
 1501        let worktree = self.worktree_for_entry(entry_id, cx)?;
 1502
 1503        cx.emit(Event::DeletedEntry(entry_id));
 1504
 1505        if self.is_local() {
 1506            worktree.update(cx, |worktree, cx| {
 1507                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
 1508            })
 1509        } else {
 1510            let client = self.client.clone();
 1511            let project_id = self.remote_id().unwrap();
 1512            Some(cx.spawn(move |_, mut cx| async move {
 1513                let response = client
 1514                    .request(proto::DeleteProjectEntry {
 1515                        project_id,
 1516                        entry_id: entry_id.to_proto(),
 1517                    })
 1518                    .await?;
 1519                worktree
 1520                    .update(&mut cx, move |worktree, cx| {
 1521                        worktree.as_remote_mut().unwrap().delete_entry(
 1522                            entry_id,
 1523                            response.worktree_scan_id as usize,
 1524                            cx,
 1525                        )
 1526                    })?
 1527                    .await
 1528            }))
 1529        }
 1530    }
 1531
 1532    pub fn expand_entry(
 1533        &mut self,
 1534        worktree_id: WorktreeId,
 1535        entry_id: ProjectEntryId,
 1536        cx: &mut ModelContext<Self>,
 1537    ) -> Option<Task<Result<()>>> {
 1538        let worktree = self.worktree_for_id(worktree_id, cx)?;
 1539        if self.is_local() {
 1540            worktree.update(cx, |worktree, cx| {
 1541                worktree.as_local_mut().unwrap().expand_entry(entry_id, cx)
 1542            })
 1543        } else {
 1544            let worktree = worktree.downgrade();
 1545            let request = self.client.request(proto::ExpandProjectEntry {
 1546                project_id: self.remote_id().unwrap(),
 1547                entry_id: entry_id.to_proto(),
 1548            });
 1549            Some(cx.spawn(move |_, mut cx| async move {
 1550                let response = request.await?;
 1551                if let Some(worktree) = worktree.upgrade() {
 1552                    worktree
 1553                        .update(&mut cx, |worktree, _| {
 1554                            worktree
 1555                                .as_remote_mut()
 1556                                .unwrap()
 1557                                .wait_for_snapshot(response.worktree_scan_id as usize)
 1558                        })?
 1559                        .await?;
 1560                }
 1561                Ok(())
 1562            }))
 1563        }
 1564    }
 1565
 1566    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
 1567        if !matches!(self.client_state, ProjectClientState::Local) {
 1568            if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
 1569                if *in_room || self.remote_project_id.is_none() {
 1570                    return Err(anyhow!("project was already shared"));
 1571                } else {
 1572                    *in_room = true;
 1573                    return Ok(());
 1574                }
 1575            } else {
 1576                return Err(anyhow!("project was already shared"));
 1577            }
 1578        }
 1579        self.client_subscriptions.push(
 1580            self.client
 1581                .subscribe_to_entity(project_id)?
 1582                .set_model(&cx.handle(), &mut cx.to_async()),
 1583        );
 1584
 1585        for open_buffer in self.opened_buffers.values_mut() {
 1586            match open_buffer {
 1587                OpenBuffer::Strong(_) => {}
 1588                OpenBuffer::Weak(buffer) => {
 1589                    if let Some(buffer) = buffer.upgrade() {
 1590                        *open_buffer = OpenBuffer::Strong(buffer);
 1591                    }
 1592                }
 1593                OpenBuffer::Operations(_) => unreachable!(),
 1594            }
 1595        }
 1596
 1597        for worktree_handle in self.worktrees.iter_mut() {
 1598            match worktree_handle {
 1599                WorktreeHandle::Strong(_) => {}
 1600                WorktreeHandle::Weak(worktree) => {
 1601                    if let Some(worktree) = worktree.upgrade() {
 1602                        *worktree_handle = WorktreeHandle::Strong(worktree);
 1603                    }
 1604                }
 1605            }
 1606        }
 1607
 1608        for (server_id, status) in &self.language_server_statuses {
 1609            self.client
 1610                .send(proto::StartLanguageServer {
 1611                    project_id,
 1612                    server: Some(proto::LanguageServer {
 1613                        id: server_id.0 as u64,
 1614                        name: status.name.clone(),
 1615                    }),
 1616                })
 1617                .log_err();
 1618        }
 1619
 1620        let store = cx.global::<SettingsStore>();
 1621        for worktree in self.worktrees() {
 1622            let worktree_id = worktree.read(cx).id().to_proto();
 1623            for (path, content) in store.local_settings(worktree.entity_id().as_u64() as usize) {
 1624                self.client
 1625                    .send(proto::UpdateWorktreeSettings {
 1626                        project_id,
 1627                        worktree_id,
 1628                        path: path.to_string_lossy().into(),
 1629                        content: Some(content),
 1630                    })
 1631                    .log_err();
 1632            }
 1633        }
 1634
 1635        let (updates_tx, mut updates_rx) = mpsc::unbounded();
 1636        let client = self.client.clone();
 1637        self.client_state = ProjectClientState::Shared {
 1638            remote_id: project_id,
 1639            updates_tx,
 1640            _send_updates: cx.spawn(move |this, mut cx| async move {
 1641                while let Some(update) = updates_rx.next().await {
 1642                    match update {
 1643                        LocalProjectUpdate::WorktreesChanged => {
 1644                            let worktrees = this.update(&mut cx, |this, _cx| {
 1645                                this.worktrees().collect::<Vec<_>>()
 1646                            })?;
 1647                            let update_project = this
 1648                                .update(&mut cx, |this, cx| {
 1649                                    this.client.request(proto::UpdateProject {
 1650                                        project_id,
 1651                                        worktrees: this.worktree_metadata_protos(cx),
 1652                                    })
 1653                                })?
 1654                                .await;
 1655                            if update_project.log_err().is_some() {
 1656                                for worktree in worktrees {
 1657                                    worktree.update(&mut cx, |worktree, cx| {
 1658                                        let worktree = worktree.as_local_mut().unwrap();
 1659                                        worktree.share(project_id, cx).detach_and_log_err(cx)
 1660                                    })?;
 1661                                }
 1662                            }
 1663                        }
 1664                        LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
 1665                            let buffer = this.update(&mut cx, |this, _| {
 1666                                let buffer = this.opened_buffers.get(&buffer_id).unwrap();
 1667                                let shared_buffers =
 1668                                    this.shared_buffers.entry(peer_id).or_default();
 1669                                if shared_buffers.insert(buffer_id) {
 1670                                    if let OpenBuffer::Strong(buffer) = buffer {
 1671                                        Some(buffer.clone())
 1672                                    } else {
 1673                                        None
 1674                                    }
 1675                                } else {
 1676                                    None
 1677                                }
 1678                            })?;
 1679
 1680                            let Some(buffer) = buffer else { continue };
 1681                            let operations =
 1682                                buffer.update(&mut cx, |b, cx| b.serialize_ops(None, cx))?;
 1683                            let operations = operations.await;
 1684                            let state = buffer.update(&mut cx, |buffer, _| buffer.to_proto())?;
 1685
 1686                            let initial_state = proto::CreateBufferForPeer {
 1687                                project_id,
 1688                                peer_id: Some(peer_id),
 1689                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
 1690                            };
 1691                            if client.send(initial_state).log_err().is_some() {
 1692                                let client = client.clone();
 1693                                cx.background_executor()
 1694                                    .spawn(async move {
 1695                                        let mut chunks = split_operations(operations).peekable();
 1696                                        while let Some(chunk) = chunks.next() {
 1697                                            let is_last = chunks.peek().is_none();
 1698                                            client.send(proto::CreateBufferForPeer {
 1699                                                project_id,
 1700                                                peer_id: Some(peer_id),
 1701                                                variant: Some(
 1702                                                    proto::create_buffer_for_peer::Variant::Chunk(
 1703                                                        proto::BufferChunk {
 1704                                                            buffer_id: buffer_id.into(),
 1705                                                            operations: chunk,
 1706                                                            is_last,
 1707                                                        },
 1708                                                    ),
 1709                                                ),
 1710                                            })?;
 1711                                        }
 1712                                        anyhow::Ok(())
 1713                                    })
 1714                                    .await
 1715                                    .log_err();
 1716                            }
 1717                        }
 1718                    }
 1719                }
 1720                Ok(())
 1721            }),
 1722        };
 1723
 1724        self.metadata_changed(cx);
 1725        cx.emit(Event::RemoteIdChanged(Some(project_id)));
 1726        cx.notify();
 1727        Ok(())
 1728    }
 1729
 1730    pub fn reshared(
 1731        &mut self,
 1732        message: proto::ResharedProject,
 1733        cx: &mut ModelContext<Self>,
 1734    ) -> Result<()> {
 1735        self.shared_buffers.clear();
 1736        self.set_collaborators_from_proto(message.collaborators, cx)?;
 1737        self.metadata_changed(cx);
 1738        Ok(())
 1739    }
 1740
 1741    pub fn rejoined(
 1742        &mut self,
 1743        message: proto::RejoinedProject,
 1744        message_id: u32,
 1745        cx: &mut ModelContext<Self>,
 1746    ) -> Result<()> {
 1747        cx.update_global::<SettingsStore, _>(|store, cx| {
 1748            for worktree in &self.worktrees {
 1749                store
 1750                    .clear_local_settings(worktree.handle_id(), cx)
 1751                    .log_err();
 1752            }
 1753        });
 1754
 1755        self.join_project_response_message_id = message_id;
 1756        self.set_worktrees_from_proto(message.worktrees, cx)?;
 1757        self.set_collaborators_from_proto(message.collaborators, cx)?;
 1758        self.language_server_statuses = message
 1759            .language_servers
 1760            .into_iter()
 1761            .map(|server| {
 1762                (
 1763                    LanguageServerId(server.id as usize),
 1764                    LanguageServerStatus {
 1765                        name: server.name,
 1766                        pending_work: Default::default(),
 1767                        has_pending_diagnostic_updates: false,
 1768                        progress_tokens: Default::default(),
 1769                    },
 1770                )
 1771            })
 1772            .collect();
 1773        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 1774            .unwrap();
 1775        cx.notify();
 1776        Ok(())
 1777    }
 1778
 1779    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
 1780        self.unshare_internal(cx)?;
 1781        self.metadata_changed(cx);
 1782        cx.notify();
 1783        Ok(())
 1784    }
 1785
 1786    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
 1787        if self.is_remote() {
 1788            if self.remote_project_id().is_some() {
 1789                if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
 1790                    *in_room = false
 1791                }
 1792                return Ok(());
 1793            } else {
 1794                return Err(anyhow!("attempted to unshare a remote project"));
 1795            }
 1796        }
 1797
 1798        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
 1799            self.client_state = ProjectClientState::Local;
 1800            self.collaborators.clear();
 1801            self.shared_buffers.clear();
 1802            self.client_subscriptions.clear();
 1803
 1804            for worktree_handle in self.worktrees.iter_mut() {
 1805                if let WorktreeHandle::Strong(worktree) = worktree_handle {
 1806                    let is_visible = worktree.update(cx, |worktree, _| {
 1807                        worktree.as_local_mut().unwrap().unshare();
 1808                        worktree.is_visible()
 1809                    });
 1810                    if !is_visible {
 1811                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
 1812                    }
 1813                }
 1814            }
 1815
 1816            for open_buffer in self.opened_buffers.values_mut() {
 1817                // Wake up any tasks waiting for peers' edits to this buffer.
 1818                if let Some(buffer) = open_buffer.upgrade() {
 1819                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
 1820                }
 1821
 1822                if let OpenBuffer::Strong(buffer) = open_buffer {
 1823                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 1824                }
 1825            }
 1826
 1827            self.client.send(proto::UnshareProject {
 1828                project_id: remote_id,
 1829            })?;
 1830
 1831            Ok(())
 1832        } else {
 1833            Err(anyhow!("attempted to unshare an unshared project"))
 1834        }
 1835    }
 1836
 1837    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
 1838        self.disconnected_from_host_internal(cx);
 1839        cx.emit(Event::DisconnectedFromHost);
 1840        cx.notify();
 1841    }
 1842
 1843    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
 1844        let new_capability =
 1845            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
 1846                Capability::ReadWrite
 1847            } else {
 1848                Capability::ReadOnly
 1849            };
 1850        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
 1851            if *capability == new_capability {
 1852                return;
 1853            }
 1854
 1855            *capability = new_capability;
 1856            for buffer in self.opened_buffers() {
 1857                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
 1858            }
 1859        }
 1860    }
 1861
 1862    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
 1863        if let ProjectClientState::Remote {
 1864            sharing_has_stopped,
 1865            ..
 1866        } = &mut self.client_state
 1867        {
 1868            *sharing_has_stopped = true;
 1869
 1870            self.collaborators.clear();
 1871
 1872            for worktree in &self.worktrees {
 1873                if let Some(worktree) = worktree.upgrade() {
 1874                    worktree.update(cx, |worktree, _| {
 1875                        if let Some(worktree) = worktree.as_remote_mut() {
 1876                            worktree.disconnected_from_host();
 1877                        }
 1878                    });
 1879                }
 1880            }
 1881
 1882            for open_buffer in self.opened_buffers.values_mut() {
 1883                // Wake up any tasks waiting for peers' edits to this buffer.
 1884                if let Some(buffer) = open_buffer.upgrade() {
 1885                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
 1886                }
 1887
 1888                if let OpenBuffer::Strong(buffer) = open_buffer {
 1889                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 1890                }
 1891            }
 1892
 1893            // Wake up all futures currently waiting on a buffer to get opened,
 1894            // to give them a chance to fail now that we've disconnected.
 1895            self.loading_buffers.clear();
 1896            // self.opened_buffer.send(OpenedBufferEvent::Disconnected);
 1897        }
 1898    }
 1899
 1900    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 1901        cx.emit(Event::Closed);
 1902    }
 1903
 1904    pub fn is_disconnected(&self) -> bool {
 1905        match &self.client_state {
 1906            ProjectClientState::Remote {
 1907                sharing_has_stopped,
 1908                ..
 1909            } => *sharing_has_stopped,
 1910            _ => false,
 1911        }
 1912    }
 1913
 1914    pub fn capability(&self) -> Capability {
 1915        match &self.client_state {
 1916            ProjectClientState::Remote { capability, .. } => *capability,
 1917            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
 1918        }
 1919    }
 1920
 1921    pub fn is_read_only(&self) -> bool {
 1922        self.is_disconnected() || self.capability() == Capability::ReadOnly
 1923    }
 1924
 1925    pub fn is_local(&self) -> bool {
 1926        match &self.client_state {
 1927            ProjectClientState::Local | ProjectClientState::Shared { .. } => true,
 1928            ProjectClientState::Remote { .. } => false,
 1929        }
 1930    }
 1931
 1932    pub fn is_remote(&self) -> bool {
 1933        !self.is_local()
 1934    }
 1935
 1936    pub fn create_buffer(
 1937        &mut self,
 1938        text: &str,
 1939        language: Option<Arc<Language>>,
 1940        cx: &mut ModelContext<Self>,
 1941    ) -> Result<Model<Buffer>> {
 1942        if self.is_remote() {
 1943            return Err(anyhow!("creating buffers as a guest is not supported yet"));
 1944        }
 1945        let buffer = cx.new_model(|cx| {
 1946            Buffer::local(text, cx)
 1947                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
 1948        });
 1949        self.register_buffer(&buffer, cx)?;
 1950        Ok(buffer)
 1951    }
 1952
 1953    pub fn open_path(
 1954        &mut self,
 1955        path: ProjectPath,
 1956        cx: &mut ModelContext<Self>,
 1957    ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
 1958        let task = self.open_buffer(path.clone(), cx);
 1959        cx.spawn(move |_, cx| async move {
 1960            let buffer = task.await?;
 1961            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
 1962                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
 1963            })?;
 1964
 1965            let buffer: &AnyModel = &buffer;
 1966            Ok((project_entry_id, buffer.clone()))
 1967        })
 1968    }
 1969
 1970    pub fn open_local_buffer(
 1971        &mut self,
 1972        abs_path: impl AsRef<Path>,
 1973        cx: &mut ModelContext<Self>,
 1974    ) -> Task<Result<Model<Buffer>>> {
 1975        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
 1976            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
 1977        } else {
 1978            Task::ready(Err(anyhow!("no such path")))
 1979        }
 1980    }
 1981
 1982    pub fn open_buffer(
 1983        &mut self,
 1984        path: impl Into<ProjectPath>,
 1985        cx: &mut ModelContext<Self>,
 1986    ) -> Task<Result<Model<Buffer>>> {
 1987        let project_path = path.into();
 1988        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
 1989            worktree
 1990        } else {
 1991            return Task::ready(Err(anyhow!("no such worktree")));
 1992        };
 1993
 1994        // If there is already a buffer for the given path, then return it.
 1995        let existing_buffer = self.get_open_buffer(&project_path, cx);
 1996        if let Some(existing_buffer) = existing_buffer {
 1997            return Task::ready(Ok(existing_buffer));
 1998        }
 1999
 2000        let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
 2001            // If the given path is already being loaded, then wait for that existing
 2002            // task to complete and return the same buffer.
 2003            hash_map::Entry::Occupied(e) => e.get().clone(),
 2004
 2005            // Otherwise, record the fact that this path is now being loaded.
 2006            hash_map::Entry::Vacant(entry) => {
 2007                let (mut tx, rx) = postage::watch::channel();
 2008                entry.insert(rx.clone());
 2009
 2010                let project_path = project_path.clone();
 2011                let load_buffer = if worktree.read(cx).is_local() {
 2012                    self.open_local_buffer_internal(project_path.path.clone(), worktree, cx)
 2013                } else {
 2014                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
 2015                };
 2016
 2017                cx.spawn(move |this, mut cx| async move {
 2018                    let load_result = load_buffer.await;
 2019                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
 2020                        // Record the fact that the buffer is no longer loading.
 2021                        this.loading_buffers_by_path.remove(&project_path);
 2022                        let buffer = load_result.map_err(Arc::new)?;
 2023                        Ok(buffer)
 2024                    })?);
 2025                    anyhow::Ok(())
 2026                })
 2027                .detach();
 2028                rx
 2029            }
 2030        };
 2031
 2032        cx.background_executor().spawn(async move {
 2033            wait_for_loading_buffer(loading_watch)
 2034                .await
 2035                .map_err(|e| e.cloned())
 2036        })
 2037    }
 2038
 2039    fn open_local_buffer_internal(
 2040        &mut self,
 2041        path: Arc<Path>,
 2042        worktree: Model<Worktree>,
 2043        cx: &mut ModelContext<Self>,
 2044    ) -> Task<Result<Model<Buffer>>> {
 2045        let load_buffer = worktree.update(cx, |worktree, cx| {
 2046            let worktree = worktree.as_local_mut().unwrap();
 2047            worktree.load_buffer(&path, cx)
 2048        });
 2049        fn is_not_found_error(error: &anyhow::Error) -> bool {
 2050            error
 2051                .root_cause()
 2052                .downcast_ref::<io::Error>()
 2053                .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
 2054        }
 2055        cx.spawn(move |this, mut cx| async move {
 2056            let buffer = match load_buffer.await {
 2057                Ok(buffer) => Ok(buffer),
 2058                Err(error) if is_not_found_error(&error) => {
 2059                    worktree.update(&mut cx, |worktree, cx| {
 2060                        let worktree = worktree.as_local_mut().unwrap();
 2061                        worktree.new_buffer(path, cx)
 2062                    })
 2063                }
 2064                Err(e) => Err(e),
 2065            }?;
 2066            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))??;
 2067            Ok(buffer)
 2068        })
 2069    }
 2070
 2071    fn open_remote_buffer_internal(
 2072        &mut self,
 2073        path: &Arc<Path>,
 2074        worktree: &Model<Worktree>,
 2075        cx: &mut ModelContext<Self>,
 2076    ) -> Task<Result<Model<Buffer>>> {
 2077        let rpc = self.client.clone();
 2078        let project_id = self.remote_id().unwrap();
 2079        let remote_worktree_id = worktree.read(cx).id();
 2080        let path = path.clone();
 2081        let path_string = path.to_string_lossy().to_string();
 2082        cx.spawn(move |this, mut cx| async move {
 2083            let response = rpc
 2084                .request(proto::OpenBufferByPath {
 2085                    project_id,
 2086                    worktree_id: remote_worktree_id.to_proto(),
 2087                    path: path_string,
 2088                })
 2089                .await?;
 2090            let buffer_id = BufferId::new(response.buffer_id)?;
 2091            this.update(&mut cx, |this, cx| {
 2092                this.wait_for_remote_buffer(buffer_id, cx)
 2093            })?
 2094            .await
 2095        })
 2096    }
 2097
 2098    /// LanguageServerName is owned, because it is inserted into a map
 2099    pub fn open_local_buffer_via_lsp(
 2100        &mut self,
 2101        abs_path: lsp::Url,
 2102        language_server_id: LanguageServerId,
 2103        language_server_name: LanguageServerName,
 2104        cx: &mut ModelContext<Self>,
 2105    ) -> Task<Result<Model<Buffer>>> {
 2106        cx.spawn(move |this, mut cx| async move {
 2107            let abs_path = abs_path
 2108                .to_file_path()
 2109                .map_err(|_| anyhow!("can't convert URI to path"))?;
 2110            let (worktree, relative_path) = if let Some(result) =
 2111                this.update(&mut cx, |this, cx| this.find_local_worktree(&abs_path, cx))?
 2112            {
 2113                result
 2114            } else {
 2115                let worktree = this
 2116                    .update(&mut cx, |this, cx| {
 2117                        this.create_local_worktree(&abs_path, false, cx)
 2118                    })?
 2119                    .await?;
 2120                this.update(&mut cx, |this, cx| {
 2121                    this.language_server_ids.insert(
 2122                        (worktree.read(cx).id(), language_server_name),
 2123                        language_server_id,
 2124                    );
 2125                })
 2126                .ok();
 2127                (worktree, PathBuf::new())
 2128            };
 2129
 2130            let project_path = ProjectPath {
 2131                worktree_id: worktree.update(&mut cx, |worktree, _| worktree.id())?,
 2132                path: relative_path.into(),
 2133            };
 2134            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))?
 2135                .await
 2136        })
 2137    }
 2138
 2139    pub fn open_buffer_by_id(
 2140        &mut self,
 2141        id: BufferId,
 2142        cx: &mut ModelContext<Self>,
 2143    ) -> Task<Result<Model<Buffer>>> {
 2144        if let Some(buffer) = self.buffer_for_id(id) {
 2145            Task::ready(Ok(buffer))
 2146        } else if self.is_local() {
 2147            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
 2148        } else if let Some(project_id) = self.remote_id() {
 2149            let request = self.client.request(proto::OpenBufferById {
 2150                project_id,
 2151                id: id.into(),
 2152            });
 2153            cx.spawn(move |this, mut cx| async move {
 2154                let buffer_id = BufferId::new(request.await?.buffer_id)?;
 2155                this.update(&mut cx, |this, cx| {
 2156                    this.wait_for_remote_buffer(buffer_id, cx)
 2157                })?
 2158                .await
 2159            })
 2160        } else {
 2161            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
 2162        }
 2163    }
 2164
 2165    pub fn save_buffers(
 2166        &self,
 2167        buffers: HashSet<Model<Buffer>>,
 2168        cx: &mut ModelContext<Self>,
 2169    ) -> Task<Result<()>> {
 2170        cx.spawn(move |this, mut cx| async move {
 2171            let save_tasks = buffers.into_iter().filter_map(|buffer| {
 2172                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
 2173                    .ok()
 2174            });
 2175            try_join_all(save_tasks).await?;
 2176            Ok(())
 2177        })
 2178    }
 2179
 2180    pub fn save_buffer(
 2181        &self,
 2182        buffer: Model<Buffer>,
 2183        cx: &mut ModelContext<Self>,
 2184    ) -> Task<Result<()>> {
 2185        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 2186            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 2187        };
 2188        let worktree = file.worktree.clone();
 2189        let path = file.path.clone();
 2190        worktree.update(cx, |worktree, cx| match worktree {
 2191            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
 2192            Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
 2193        })
 2194    }
 2195
 2196    pub fn save_buffer_as(
 2197        &mut self,
 2198        buffer: Model<Buffer>,
 2199        abs_path: PathBuf,
 2200        cx: &mut ModelContext<Self>,
 2201    ) -> Task<Result<()>> {
 2202        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
 2203        let old_file = File::from_dyn(buffer.read(cx).file())
 2204            .filter(|f| f.is_local())
 2205            .cloned();
 2206        cx.spawn(move |this, mut cx| async move {
 2207            if let Some(old_file) = &old_file {
 2208                this.update(&mut cx, |this, cx| {
 2209                    this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
 2210                })?;
 2211            }
 2212            let (worktree, path) = worktree_task.await?;
 2213            worktree
 2214                .update(&mut cx, |worktree, cx| match worktree {
 2215                    Worktree::Local(worktree) => {
 2216                        worktree.save_buffer(buffer.clone(), path.into(), true, cx)
 2217                    }
 2218                    Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
 2219                })?
 2220                .await?;
 2221
 2222            this.update(&mut cx, |this, cx| {
 2223                this.detect_language_for_buffer(&buffer, cx);
 2224                this.register_buffer_with_language_servers(&buffer, cx);
 2225            })?;
 2226            Ok(())
 2227        })
 2228    }
 2229
 2230    pub fn get_open_buffer(
 2231        &mut self,
 2232        path: &ProjectPath,
 2233        cx: &mut ModelContext<Self>,
 2234    ) -> Option<Model<Buffer>> {
 2235        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
 2236        self.opened_buffers.values().find_map(|buffer| {
 2237            let buffer = buffer.upgrade()?;
 2238            let file = File::from_dyn(buffer.read(cx).file())?;
 2239            if file.worktree == worktree && file.path() == &path.path {
 2240                Some(buffer)
 2241            } else {
 2242                None
 2243            }
 2244        })
 2245    }
 2246
 2247    fn register_buffer(
 2248        &mut self,
 2249        buffer: &Model<Buffer>,
 2250        cx: &mut ModelContext<Self>,
 2251    ) -> Result<()> {
 2252        self.request_buffer_diff_recalculation(buffer, cx);
 2253        buffer.update(cx, |buffer, _| {
 2254            buffer.set_language_registry(self.languages.clone())
 2255        });
 2256
 2257        let remote_id = buffer.read(cx).remote_id();
 2258        let is_remote = self.is_remote();
 2259        let open_buffer = if is_remote || self.is_shared() {
 2260            OpenBuffer::Strong(buffer.clone())
 2261        } else {
 2262            OpenBuffer::Weak(buffer.downgrade())
 2263        };
 2264
 2265        match self.opened_buffers.entry(remote_id) {
 2266            hash_map::Entry::Vacant(entry) => {
 2267                entry.insert(open_buffer);
 2268            }
 2269            hash_map::Entry::Occupied(mut entry) => {
 2270                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 2271                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
 2272                } else if entry.get().upgrade().is_some() {
 2273                    if is_remote {
 2274                        return Ok(());
 2275                    } else {
 2276                        debug_panic!("buffer {} was already registered", remote_id);
 2277                        Err(anyhow!("buffer {} was already registered", remote_id))?;
 2278                    }
 2279                }
 2280                entry.insert(open_buffer);
 2281            }
 2282        }
 2283        cx.subscribe(buffer, |this, buffer, event, cx| {
 2284            this.on_buffer_event(buffer, event, cx);
 2285        })
 2286        .detach();
 2287
 2288        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 2289            if file.is_local {
 2290                self.local_buffer_ids_by_path.insert(
 2291                    ProjectPath {
 2292                        worktree_id: file.worktree_id(cx),
 2293                        path: file.path.clone(),
 2294                    },
 2295                    remote_id,
 2296                );
 2297
 2298                if let Some(entry_id) = file.entry_id {
 2299                    self.local_buffer_ids_by_entry_id
 2300                        .insert(entry_id, remote_id);
 2301                }
 2302            }
 2303        }
 2304
 2305        self.detect_language_for_buffer(buffer, cx);
 2306        self.register_buffer_with_language_servers(buffer, cx);
 2307        self.register_buffer_with_copilot(buffer, cx);
 2308        cx.observe_release(buffer, |this, buffer, cx| {
 2309            if let Some(file) = File::from_dyn(buffer.file()) {
 2310                if file.is_local() {
 2311                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
 2312                    for server in this.language_servers_for_buffer(buffer, cx) {
 2313                        server
 2314                            .1
 2315                            .notify::<lsp::notification::DidCloseTextDocument>(
 2316                                lsp::DidCloseTextDocumentParams {
 2317                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
 2318                                },
 2319                            )
 2320                            .log_err();
 2321                    }
 2322                }
 2323            }
 2324        })
 2325        .detach();
 2326
 2327        if let Some(senders) = self.loading_buffers.remove(&remote_id) {
 2328            for sender in senders {
 2329                sender.send(Ok(buffer.clone())).ok();
 2330            }
 2331        }
 2332        Ok(())
 2333    }
 2334
 2335    fn register_buffer_with_language_servers(
 2336        &mut self,
 2337        buffer_handle: &Model<Buffer>,
 2338        cx: &mut ModelContext<Self>,
 2339    ) {
 2340        let buffer = buffer_handle.read(cx);
 2341        let buffer_id = buffer.remote_id();
 2342
 2343        if let Some(file) = File::from_dyn(buffer.file()) {
 2344            if !file.is_local() {
 2345                return;
 2346            }
 2347
 2348            let abs_path = file.abs_path(cx);
 2349            let uri = lsp::Url::from_file_path(&abs_path)
 2350                .unwrap_or_else(|()| panic!("Failed to register file {abs_path:?}"));
 2351            let initial_snapshot = buffer.text_snapshot();
 2352            let language = buffer.language().cloned();
 2353            let worktree_id = file.worktree_id(cx);
 2354
 2355            if let Some(local_worktree) = file.worktree.read(cx).as_local() {
 2356                for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
 2357                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
 2358                        .log_err();
 2359                }
 2360            }
 2361
 2362            if let Some(language) = language {
 2363                for adapter in self.languages.lsp_adapters(&language) {
 2364                    let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
 2365                    let server = self
 2366                        .language_server_ids
 2367                        .get(&(worktree_id, adapter.name.clone()))
 2368                        .and_then(|id| self.language_servers.get(id))
 2369                        .and_then(|server_state| {
 2370                            if let LanguageServerState::Running { server, .. } = server_state {
 2371                                Some(server.clone())
 2372                            } else {
 2373                                None
 2374                            }
 2375                        });
 2376                    let server = match server {
 2377                        Some(server) => server,
 2378                        None => continue,
 2379                    };
 2380
 2381                    server
 2382                        .notify::<lsp::notification::DidOpenTextDocument>(
 2383                            lsp::DidOpenTextDocumentParams {
 2384                                text_document: lsp::TextDocumentItem::new(
 2385                                    uri.clone(),
 2386                                    language_id.unwrap_or_default(),
 2387                                    0,
 2388                                    initial_snapshot.text(),
 2389                                ),
 2390                            },
 2391                        )
 2392                        .log_err();
 2393
 2394                    buffer_handle.update(cx, |buffer, cx| {
 2395                        buffer.set_completion_triggers(
 2396                            server
 2397                                .capabilities()
 2398                                .completion_provider
 2399                                .as_ref()
 2400                                .and_then(|provider| provider.trigger_characters.clone())
 2401                                .unwrap_or_default(),
 2402                            cx,
 2403                        );
 2404                    });
 2405
 2406                    let snapshot = LspBufferSnapshot {
 2407                        version: 0,
 2408                        snapshot: initial_snapshot.clone(),
 2409                    };
 2410                    self.buffer_snapshots
 2411                        .entry(buffer_id)
 2412                        .or_default()
 2413                        .insert(server.server_id(), vec![snapshot]);
 2414                }
 2415            }
 2416        }
 2417    }
 2418
 2419    fn unregister_buffer_from_language_servers(
 2420        &mut self,
 2421        buffer: &Model<Buffer>,
 2422        old_file: &File,
 2423        cx: &mut ModelContext<Self>,
 2424    ) {
 2425        let old_path = match old_file.as_local() {
 2426            Some(local) => local.abs_path(cx),
 2427            None => return,
 2428        };
 2429
 2430        buffer.update(cx, |buffer, cx| {
 2431            let worktree_id = old_file.worktree_id(cx);
 2432            let ids = &self.language_server_ids;
 2433
 2434            if let Some(language) = buffer.language().cloned() {
 2435                for adapter in self.languages.lsp_adapters(&language) {
 2436                    if let Some(server_id) = ids.get(&(worktree_id, adapter.name.clone())) {
 2437                        buffer.update_diagnostics(*server_id, Default::default(), cx);
 2438                    }
 2439                }
 2440            }
 2441
 2442            self.buffer_snapshots.remove(&buffer.remote_id());
 2443            let file_url = lsp::Url::from_file_path(old_path).unwrap();
 2444            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
 2445                language_server
 2446                    .notify::<lsp::notification::DidCloseTextDocument>(
 2447                        lsp::DidCloseTextDocumentParams {
 2448                            text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
 2449                        },
 2450                    )
 2451                    .log_err();
 2452            }
 2453        });
 2454    }
 2455
 2456    fn register_buffer_with_copilot(
 2457        &self,
 2458        buffer_handle: &Model<Buffer>,
 2459        cx: &mut ModelContext<Self>,
 2460    ) {
 2461        if let Some(copilot) = Copilot::global(cx) {
 2462            copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
 2463        }
 2464    }
 2465
 2466    async fn send_buffer_ordered_messages(
 2467        this: WeakModel<Self>,
 2468        rx: UnboundedReceiver<BufferOrderedMessage>,
 2469        mut cx: AsyncAppContext,
 2470    ) -> Result<()> {
 2471        const MAX_BATCH_SIZE: usize = 128;
 2472
 2473        let mut operations_by_buffer_id = HashMap::default();
 2474        async fn flush_operations(
 2475            this: &WeakModel<Project>,
 2476            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
 2477            needs_resync_with_host: &mut bool,
 2478            is_local: bool,
 2479            cx: &mut AsyncAppContext,
 2480        ) -> Result<()> {
 2481            for (buffer_id, operations) in operations_by_buffer_id.drain() {
 2482                let request = this.update(cx, |this, _| {
 2483                    let project_id = this.remote_id()?;
 2484                    Some(this.client.request(proto::UpdateBuffer {
 2485                        buffer_id: buffer_id.into(),
 2486                        project_id,
 2487                        operations,
 2488                    }))
 2489                })?;
 2490                if let Some(request) = request {
 2491                    if request.await.is_err() && !is_local {
 2492                        *needs_resync_with_host = true;
 2493                        break;
 2494                    }
 2495                }
 2496            }
 2497            Ok(())
 2498        }
 2499
 2500        let mut needs_resync_with_host = false;
 2501        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
 2502
 2503        while let Some(changes) = changes.next().await {
 2504            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
 2505
 2506            for change in changes {
 2507                match change {
 2508                    BufferOrderedMessage::Operation {
 2509                        buffer_id,
 2510                        operation,
 2511                    } => {
 2512                        if needs_resync_with_host {
 2513                            continue;
 2514                        }
 2515
 2516                        operations_by_buffer_id
 2517                            .entry(buffer_id)
 2518                            .or_insert(Vec::new())
 2519                            .push(operation);
 2520                    }
 2521
 2522                    BufferOrderedMessage::Resync => {
 2523                        operations_by_buffer_id.clear();
 2524                        if this
 2525                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
 2526                            .await
 2527                            .is_ok()
 2528                        {
 2529                            needs_resync_with_host = false;
 2530                        }
 2531                    }
 2532
 2533                    BufferOrderedMessage::LanguageServerUpdate {
 2534                        language_server_id,
 2535                        message,
 2536                    } => {
 2537                        flush_operations(
 2538                            &this,
 2539                            &mut operations_by_buffer_id,
 2540                            &mut needs_resync_with_host,
 2541                            is_local,
 2542                            &mut cx,
 2543                        )
 2544                        .await?;
 2545
 2546                        this.update(&mut cx, |this, _| {
 2547                            if let Some(project_id) = this.remote_id() {
 2548                                this.client
 2549                                    .send(proto::UpdateLanguageServer {
 2550                                        project_id,
 2551                                        language_server_id: language_server_id.0 as u64,
 2552                                        variant: Some(message),
 2553                                    })
 2554                                    .log_err();
 2555                            }
 2556                        })?;
 2557                    }
 2558                }
 2559            }
 2560
 2561            flush_operations(
 2562                &this,
 2563                &mut operations_by_buffer_id,
 2564                &mut needs_resync_with_host,
 2565                is_local,
 2566                &mut cx,
 2567            )
 2568            .await?;
 2569        }
 2570
 2571        Ok(())
 2572    }
 2573
 2574    fn on_buffer_event(
 2575        &mut self,
 2576        buffer: Model<Buffer>,
 2577        event: &BufferEvent,
 2578        cx: &mut ModelContext<Self>,
 2579    ) -> Option<()> {
 2580        if matches!(
 2581            event,
 2582            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
 2583        ) {
 2584            self.request_buffer_diff_recalculation(&buffer, cx);
 2585        }
 2586
 2587        match event {
 2588            BufferEvent::Operation(operation) => {
 2589                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
 2590                    buffer_id: buffer.read(cx).remote_id(),
 2591                    operation: language::proto::serialize_operation(operation),
 2592                })
 2593                .ok();
 2594            }
 2595
 2596            BufferEvent::Edited { .. } => {
 2597                let buffer = buffer.read(cx);
 2598                let file = File::from_dyn(buffer.file())?;
 2599                let abs_path = file.as_local()?.abs_path(cx);
 2600                let uri = lsp::Url::from_file_path(abs_path).unwrap();
 2601                let next_snapshot = buffer.text_snapshot();
 2602
 2603                let language_servers: Vec<_> = self
 2604                    .language_servers_for_buffer(buffer, cx)
 2605                    .map(|i| i.1.clone())
 2606                    .collect();
 2607
 2608                for language_server in language_servers {
 2609                    let language_server = language_server.clone();
 2610
 2611                    let buffer_snapshots = self
 2612                        .buffer_snapshots
 2613                        .get_mut(&buffer.remote_id())
 2614                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
 2615                    let previous_snapshot = buffer_snapshots.last()?;
 2616
 2617                    let build_incremental_change = || {
 2618                        buffer
 2619                            .edits_since::<(PointUtf16, usize)>(
 2620                                previous_snapshot.snapshot.version(),
 2621                            )
 2622                            .map(|edit| {
 2623                                let edit_start = edit.new.start.0;
 2624                                let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
 2625                                let new_text = next_snapshot
 2626                                    .text_for_range(edit.new.start.1..edit.new.end.1)
 2627                                    .collect();
 2628                                lsp::TextDocumentContentChangeEvent {
 2629                                    range: Some(lsp::Range::new(
 2630                                        point_to_lsp(edit_start),
 2631                                        point_to_lsp(edit_end),
 2632                                    )),
 2633                                    range_length: None,
 2634                                    text: new_text,
 2635                                }
 2636                            })
 2637                            .collect()
 2638                    };
 2639
 2640                    let document_sync_kind = language_server
 2641                        .capabilities()
 2642                        .text_document_sync
 2643                        .as_ref()
 2644                        .and_then(|sync| match sync {
 2645                            lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
 2646                            lsp::TextDocumentSyncCapability::Options(options) => options.change,
 2647                        });
 2648
 2649                    let content_changes: Vec<_> = match document_sync_kind {
 2650                        Some(lsp::TextDocumentSyncKind::FULL) => {
 2651                            vec![lsp::TextDocumentContentChangeEvent {
 2652                                range: None,
 2653                                range_length: None,
 2654                                text: next_snapshot.text(),
 2655                            }]
 2656                        }
 2657                        Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
 2658                        _ => {
 2659                            #[cfg(any(test, feature = "test-support"))]
 2660                            {
 2661                                build_incremental_change()
 2662                            }
 2663
 2664                            #[cfg(not(any(test, feature = "test-support")))]
 2665                            {
 2666                                continue;
 2667                            }
 2668                        }
 2669                    };
 2670
 2671                    let next_version = previous_snapshot.version + 1;
 2672
 2673                    buffer_snapshots.push(LspBufferSnapshot {
 2674                        version: next_version,
 2675                        snapshot: next_snapshot.clone(),
 2676                    });
 2677
 2678                    language_server
 2679                        .notify::<lsp::notification::DidChangeTextDocument>(
 2680                            lsp::DidChangeTextDocumentParams {
 2681                                text_document: lsp::VersionedTextDocumentIdentifier::new(
 2682                                    uri.clone(),
 2683                                    next_version,
 2684                                ),
 2685                                content_changes,
 2686                            },
 2687                        )
 2688                        .log_err();
 2689                }
 2690            }
 2691
 2692            BufferEvent::Saved => {
 2693                let file = File::from_dyn(buffer.read(cx).file())?;
 2694                let worktree_id = file.worktree_id(cx);
 2695                let abs_path = file.as_local()?.abs_path(cx);
 2696                let text_document = lsp::TextDocumentIdentifier {
 2697                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
 2698                };
 2699
 2700                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
 2701                    let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
 2702
 2703                    server
 2704                        .notify::<lsp::notification::DidSaveTextDocument>(
 2705                            lsp::DidSaveTextDocumentParams {
 2706                                text_document: text_document.clone(),
 2707                                text,
 2708                            },
 2709                        )
 2710                        .log_err();
 2711                }
 2712
 2713                let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
 2714                for language_server_id in language_server_ids {
 2715                    if let Some(LanguageServerState::Running {
 2716                        adapter,
 2717                        simulate_disk_based_diagnostics_completion,
 2718                        ..
 2719                    }) = self.language_servers.get_mut(&language_server_id)
 2720                    {
 2721                        // After saving a buffer using a language server that doesn't provide
 2722                        // a disk-based progress token, kick off a timer that will reset every
 2723                        // time the buffer is saved. If the timer eventually fires, simulate
 2724                        // disk-based diagnostics being finished so that other pieces of UI
 2725                        // (e.g., project diagnostics view, diagnostic status bar) can update.
 2726                        // We don't emit an event right away because the language server might take
 2727                        // some time to publish diagnostics.
 2728                        if adapter.disk_based_diagnostics_progress_token.is_none() {
 2729                            const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
 2730                                Duration::from_secs(1);
 2731
 2732                            let task = cx.spawn(move |this, mut cx| async move {
 2733                                cx.background_executor().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
 2734                                if let Some(this) = this.upgrade() {
 2735                                    this.update(&mut cx, |this, cx| {
 2736                                        this.disk_based_diagnostics_finished(
 2737                                            language_server_id,
 2738                                            cx,
 2739                                        );
 2740                                        this.enqueue_buffer_ordered_message(
 2741                                                BufferOrderedMessage::LanguageServerUpdate {
 2742                                                    language_server_id,
 2743                                                    message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
 2744                                                },
 2745                                            )
 2746                                            .ok();
 2747                                    }).ok();
 2748                                }
 2749                            });
 2750                            *simulate_disk_based_diagnostics_completion = Some(task);
 2751                        }
 2752                    }
 2753                }
 2754            }
 2755            BufferEvent::FileHandleChanged => {
 2756                let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 2757                    return None;
 2758                };
 2759
 2760                let remote_id = buffer.read(cx).remote_id();
 2761                if let Some(entry_id) = file.entry_id {
 2762                    match self.local_buffer_ids_by_entry_id.get(&entry_id) {
 2763                        Some(_) => {
 2764                            return None;
 2765                        }
 2766                        None => {
 2767                            self.local_buffer_ids_by_entry_id
 2768                                .insert(entry_id, remote_id);
 2769                        }
 2770                    }
 2771                };
 2772                self.local_buffer_ids_by_path.insert(
 2773                    ProjectPath {
 2774                        worktree_id: file.worktree_id(cx),
 2775                        path: file.path.clone(),
 2776                    },
 2777                    remote_id,
 2778                );
 2779            }
 2780            _ => {}
 2781        }
 2782
 2783        None
 2784    }
 2785
 2786    fn request_buffer_diff_recalculation(
 2787        &mut self,
 2788        buffer: &Model<Buffer>,
 2789        cx: &mut ModelContext<Self>,
 2790    ) {
 2791        self.buffers_needing_diff.insert(buffer.downgrade());
 2792        let first_insertion = self.buffers_needing_diff.len() == 1;
 2793
 2794        let settings = ProjectSettings::get_global(cx);
 2795        let delay = if let Some(delay) = settings.git.gutter_debounce {
 2796            delay
 2797        } else {
 2798            if first_insertion {
 2799                let this = cx.weak_model();
 2800                cx.defer(move |cx| {
 2801                    if let Some(this) = this.upgrade() {
 2802                        this.update(cx, |this, cx| {
 2803                            this.recalculate_buffer_diffs(cx).detach();
 2804                        });
 2805                    }
 2806                });
 2807            }
 2808            return;
 2809        };
 2810
 2811        const MIN_DELAY: u64 = 50;
 2812        let delay = delay.max(MIN_DELAY);
 2813        let duration = Duration::from_millis(delay);
 2814
 2815        self.git_diff_debouncer
 2816            .fire_new(duration, cx, move |this, cx| {
 2817                this.recalculate_buffer_diffs(cx)
 2818            });
 2819    }
 2820
 2821    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
 2822        let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
 2823        cx.spawn(move |this, mut cx| async move {
 2824            let tasks: Vec<_> = buffers
 2825                .iter()
 2826                .filter_map(|buffer| {
 2827                    let buffer = buffer.upgrade()?;
 2828                    buffer
 2829                        .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
 2830                        .ok()
 2831                        .flatten()
 2832                })
 2833                .collect();
 2834
 2835            futures::future::join_all(tasks).await;
 2836
 2837            this.update(&mut cx, |this, cx| {
 2838                if this.buffers_needing_diff.is_empty() {
 2839                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
 2840                    for buffer in buffers {
 2841                        if let Some(buffer) = buffer.upgrade() {
 2842                            buffer.update(cx, |_, cx| cx.notify());
 2843                        }
 2844                    }
 2845                } else {
 2846                    this.recalculate_buffer_diffs(cx).detach();
 2847                }
 2848            })
 2849            .ok();
 2850        })
 2851    }
 2852
 2853    fn language_servers_for_worktree(
 2854        &self,
 2855        worktree_id: WorktreeId,
 2856    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
 2857        self.language_server_ids
 2858            .iter()
 2859            .filter_map(move |((language_server_worktree_id, _), id)| {
 2860                if *language_server_worktree_id == worktree_id {
 2861                    if let Some(LanguageServerState::Running {
 2862                        adapter,
 2863                        language,
 2864                        server,
 2865                        ..
 2866                    }) = self.language_servers.get(id)
 2867                    {
 2868                        return Some((adapter, language, server));
 2869                    }
 2870                }
 2871                None
 2872            })
 2873    }
 2874
 2875    fn maintain_buffer_languages(
 2876        languages: Arc<LanguageRegistry>,
 2877        cx: &mut ModelContext<Project>,
 2878    ) -> Task<()> {
 2879        let mut subscription = languages.subscribe();
 2880        let mut prev_reload_count = languages.reload_count();
 2881        cx.spawn(move |project, mut cx| async move {
 2882            while let Some(()) = subscription.next().await {
 2883                if let Some(project) = project.upgrade() {
 2884                    // If the language registry has been reloaded, then remove and
 2885                    // re-assign the languages on all open buffers.
 2886                    let reload_count = languages.reload_count();
 2887                    if reload_count > prev_reload_count {
 2888                        prev_reload_count = reload_count;
 2889                        project
 2890                            .update(&mut cx, |this, cx| {
 2891                                let buffers = this
 2892                                    .opened_buffers
 2893                                    .values()
 2894                                    .filter_map(|b| b.upgrade())
 2895                                    .collect::<Vec<_>>();
 2896                                for buffer in buffers {
 2897                                    if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
 2898                                    {
 2899                                        this.unregister_buffer_from_language_servers(
 2900                                            &buffer, &f, cx,
 2901                                        );
 2902                                        buffer
 2903                                            .update(cx, |buffer, cx| buffer.set_language(None, cx));
 2904                                    }
 2905                                }
 2906                            })
 2907                            .ok();
 2908                    }
 2909
 2910                    project
 2911                        .update(&mut cx, |project, cx| {
 2912                            let mut plain_text_buffers = Vec::new();
 2913                            let mut buffers_with_unknown_injections = Vec::new();
 2914                            for buffer in project.opened_buffers.values() {
 2915                                if let Some(handle) = buffer.upgrade() {
 2916                                    let buffer = &handle.read(cx);
 2917                                    if buffer.language().is_none()
 2918                                        || buffer.language() == Some(&*language::PLAIN_TEXT)
 2919                                    {
 2920                                        plain_text_buffers.push(handle);
 2921                                    } else if buffer.contains_unknown_injections() {
 2922                                        buffers_with_unknown_injections.push(handle);
 2923                                    }
 2924                                }
 2925                            }
 2926
 2927                            for buffer in plain_text_buffers {
 2928                                project.detect_language_for_buffer(&buffer, cx);
 2929                                project.register_buffer_with_language_servers(&buffer, cx);
 2930                            }
 2931
 2932                            for buffer in buffers_with_unknown_injections {
 2933                                buffer.update(cx, |buffer, cx| buffer.reparse(cx));
 2934                            }
 2935                        })
 2936                        .ok();
 2937                }
 2938            }
 2939        })
 2940    }
 2941
 2942    fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<Result<()>> {
 2943        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
 2944        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
 2945
 2946        let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
 2947            *settings_changed_tx.borrow_mut() = ();
 2948        });
 2949
 2950        cx.spawn(move |this, mut cx| async move {
 2951            while let Some(()) = settings_changed_rx.next().await {
 2952                let servers = this.update(&mut cx, |this, cx| {
 2953                    this.language_server_ids
 2954                        .iter()
 2955                        .filter_map(|((worktree_id, _), server_id)| {
 2956                            let worktree = this.worktree_for_id(*worktree_id, cx)?;
 2957                            let state = this.language_servers.get(server_id)?;
 2958                            let delegate = ProjectLspAdapterDelegate::new(this, &worktree, cx);
 2959                            match state {
 2960                                LanguageServerState::Starting(_) => None,
 2961                                LanguageServerState::Running {
 2962                                    adapter, server, ..
 2963                                } => Some((
 2964                                    adapter.adapter.clone(),
 2965                                    server.clone(),
 2966                                    delegate as Arc<dyn LspAdapterDelegate>,
 2967                                )),
 2968                            }
 2969                        })
 2970                        .collect::<Vec<_>>()
 2971                })?;
 2972
 2973                for (adapter, server, delegate) in servers {
 2974                    let settings = adapter.workspace_configuration(&delegate, &mut cx).await?;
 2975
 2976                    server
 2977                        .notify::<lsp::notification::DidChangeConfiguration>(
 2978                            lsp::DidChangeConfigurationParams { settings },
 2979                        )
 2980                        .ok();
 2981                }
 2982            }
 2983
 2984            drop(settings_observation);
 2985            anyhow::Ok(())
 2986        })
 2987    }
 2988
 2989    fn detect_language_for_buffer(
 2990        &mut self,
 2991        buffer_handle: &Model<Buffer>,
 2992        cx: &mut ModelContext<Self>,
 2993    ) {
 2994        // If the buffer has a language, set it and start the language server if we haven't already.
 2995        let buffer = buffer_handle.read(cx);
 2996        let Some(file) = buffer.file() else {
 2997            return;
 2998        };
 2999        let content = buffer.as_rope();
 3000        let Some(new_language_result) = self
 3001            .languages
 3002            .language_for_file(file, Some(content), cx)
 3003            .now_or_never()
 3004        else {
 3005            return;
 3006        };
 3007
 3008        match new_language_result {
 3009            Err(e) => {
 3010                if e.is::<language::LanguageNotFound>() {
 3011                    cx.emit(Event::LanguageNotFound(buffer_handle.clone()))
 3012                }
 3013            }
 3014            Ok(new_language) => {
 3015                self.set_language_for_buffer(buffer_handle, new_language, cx);
 3016            }
 3017        };
 3018    }
 3019
 3020    pub fn set_language_for_buffer(
 3021        &mut self,
 3022        buffer: &Model<Buffer>,
 3023        new_language: Arc<Language>,
 3024        cx: &mut ModelContext<Self>,
 3025    ) {
 3026        buffer.update(cx, |buffer, cx| {
 3027            if buffer.language().map_or(true, |old_language| {
 3028                !Arc::ptr_eq(old_language, &new_language)
 3029            }) {
 3030                buffer.set_language(Some(new_language.clone()), cx);
 3031            }
 3032        });
 3033
 3034        let buffer_file = buffer.read(cx).file().cloned();
 3035        let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
 3036        let buffer_file = File::from_dyn(buffer_file.as_ref());
 3037        let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
 3038        if let Some(prettier_plugins) =
 3039            prettier_support::prettier_plugins_for_language(&new_language, &settings)
 3040        {
 3041            self.install_default_prettier(worktree, prettier_plugins.iter().cloned(), cx);
 3042        };
 3043        if let Some(file) = buffer_file {
 3044            let worktree = file.worktree.clone();
 3045            if worktree.read(cx).is_local() {
 3046                self.start_language_servers(&worktree, new_language, cx);
 3047            }
 3048        }
 3049    }
 3050
 3051    fn start_language_servers(
 3052        &mut self,
 3053        worktree: &Model<Worktree>,
 3054        language: Arc<Language>,
 3055        cx: &mut ModelContext<Self>,
 3056    ) {
 3057        let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
 3058        let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
 3059        if !settings.enable_language_server {
 3060            return;
 3061        }
 3062
 3063        let available_lsp_adapters = self.languages.clone().lsp_adapters(&language);
 3064        let available_language_servers = available_lsp_adapters
 3065            .iter()
 3066            .map(|lsp_adapter| lsp_adapter.name.clone())
 3067            .collect::<Vec<_>>();
 3068
 3069        let enabled_language_servers =
 3070            settings.customized_language_servers(&available_language_servers);
 3071        let enabled_lsp_adapters = available_lsp_adapters
 3072            .into_iter()
 3073            .filter(|adapter| enabled_language_servers.contains(&adapter.name))
 3074            .collect::<Vec<_>>();
 3075
 3076        log::info!(
 3077            "starting language servers for {language}: {adapters}",
 3078            language = language.name(),
 3079            adapters = enabled_lsp_adapters
 3080                .iter()
 3081                .map(|adapter| adapter.name.0.as_ref())
 3082                .join(", ")
 3083        );
 3084
 3085        for adapter in enabled_lsp_adapters {
 3086            self.start_language_server(worktree, adapter.clone(), language.clone(), cx);
 3087        }
 3088    }
 3089
 3090    fn start_language_server(
 3091        &mut self,
 3092        worktree_handle: &Model<Worktree>,
 3093        adapter: Arc<CachedLspAdapter>,
 3094        language: Arc<Language>,
 3095        cx: &mut ModelContext<Self>,
 3096    ) {
 3097        if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
 3098            return;
 3099        }
 3100
 3101        let worktree = worktree_handle.read(cx);
 3102        let worktree_id = worktree.id();
 3103        let worktree_path = worktree.abs_path();
 3104        let key = (worktree_id, adapter.name.clone());
 3105        if self.language_server_ids.contains_key(&key) {
 3106            return;
 3107        }
 3108
 3109        let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
 3110        let lsp_adapter_delegate = ProjectLspAdapterDelegate::new(self, worktree_handle, cx);
 3111        let pending_server = match self.languages.create_pending_language_server(
 3112            stderr_capture.clone(),
 3113            language.clone(),
 3114            adapter.clone(),
 3115            Arc::clone(&worktree_path),
 3116            lsp_adapter_delegate.clone(),
 3117            cx,
 3118        ) {
 3119            Some(pending_server) => pending_server,
 3120            None => return,
 3121        };
 3122
 3123        let project_settings = ProjectSettings::get(
 3124            Some(SettingsLocation {
 3125                worktree_id: worktree_id.to_proto() as usize,
 3126                path: Path::new(""),
 3127            }),
 3128            cx,
 3129        );
 3130        let lsp = project_settings.lsp.get(&adapter.name.0);
 3131        let override_options = lsp.and_then(|s| s.initialization_options.clone());
 3132
 3133        let server_id = pending_server.server_id;
 3134        let container_dir = pending_server.container_dir.clone();
 3135        let state = LanguageServerState::Starting({
 3136            let adapter = adapter.clone();
 3137            let server_name = adapter.name.0.clone();
 3138            let language = language.clone();
 3139            let key = key.clone();
 3140
 3141            cx.spawn(move |this, mut cx| async move {
 3142                let result = Self::setup_and_insert_language_server(
 3143                    this.clone(),
 3144                    lsp_adapter_delegate,
 3145                    override_options,
 3146                    pending_server,
 3147                    adapter.clone(),
 3148                    language.clone(),
 3149                    server_id,
 3150                    key,
 3151                    &mut cx,
 3152                )
 3153                .await;
 3154
 3155                match result {
 3156                    Ok(server) => {
 3157                        stderr_capture.lock().take();
 3158                        server
 3159                    }
 3160
 3161                    Err(err) => {
 3162                        log::error!("failed to start language server {server_name:?}: {err}");
 3163                        log::error!("server stderr: {:?}", stderr_capture.lock().take());
 3164
 3165                        let this = this.upgrade()?;
 3166                        let container_dir = container_dir?;
 3167
 3168                        let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
 3169                        if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
 3170                            let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
 3171                            log::error!("Hit {max} reinstallation attempts for {server_name:?}");
 3172                            return None;
 3173                        }
 3174
 3175                        log::info!(
 3176                            "retrying installation of language server {server_name:?} in {}s",
 3177                            SERVER_REINSTALL_DEBOUNCE_TIMEOUT.as_secs()
 3178                        );
 3179                        cx.background_executor()
 3180                            .timer(SERVER_REINSTALL_DEBOUNCE_TIMEOUT)
 3181                            .await;
 3182
 3183                        let installation_test_binary = adapter
 3184                            .installation_test_binary(container_dir.to_path_buf())
 3185                            .await;
 3186
 3187                        this.update(&mut cx, |_, cx| {
 3188                            Self::check_errored_server(
 3189                                language,
 3190                                adapter,
 3191                                server_id,
 3192                                installation_test_binary,
 3193                                cx,
 3194                            )
 3195                        })
 3196                        .ok();
 3197
 3198                        None
 3199                    }
 3200                }
 3201            })
 3202        });
 3203
 3204        self.language_servers.insert(server_id, state);
 3205        self.language_server_ids.insert(key, server_id);
 3206    }
 3207
 3208    fn reinstall_language_server(
 3209        &mut self,
 3210        language: Arc<Language>,
 3211        adapter: Arc<CachedLspAdapter>,
 3212        server_id: LanguageServerId,
 3213        cx: &mut ModelContext<Self>,
 3214    ) -> Option<Task<()>> {
 3215        log::info!("beginning to reinstall server");
 3216
 3217        let existing_server = match self.language_servers.remove(&server_id) {
 3218            Some(LanguageServerState::Running { server, .. }) => Some(server),
 3219            _ => None,
 3220        };
 3221
 3222        for worktree in &self.worktrees {
 3223            if let Some(worktree) = worktree.upgrade() {
 3224                let key = (worktree.read(cx).id(), adapter.name.clone());
 3225                self.language_server_ids.remove(&key);
 3226            }
 3227        }
 3228
 3229        Some(cx.spawn(move |this, mut cx| async move {
 3230            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
 3231                log::info!("shutting down existing server");
 3232                task.await;
 3233            }
 3234
 3235            // TODO: This is race-safe with regards to preventing new instances from
 3236            // starting while deleting, but existing instances in other projects are going
 3237            // to be very confused and messed up
 3238            let Some(task) = this
 3239                .update(&mut cx, |this, cx| {
 3240                    this.languages.delete_server_container(adapter.clone(), cx)
 3241                })
 3242                .log_err()
 3243            else {
 3244                return;
 3245            };
 3246            task.await;
 3247
 3248            this.update(&mut cx, |this, cx| {
 3249                let worktrees = this.worktrees.clone();
 3250                for worktree in worktrees {
 3251                    if let Some(worktree) = worktree.upgrade() {
 3252                        this.start_language_server(
 3253                            &worktree,
 3254                            adapter.clone(),
 3255                            language.clone(),
 3256                            cx,
 3257                        );
 3258                    }
 3259                }
 3260            })
 3261            .ok();
 3262        }))
 3263    }
 3264
 3265    #[allow(clippy::too_many_arguments)]
 3266    async fn setup_and_insert_language_server(
 3267        this: WeakModel<Self>,
 3268        delegate: Arc<dyn LspAdapterDelegate>,
 3269        override_initialization_options: Option<serde_json::Value>,
 3270        pending_server: PendingLanguageServer,
 3271        adapter: Arc<CachedLspAdapter>,
 3272        language: Arc<Language>,
 3273        server_id: LanguageServerId,
 3274        key: (WorktreeId, LanguageServerName),
 3275        cx: &mut AsyncAppContext,
 3276    ) -> Result<Option<Arc<LanguageServer>>> {
 3277        let language_server = Self::setup_pending_language_server(
 3278            this.clone(),
 3279            override_initialization_options,
 3280            pending_server,
 3281            delegate,
 3282            adapter.clone(),
 3283            server_id,
 3284            cx,
 3285        )
 3286        .await?;
 3287
 3288        let this = match this.upgrade() {
 3289            Some(this) => this,
 3290            None => return Err(anyhow!("failed to upgrade project handle")),
 3291        };
 3292
 3293        this.update(cx, |this, cx| {
 3294            this.insert_newly_running_language_server(
 3295                language,
 3296                adapter,
 3297                language_server.clone(),
 3298                server_id,
 3299                key,
 3300                cx,
 3301            )
 3302        })??;
 3303
 3304        Ok(Some(language_server))
 3305    }
 3306
 3307    async fn setup_pending_language_server(
 3308        this: WeakModel<Self>,
 3309        override_options: Option<serde_json::Value>,
 3310        pending_server: PendingLanguageServer,
 3311        delegate: Arc<dyn LspAdapterDelegate>,
 3312        adapter: Arc<CachedLspAdapter>,
 3313        server_id: LanguageServerId,
 3314        cx: &mut AsyncAppContext,
 3315    ) -> Result<Arc<LanguageServer>> {
 3316        let workspace_config = adapter
 3317            .adapter
 3318            .clone()
 3319            .workspace_configuration(&delegate, cx)
 3320            .await?;
 3321        let (language_server, mut initialization_options) = pending_server.task.await?;
 3322
 3323        let name = language_server.name();
 3324        language_server
 3325            .on_notification::<lsp::notification::PublishDiagnostics, _>({
 3326                let adapter = adapter.clone();
 3327                let this = this.clone();
 3328                move |mut params, mut cx| {
 3329                    let adapter = adapter.clone();
 3330                    if let Some(this) = this.upgrade() {
 3331                        adapter.process_diagnostics(&mut params);
 3332                        this.update(&mut cx, |this, cx| {
 3333                            this.update_diagnostics(
 3334                                server_id,
 3335                                params,
 3336                                &adapter.disk_based_diagnostic_sources,
 3337                                cx,
 3338                            )
 3339                            .log_err();
 3340                        })
 3341                        .ok();
 3342                    }
 3343                }
 3344            })
 3345            .detach();
 3346
 3347        language_server
 3348            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
 3349                let adapter = adapter.adapter.clone();
 3350                let delegate = delegate.clone();
 3351                move |params, mut cx| {
 3352                    let adapter = adapter.clone();
 3353                    let delegate = delegate.clone();
 3354                    async move {
 3355                        let workspace_config =
 3356                            adapter.workspace_configuration(&delegate, &mut cx).await?;
 3357                        Ok(params
 3358                            .items
 3359                            .into_iter()
 3360                            .map(|item| {
 3361                                if let Some(section) = &item.section {
 3362                                    workspace_config
 3363                                        .get(section)
 3364                                        .cloned()
 3365                                        .unwrap_or(serde_json::Value::Null)
 3366                                } else {
 3367                                    workspace_config.clone()
 3368                                }
 3369                            })
 3370                            .collect())
 3371                    }
 3372                }
 3373            })
 3374            .detach();
 3375
 3376        // Even though we don't have handling for these requests, respond to them to
 3377        // avoid stalling any language server like `gopls` which waits for a response
 3378        // to these requests when initializing.
 3379        language_server
 3380            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
 3381                let this = this.clone();
 3382                move |params, mut cx| {
 3383                    let this = this.clone();
 3384                    async move {
 3385                        this.update(&mut cx, |this, _| {
 3386                            if let Some(status) = this.language_server_statuses.get_mut(&server_id)
 3387                            {
 3388                                if let lsp::NumberOrString::String(token) = params.token {
 3389                                    status.progress_tokens.insert(token);
 3390                                }
 3391                            }
 3392                        })?;
 3393
 3394                        Ok(())
 3395                    }
 3396                }
 3397            })
 3398            .detach();
 3399
 3400        language_server
 3401            .on_request::<lsp::request::RegisterCapability, _, _>({
 3402                let this = this.clone();
 3403                move |params, mut cx| {
 3404                    let this = this.clone();
 3405                    async move {
 3406                        for reg in params.registrations {
 3407                            if reg.method == "workspace/didChangeWatchedFiles" {
 3408                                if let Some(options) = reg.register_options {
 3409                                    let options = serde_json::from_value(options)?;
 3410                                    this.update(&mut cx, |this, cx| {
 3411                                        this.on_lsp_did_change_watched_files(
 3412                                            server_id, options, cx,
 3413                                        );
 3414                                    })?;
 3415                                }
 3416                            }
 3417                        }
 3418                        Ok(())
 3419                    }
 3420                }
 3421            })
 3422            .detach();
 3423
 3424        language_server
 3425            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
 3426                let adapter = adapter.clone();
 3427                let this = this.clone();
 3428                move |params, cx| {
 3429                    Self::on_lsp_workspace_edit(
 3430                        this.clone(),
 3431                        params,
 3432                        server_id,
 3433                        adapter.clone(),
 3434                        cx,
 3435                    )
 3436                }
 3437            })
 3438            .detach();
 3439
 3440        language_server
 3441            .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
 3442                let this = this.clone();
 3443                move |(), mut cx| {
 3444                    let this = this.clone();
 3445                    async move {
 3446                        this.update(&mut cx, |project, cx| {
 3447                            cx.emit(Event::RefreshInlayHints);
 3448                            project.remote_id().map(|project_id| {
 3449                                project.client.send(proto::RefreshInlayHints { project_id })
 3450                            })
 3451                        })?
 3452                        .transpose()?;
 3453                        Ok(())
 3454                    }
 3455                }
 3456            })
 3457            .detach();
 3458
 3459        language_server
 3460            .on_request::<lsp::request::ShowMessageRequest, _, _>({
 3461                let this = this.clone();
 3462                let name = name.to_string();
 3463                move |params, mut cx| {
 3464                    let this = this.clone();
 3465                    let name = name.to_string();
 3466                    async move {
 3467                        if let Some(actions) = params.actions {
 3468                            let (tx, mut rx) = smol::channel::bounded(1);
 3469                            let request = LanguageServerPromptRequest {
 3470                                level: match params.typ {
 3471                                    lsp::MessageType::ERROR => PromptLevel::Critical,
 3472                                    lsp::MessageType::WARNING => PromptLevel::Warning,
 3473                                    _ => PromptLevel::Info,
 3474                                },
 3475                                message: params.message,
 3476                                actions,
 3477                                response_channel: tx,
 3478                                lsp_name: name.clone(),
 3479                            };
 3480
 3481                            if let Ok(_) = this.update(&mut cx, |_, cx| {
 3482                                cx.emit(Event::LanguageServerPrompt(request));
 3483                            }) {
 3484                                let response = rx.next().await;
 3485
 3486                                Ok(response)
 3487                            } else {
 3488                                Ok(None)
 3489                            }
 3490                        } else {
 3491                            Ok(None)
 3492                        }
 3493                    }
 3494                }
 3495            })
 3496            .detach();
 3497
 3498        let disk_based_diagnostics_progress_token =
 3499            adapter.disk_based_diagnostics_progress_token.clone();
 3500
 3501        language_server
 3502            .on_notification::<ServerStatus, _>({
 3503                let this = this.clone();
 3504                let name = name.to_string();
 3505                move |params, mut cx| {
 3506                    let this = this.clone();
 3507                    let name = name.to_string();
 3508                    if let Some(ref message) = params.message {
 3509                        let message = message.trim();
 3510                        if !message.is_empty() {
 3511                            let formatted_message = format!(
 3512                                "Language server {name} (id {server_id}) status update: {message}"
 3513                            );
 3514                            match params.health {
 3515                                ServerHealthStatus::Ok => log::info!("{}", formatted_message),
 3516                                ServerHealthStatus::Warning => log::warn!("{}", formatted_message),
 3517                                ServerHealthStatus::Error => {
 3518                                    log::error!("{}", formatted_message);
 3519                                    let (tx, _rx) = smol::channel::bounded(1);
 3520                                    let request = LanguageServerPromptRequest {
 3521                                        level: PromptLevel::Critical,
 3522                                        message: params.message.unwrap_or_default(),
 3523                                        actions: Vec::new(),
 3524                                        response_channel: tx,
 3525                                        lsp_name: name.clone(),
 3526                                    };
 3527                                    let _ = this
 3528                                        .update(&mut cx, |_, cx| {
 3529                                            cx.emit(Event::LanguageServerPrompt(request));
 3530                                        })
 3531                                        .ok();
 3532                                }
 3533                                ServerHealthStatus::Other(status) => {
 3534                                    log::info!(
 3535                                        "Unknown server health: {status}\n{formatted_message}"
 3536                                    )
 3537                                }
 3538                            }
 3539                        }
 3540                    }
 3541                }
 3542            })
 3543            .detach();
 3544
 3545        language_server
 3546            .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
 3547                if let Some(this) = this.upgrade() {
 3548                    this.update(&mut cx, |this, cx| {
 3549                        this.on_lsp_progress(
 3550                            params,
 3551                            server_id,
 3552                            disk_based_diagnostics_progress_token.clone(),
 3553                            cx,
 3554                        );
 3555                    })
 3556                    .ok();
 3557                }
 3558            })
 3559            .detach();
 3560
 3561        match (&mut initialization_options, override_options) {
 3562            (Some(initialization_options), Some(override_options)) => {
 3563                merge_json_value_into(override_options, initialization_options);
 3564            }
 3565            (None, override_options) => initialization_options = override_options,
 3566            _ => {}
 3567        }
 3568        let language_server = cx
 3569            .update(|cx| language_server.initialize(initialization_options, cx))?
 3570            .await?;
 3571
 3572        language_server
 3573            .notify::<lsp::notification::DidChangeConfiguration>(
 3574                lsp::DidChangeConfigurationParams {
 3575                    settings: workspace_config,
 3576                },
 3577            )
 3578            .ok();
 3579
 3580        Ok(language_server)
 3581    }
 3582
 3583    fn insert_newly_running_language_server(
 3584        &mut self,
 3585        language: Arc<Language>,
 3586        adapter: Arc<CachedLspAdapter>,
 3587        language_server: Arc<LanguageServer>,
 3588        server_id: LanguageServerId,
 3589        key: (WorktreeId, LanguageServerName),
 3590        cx: &mut ModelContext<Self>,
 3591    ) -> Result<()> {
 3592        // If the language server for this key doesn't match the server id, don't store the
 3593        // server. Which will cause it to be dropped, killing the process
 3594        if self
 3595            .language_server_ids
 3596            .get(&key)
 3597            .map(|id| id != &server_id)
 3598            .unwrap_or(false)
 3599        {
 3600            return Ok(());
 3601        }
 3602
 3603        // Update language_servers collection with Running variant of LanguageServerState
 3604        // indicating that the server is up and running and ready
 3605        self.language_servers.insert(
 3606            server_id,
 3607            LanguageServerState::Running {
 3608                adapter: adapter.clone(),
 3609                language: language.clone(),
 3610                server: language_server.clone(),
 3611                simulate_disk_based_diagnostics_completion: None,
 3612            },
 3613        );
 3614
 3615        self.language_server_statuses.insert(
 3616            server_id,
 3617            LanguageServerStatus {
 3618                name: language_server.name().to_string(),
 3619                pending_work: Default::default(),
 3620                has_pending_diagnostic_updates: false,
 3621                progress_tokens: Default::default(),
 3622            },
 3623        );
 3624
 3625        cx.emit(Event::LanguageServerAdded(server_id));
 3626
 3627        if let Some(project_id) = self.remote_id() {
 3628            self.client.send(proto::StartLanguageServer {
 3629                project_id,
 3630                server: Some(proto::LanguageServer {
 3631                    id: server_id.0 as u64,
 3632                    name: language_server.name().to_string(),
 3633                }),
 3634            })?;
 3635        }
 3636
 3637        // Tell the language server about every open buffer in the worktree that matches the language.
 3638        for buffer in self.opened_buffers.values() {
 3639            if let Some(buffer_handle) = buffer.upgrade() {
 3640                let buffer = buffer_handle.read(cx);
 3641                let file = match File::from_dyn(buffer.file()) {
 3642                    Some(file) => file,
 3643                    None => continue,
 3644                };
 3645                let language = match buffer.language() {
 3646                    Some(language) => language,
 3647                    None => continue,
 3648                };
 3649
 3650                if file.worktree.read(cx).id() != key.0
 3651                    || !self
 3652                        .languages
 3653                        .lsp_adapters(&language)
 3654                        .iter()
 3655                        .any(|a| a.name == key.1)
 3656                {
 3657                    continue;
 3658                }
 3659
 3660                let file = match file.as_local() {
 3661                    Some(file) => file,
 3662                    None => continue,
 3663                };
 3664
 3665                let versions = self
 3666                    .buffer_snapshots
 3667                    .entry(buffer.remote_id())
 3668                    .or_default()
 3669                    .entry(server_id)
 3670                    .or_insert_with(|| {
 3671                        vec![LspBufferSnapshot {
 3672                            version: 0,
 3673                            snapshot: buffer.text_snapshot(),
 3674                        }]
 3675                    });
 3676
 3677                let snapshot = versions.last().unwrap();
 3678                let version = snapshot.version;
 3679                let initial_snapshot = &snapshot.snapshot;
 3680                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
 3681                language_server.notify::<lsp::notification::DidOpenTextDocument>(
 3682                    lsp::DidOpenTextDocumentParams {
 3683                        text_document: lsp::TextDocumentItem::new(
 3684                            uri,
 3685                            adapter
 3686                                .language_ids
 3687                                .get(language.name().as_ref())
 3688                                .cloned()
 3689                                .unwrap_or_default(),
 3690                            version,
 3691                            initial_snapshot.text(),
 3692                        ),
 3693                    },
 3694                )?;
 3695
 3696                buffer_handle.update(cx, |buffer, cx| {
 3697                    buffer.set_completion_triggers(
 3698                        language_server
 3699                            .capabilities()
 3700                            .completion_provider
 3701                            .as_ref()
 3702                            .and_then(|provider| provider.trigger_characters.clone())
 3703                            .unwrap_or_default(),
 3704                        cx,
 3705                    )
 3706                });
 3707            }
 3708        }
 3709
 3710        cx.notify();
 3711        Ok(())
 3712    }
 3713
 3714    // Returns a list of all of the worktrees which no longer have a language server and the root path
 3715    // for the stopped server
 3716    fn stop_language_server(
 3717        &mut self,
 3718        worktree_id: WorktreeId,
 3719        adapter_name: LanguageServerName,
 3720        cx: &mut ModelContext<Self>,
 3721    ) -> Task<Vec<WorktreeId>> {
 3722        let key = (worktree_id, adapter_name);
 3723        if let Some(server_id) = self.language_server_ids.remove(&key) {
 3724            let name = key.1 .0;
 3725            log::info!("stopping language server {name}");
 3726
 3727            // Remove other entries for this language server as well
 3728            let mut orphaned_worktrees = vec![worktree_id];
 3729            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
 3730            for other_key in other_keys {
 3731                if self.language_server_ids.get(&other_key) == Some(&server_id) {
 3732                    self.language_server_ids.remove(&other_key);
 3733                    orphaned_worktrees.push(other_key.0);
 3734                }
 3735            }
 3736
 3737            for buffer in self.opened_buffers.values() {
 3738                if let Some(buffer) = buffer.upgrade() {
 3739                    buffer.update(cx, |buffer, cx| {
 3740                        buffer.update_diagnostics(server_id, Default::default(), cx);
 3741                    });
 3742                }
 3743            }
 3744            for worktree in &self.worktrees {
 3745                if let Some(worktree) = worktree.upgrade() {
 3746                    worktree.update(cx, |worktree, cx| {
 3747                        if let Some(worktree) = worktree.as_local_mut() {
 3748                            worktree.clear_diagnostics_for_language_server(server_id, cx);
 3749                        }
 3750                    });
 3751                }
 3752            }
 3753
 3754            self.language_server_watched_paths.remove(&server_id);
 3755            self.language_server_statuses.remove(&server_id);
 3756            cx.notify();
 3757
 3758            let server_state = self.language_servers.remove(&server_id);
 3759            cx.emit(Event::LanguageServerRemoved(server_id));
 3760            cx.spawn(move |_, cx| async move {
 3761                Self::shutdown_language_server(server_state, name, cx).await;
 3762                orphaned_worktrees
 3763            })
 3764        } else {
 3765            Task::ready(Vec::new())
 3766        }
 3767    }
 3768
 3769    async fn shutdown_language_server(
 3770        server_state: Option<LanguageServerState>,
 3771        name: Arc<str>,
 3772        cx: AsyncAppContext,
 3773    ) {
 3774        let server = match server_state {
 3775            Some(LanguageServerState::Starting(task)) => {
 3776                let mut timer = cx
 3777                    .background_executor()
 3778                    .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
 3779                    .fuse();
 3780
 3781                select! {
 3782                    server = task.fuse() => server,
 3783                    _ = timer => {
 3784                        log::info!(
 3785                            "timeout waiting for language server {} to finish launching before stopping",
 3786                            name
 3787                        );
 3788                        None
 3789                    },
 3790                }
 3791            }
 3792
 3793            Some(LanguageServerState::Running { server, .. }) => Some(server),
 3794
 3795            None => None,
 3796        };
 3797
 3798        if let Some(server) = server {
 3799            if let Some(shutdown) = server.shutdown() {
 3800                shutdown.await;
 3801            }
 3802        }
 3803    }
 3804
 3805    pub fn restart_language_servers_for_buffers(
 3806        &mut self,
 3807        buffers: impl IntoIterator<Item = Model<Buffer>>,
 3808        cx: &mut ModelContext<Self>,
 3809    ) -> Option<()> {
 3810        let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
 3811            .into_iter()
 3812            .filter_map(|buffer| {
 3813                let buffer = buffer.read(cx);
 3814                let file = buffer.file()?;
 3815                let worktree = File::from_dyn(Some(file))?.worktree.clone();
 3816                let language = self
 3817                    .languages
 3818                    .language_for_file(file, Some(buffer.as_rope()), cx)
 3819                    .now_or_never()?
 3820                    .ok()?;
 3821                Some((worktree, language))
 3822            })
 3823            .collect();
 3824        for (worktree, language) in language_server_lookup_info {
 3825            self.restart_language_servers(worktree, language, cx);
 3826        }
 3827
 3828        None
 3829    }
 3830
 3831    fn restart_language_servers(
 3832        &mut self,
 3833        worktree: Model<Worktree>,
 3834        language: Arc<Language>,
 3835        cx: &mut ModelContext<Self>,
 3836    ) {
 3837        let worktree_id = worktree.read(cx).id();
 3838
 3839        let stop_tasks = self
 3840            .languages
 3841            .clone()
 3842            .lsp_adapters(&language)
 3843            .iter()
 3844            .map(|adapter| {
 3845                let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
 3846                (stop_task, adapter.name.clone())
 3847            })
 3848            .collect::<Vec<_>>();
 3849        if stop_tasks.is_empty() {
 3850            return;
 3851        }
 3852
 3853        cx.spawn(move |this, mut cx| async move {
 3854            // For each stopped language server, record all of the worktrees with which
 3855            // it was associated.
 3856            let mut affected_worktrees = Vec::new();
 3857            for (stop_task, language_server_name) in stop_tasks {
 3858                for affected_worktree_id in stop_task.await {
 3859                    affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
 3860                }
 3861            }
 3862
 3863            this.update(&mut cx, |this, cx| {
 3864                // Restart the language server for the given worktree.
 3865                this.start_language_servers(&worktree, language.clone(), cx);
 3866
 3867                // Lookup new server ids and set them for each of the orphaned worktrees
 3868                for (affected_worktree_id, language_server_name) in affected_worktrees {
 3869                    if let Some(new_server_id) = this
 3870                        .language_server_ids
 3871                        .get(&(worktree_id, language_server_name.clone()))
 3872                        .cloned()
 3873                    {
 3874                        this.language_server_ids
 3875                            .insert((affected_worktree_id, language_server_name), new_server_id);
 3876                    }
 3877                }
 3878            })
 3879            .ok();
 3880        })
 3881        .detach();
 3882    }
 3883
 3884    fn check_errored_server(
 3885        language: Arc<Language>,
 3886        adapter: Arc<CachedLspAdapter>,
 3887        server_id: LanguageServerId,
 3888        installation_test_binary: Option<LanguageServerBinary>,
 3889        cx: &mut ModelContext<Self>,
 3890    ) {
 3891        if !adapter.can_be_reinstalled() {
 3892            log::info!(
 3893                "Validation check requested for {:?} but it cannot be reinstalled",
 3894                adapter.name.0
 3895            );
 3896            return;
 3897        }
 3898
 3899        cx.spawn(move |this, mut cx| async move {
 3900            log::info!("About to spawn test binary");
 3901
 3902            // A lack of test binary counts as a failure
 3903            let process = installation_test_binary.and_then(|binary| {
 3904                smol::process::Command::new(&binary.path)
 3905                    .current_dir(&binary.path)
 3906                    .args(binary.arguments)
 3907                    .stdin(Stdio::piped())
 3908                    .stdout(Stdio::piped())
 3909                    .stderr(Stdio::inherit())
 3910                    .kill_on_drop(true)
 3911                    .spawn()
 3912                    .ok()
 3913            });
 3914
 3915            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
 3916            let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
 3917
 3918            let mut errored = false;
 3919            if let Some(mut process) = process {
 3920                futures::select! {
 3921                    status = process.status().fuse() => match status {
 3922                        Ok(status) => errored = !status.success(),
 3923                        Err(_) => errored = true,
 3924                    },
 3925
 3926                    _ = timeout => {
 3927                        log::info!("test binary time-ed out, this counts as a success");
 3928                        _ = process.kill();
 3929                    }
 3930                }
 3931            } else {
 3932                log::warn!("test binary failed to launch");
 3933                errored = true;
 3934            }
 3935
 3936            if errored {
 3937                log::warn!("test binary check failed");
 3938                let task = this
 3939                    .update(&mut cx, move |this, cx| {
 3940                        this.reinstall_language_server(language, adapter, server_id, cx)
 3941                    })
 3942                    .ok()
 3943                    .flatten();
 3944
 3945                if let Some(task) = task {
 3946                    task.await;
 3947                }
 3948            }
 3949        })
 3950        .detach();
 3951    }
 3952
 3953    fn enqueue_language_server_progress(
 3954        &mut self,
 3955        message: BufferOrderedMessage,
 3956        cx: &mut ModelContext<Self>,
 3957    ) {
 3958        self.pending_language_server_update.replace(message);
 3959        self.flush_language_server_update.get_or_insert_with(|| {
 3960            cx.spawn(|this, mut cx| async move {
 3961                cx.background_executor()
 3962                    .timer(SERVER_PROGRESS_DEBOUNCE_TIMEOUT)
 3963                    .await;
 3964                this.update(&mut cx, |this, _| {
 3965                    this.flush_language_server_update.take();
 3966                    if let Some(update) = this.pending_language_server_update.take() {
 3967                        this.enqueue_buffer_ordered_message(update).ok();
 3968                    }
 3969                })
 3970                .ok();
 3971            })
 3972        });
 3973    }
 3974
 3975    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
 3976        if let Some(pending_message) = self.pending_language_server_update.take() {
 3977            self.flush_language_server_update.take();
 3978            self.buffer_ordered_messages_tx
 3979                .unbounded_send(pending_message)
 3980                .map_err(|e| anyhow!(e))?;
 3981        }
 3982        self.buffer_ordered_messages_tx
 3983            .unbounded_send(message)
 3984            .map_err(|e| anyhow!(e))
 3985    }
 3986
 3987    fn on_lsp_progress(
 3988        &mut self,
 3989        progress: lsp::ProgressParams,
 3990        language_server_id: LanguageServerId,
 3991        disk_based_diagnostics_progress_token: Option<String>,
 3992        cx: &mut ModelContext<Self>,
 3993    ) {
 3994        let token = match progress.token {
 3995            lsp::NumberOrString::String(token) => token,
 3996            lsp::NumberOrString::Number(token) => {
 3997                log::info!("skipping numeric progress token {}", token);
 3998                return;
 3999            }
 4000        };
 4001        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
 4002        let language_server_status =
 4003            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4004                status
 4005            } else {
 4006                return;
 4007            };
 4008
 4009        if !language_server_status.progress_tokens.contains(&token) {
 4010            return;
 4011        }
 4012
 4013        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
 4014            .as_ref()
 4015            .map_or(false, |disk_based_token| {
 4016                token.starts_with(disk_based_token)
 4017            });
 4018
 4019        match progress {
 4020            lsp::WorkDoneProgress::Begin(report) => {
 4021                if is_disk_based_diagnostics_progress {
 4022                    language_server_status.has_pending_diagnostic_updates = true;
 4023                    self.disk_based_diagnostics_started(language_server_id, cx);
 4024                    self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 4025                            language_server_id,
 4026                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
 4027                        })
 4028                        .ok();
 4029                } else {
 4030                    self.on_lsp_work_start(
 4031                        language_server_id,
 4032                        token.clone(),
 4033                        LanguageServerProgress {
 4034                            message: report.message.clone(),
 4035                            percentage: report.percentage.map(|p| p as usize),
 4036                            last_update_at: Instant::now(),
 4037                        },
 4038                        cx,
 4039                    );
 4040                }
 4041            }
 4042            lsp::WorkDoneProgress::Report(report) => {
 4043                if !is_disk_based_diagnostics_progress {
 4044                    self.on_lsp_work_progress(
 4045                        language_server_id,
 4046                        token.clone(),
 4047                        LanguageServerProgress {
 4048                            message: report.message.clone(),
 4049                            percentage: report.percentage.map(|p| p as usize),
 4050                            last_update_at: Instant::now(),
 4051                        },
 4052                        cx,
 4053                    );
 4054                    self.enqueue_language_server_progress(
 4055                        BufferOrderedMessage::LanguageServerUpdate {
 4056                            language_server_id,
 4057                            message: proto::update_language_server::Variant::WorkProgress(
 4058                                proto::LspWorkProgress {
 4059                                    token,
 4060                                    message: report.message,
 4061                                    percentage: report.percentage,
 4062                                },
 4063                            ),
 4064                        },
 4065                        cx,
 4066                    );
 4067                }
 4068            }
 4069            lsp::WorkDoneProgress::End(_) => {
 4070                language_server_status.progress_tokens.remove(&token);
 4071
 4072                if is_disk_based_diagnostics_progress {
 4073                    language_server_status.has_pending_diagnostic_updates = false;
 4074                    self.disk_based_diagnostics_finished(language_server_id, cx);
 4075                    self.enqueue_buffer_ordered_message(
 4076                        BufferOrderedMessage::LanguageServerUpdate {
 4077                            language_server_id,
 4078                            message:
 4079                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
 4080                                    Default::default(),
 4081                                ),
 4082                        },
 4083                    )
 4084                    .ok();
 4085                } else {
 4086                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
 4087                }
 4088            }
 4089        }
 4090    }
 4091
 4092    fn on_lsp_work_start(
 4093        &mut self,
 4094        language_server_id: LanguageServerId,
 4095        token: String,
 4096        progress: LanguageServerProgress,
 4097        cx: &mut ModelContext<Self>,
 4098    ) {
 4099        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4100            status.pending_work.insert(token.clone(), progress.clone());
 4101            cx.notify();
 4102        }
 4103
 4104        if self.is_local() {
 4105            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 4106                language_server_id,
 4107                message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
 4108                    token,
 4109                    message: progress.message,
 4110                    percentage: progress.percentage.map(|p| p as u32),
 4111                }),
 4112            })
 4113            .ok();
 4114        }
 4115    }
 4116
 4117    fn on_lsp_work_progress(
 4118        &mut self,
 4119        language_server_id: LanguageServerId,
 4120        token: String,
 4121        progress: LanguageServerProgress,
 4122        cx: &mut ModelContext<Self>,
 4123    ) {
 4124        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4125            let entry = status
 4126                .pending_work
 4127                .entry(token)
 4128                .or_insert(LanguageServerProgress {
 4129                    message: Default::default(),
 4130                    percentage: Default::default(),
 4131                    last_update_at: progress.last_update_at,
 4132                });
 4133            if progress.message.is_some() {
 4134                entry.message = progress.message;
 4135            }
 4136            if progress.percentage.is_some() {
 4137                entry.percentage = progress.percentage;
 4138            }
 4139            entry.last_update_at = progress.last_update_at;
 4140            cx.notify();
 4141        }
 4142    }
 4143
 4144    fn on_lsp_work_end(
 4145        &mut self,
 4146        language_server_id: LanguageServerId,
 4147        token: String,
 4148        cx: &mut ModelContext<Self>,
 4149    ) {
 4150        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4151            cx.emit(Event::RefreshInlayHints);
 4152            status.pending_work.remove(&token);
 4153            cx.notify();
 4154        }
 4155
 4156        if self.is_local() {
 4157            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 4158                language_server_id,
 4159                message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
 4160                    token,
 4161                }),
 4162            })
 4163            .ok();
 4164        }
 4165    }
 4166
 4167    fn on_lsp_did_change_watched_files(
 4168        &mut self,
 4169        language_server_id: LanguageServerId,
 4170        params: DidChangeWatchedFilesRegistrationOptions,
 4171        cx: &mut ModelContext<Self>,
 4172    ) {
 4173        let watched_paths = self
 4174            .language_server_watched_paths
 4175            .entry(language_server_id)
 4176            .or_default();
 4177
 4178        let mut builders = HashMap::default();
 4179        for watcher in params.watchers {
 4180            for worktree in &self.worktrees {
 4181                if let Some(worktree) = worktree.upgrade() {
 4182                    let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
 4183                        if let Some(abs_path) = tree.abs_path().to_str() {
 4184                            let relative_glob_pattern = match &watcher.glob_pattern {
 4185                                lsp::GlobPattern::String(s) => Some(
 4186                                    s.strip_prefix(abs_path)
 4187                                        .unwrap_or(s)
 4188                                        .strip_prefix(std::path::MAIN_SEPARATOR)
 4189                                        .unwrap_or(s),
 4190                                ),
 4191                                lsp::GlobPattern::Relative(rp) => {
 4192                                    let base_uri = match &rp.base_uri {
 4193                                        lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
 4194                                        lsp::OneOf::Right(base_uri) => base_uri,
 4195                                    };
 4196                                    base_uri.to_file_path().ok().and_then(|file_path| {
 4197                                        (file_path.to_str() == Some(abs_path))
 4198                                            .then_some(rp.pattern.as_str())
 4199                                    })
 4200                                }
 4201                            };
 4202                            if let Some(relative_glob_pattern) = relative_glob_pattern {
 4203                                let literal_prefix = glob_literal_prefix(relative_glob_pattern);
 4204                                tree.as_local_mut()
 4205                                    .unwrap()
 4206                                    .add_path_prefix_to_scan(Path::new(literal_prefix).into());
 4207                                if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
 4208                                    builders
 4209                                        .entry(tree.id())
 4210                                        .or_insert_with(|| GlobSetBuilder::new())
 4211                                        .add(glob);
 4212                                }
 4213                                return true;
 4214                            }
 4215                        }
 4216                        false
 4217                    });
 4218                    if glob_is_inside_worktree {
 4219                        break;
 4220                    }
 4221                }
 4222            }
 4223        }
 4224
 4225        watched_paths.clear();
 4226        for (worktree_id, builder) in builders {
 4227            if let Ok(globset) = builder.build() {
 4228                watched_paths.insert(worktree_id, globset);
 4229            }
 4230        }
 4231
 4232        cx.notify();
 4233    }
 4234
 4235    async fn on_lsp_workspace_edit(
 4236        this: WeakModel<Self>,
 4237        params: lsp::ApplyWorkspaceEditParams,
 4238        server_id: LanguageServerId,
 4239        adapter: Arc<CachedLspAdapter>,
 4240        mut cx: AsyncAppContext,
 4241    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
 4242        let this = this
 4243            .upgrade()
 4244            .ok_or_else(|| anyhow!("project project closed"))?;
 4245        let language_server = this
 4246            .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
 4247            .ok_or_else(|| anyhow!("language server not found"))?;
 4248        let transaction = Self::deserialize_workspace_edit(
 4249            this.clone(),
 4250            params.edit,
 4251            true,
 4252            adapter.clone(),
 4253            language_server.clone(),
 4254            &mut cx,
 4255        )
 4256        .await
 4257        .log_err();
 4258        this.update(&mut cx, |this, _| {
 4259            if let Some(transaction) = transaction {
 4260                this.last_workspace_edits_by_language_server
 4261                    .insert(server_id, transaction);
 4262            }
 4263        })?;
 4264        Ok(lsp::ApplyWorkspaceEditResponse {
 4265            applied: true,
 4266            failed_change: None,
 4267            failure_reason: None,
 4268        })
 4269    }
 4270
 4271    pub fn language_server_statuses(
 4272        &self,
 4273    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
 4274        self.language_server_statuses.values()
 4275    }
 4276
 4277    pub fn last_formatting_failure(&self) -> Option<&str> {
 4278        self.last_formatting_failure.as_deref()
 4279    }
 4280
 4281    pub fn update_diagnostics(
 4282        &mut self,
 4283        language_server_id: LanguageServerId,
 4284        mut params: lsp::PublishDiagnosticsParams,
 4285        disk_based_sources: &[String],
 4286        cx: &mut ModelContext<Self>,
 4287    ) -> Result<()> {
 4288        let abs_path = params
 4289            .uri
 4290            .to_file_path()
 4291            .map_err(|_| anyhow!("URI is not a file"))?;
 4292        let mut diagnostics = Vec::default();
 4293        let mut primary_diagnostic_group_ids = HashMap::default();
 4294        let mut sources_by_group_id = HashMap::default();
 4295        let mut supporting_diagnostics = HashMap::default();
 4296
 4297        // Ensure that primary diagnostics are always the most severe
 4298        params.diagnostics.sort_by_key(|item| item.severity);
 4299
 4300        for diagnostic in &params.diagnostics {
 4301            let source = diagnostic.source.as_ref();
 4302            let code = diagnostic.code.as_ref().map(|code| match code {
 4303                lsp::NumberOrString::Number(code) => code.to_string(),
 4304                lsp::NumberOrString::String(code) => code.clone(),
 4305            });
 4306            let range = range_from_lsp(diagnostic.range);
 4307            let is_supporting = diagnostic
 4308                .related_information
 4309                .as_ref()
 4310                .map_or(false, |infos| {
 4311                    infos.iter().any(|info| {
 4312                        primary_diagnostic_group_ids.contains_key(&(
 4313                            source,
 4314                            code.clone(),
 4315                            range_from_lsp(info.location.range),
 4316                        ))
 4317                    })
 4318                });
 4319
 4320            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
 4321                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
 4322            });
 4323
 4324            if is_supporting {
 4325                supporting_diagnostics.insert(
 4326                    (source, code.clone(), range),
 4327                    (diagnostic.severity, is_unnecessary),
 4328                );
 4329            } else {
 4330                let group_id = post_inc(&mut self.next_diagnostic_group_id);
 4331                let is_disk_based =
 4332                    source.map_or(false, |source| disk_based_sources.contains(source));
 4333
 4334                sources_by_group_id.insert(group_id, source);
 4335                primary_diagnostic_group_ids
 4336                    .insert((source, code.clone(), range.clone()), group_id);
 4337
 4338                diagnostics.push(DiagnosticEntry {
 4339                    range,
 4340                    diagnostic: Diagnostic {
 4341                        source: diagnostic.source.clone(),
 4342                        code: code.clone(),
 4343                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
 4344                        message: diagnostic.message.trim().to_string(),
 4345                        group_id,
 4346                        is_primary: true,
 4347                        is_disk_based,
 4348                        is_unnecessary,
 4349                    },
 4350                });
 4351                if let Some(infos) = &diagnostic.related_information {
 4352                    for info in infos {
 4353                        if info.location.uri == params.uri && !info.message.is_empty() {
 4354                            let range = range_from_lsp(info.location.range);
 4355                            diagnostics.push(DiagnosticEntry {
 4356                                range,
 4357                                diagnostic: Diagnostic {
 4358                                    source: diagnostic.source.clone(),
 4359                                    code: code.clone(),
 4360                                    severity: DiagnosticSeverity::INFORMATION,
 4361                                    message: info.message.trim().to_string(),
 4362                                    group_id,
 4363                                    is_primary: false,
 4364                                    is_disk_based,
 4365                                    is_unnecessary: false,
 4366                                },
 4367                            });
 4368                        }
 4369                    }
 4370                }
 4371            }
 4372        }
 4373
 4374        for entry in &mut diagnostics {
 4375            let diagnostic = &mut entry.diagnostic;
 4376            if !diagnostic.is_primary {
 4377                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
 4378                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
 4379                    source,
 4380                    diagnostic.code.clone(),
 4381                    entry.range.clone(),
 4382                )) {
 4383                    if let Some(severity) = severity {
 4384                        diagnostic.severity = severity;
 4385                    }
 4386                    diagnostic.is_unnecessary = is_unnecessary;
 4387                }
 4388            }
 4389        }
 4390
 4391        self.update_diagnostic_entries(
 4392            language_server_id,
 4393            abs_path,
 4394            params.version,
 4395            diagnostics,
 4396            cx,
 4397        )?;
 4398        Ok(())
 4399    }
 4400
 4401    pub fn update_diagnostic_entries(
 4402        &mut self,
 4403        server_id: LanguageServerId,
 4404        abs_path: PathBuf,
 4405        version: Option<i32>,
 4406        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 4407        cx: &mut ModelContext<Project>,
 4408    ) -> Result<(), anyhow::Error> {
 4409        let (worktree, relative_path) = self
 4410            .find_local_worktree(&abs_path, cx)
 4411            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
 4412
 4413        let project_path = ProjectPath {
 4414            worktree_id: worktree.read(cx).id(),
 4415            path: relative_path.into(),
 4416        };
 4417
 4418        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
 4419            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
 4420        }
 4421
 4422        let updated = worktree.update(cx, |worktree, cx| {
 4423            worktree
 4424                .as_local_mut()
 4425                .ok_or_else(|| anyhow!("not a local worktree"))?
 4426                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
 4427        })?;
 4428        if updated {
 4429            cx.emit(Event::DiagnosticsUpdated {
 4430                language_server_id: server_id,
 4431                path: project_path,
 4432            });
 4433        }
 4434        Ok(())
 4435    }
 4436
 4437    fn update_buffer_diagnostics(
 4438        &mut self,
 4439        buffer: &Model<Buffer>,
 4440        server_id: LanguageServerId,
 4441        version: Option<i32>,
 4442        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 4443        cx: &mut ModelContext<Self>,
 4444    ) -> Result<()> {
 4445        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
 4446            Ordering::Equal
 4447                .then_with(|| b.is_primary.cmp(&a.is_primary))
 4448                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
 4449                .then_with(|| a.severity.cmp(&b.severity))
 4450                .then_with(|| a.message.cmp(&b.message))
 4451        }
 4452
 4453        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
 4454
 4455        diagnostics.sort_unstable_by(|a, b| {
 4456            Ordering::Equal
 4457                .then_with(|| a.range.start.cmp(&b.range.start))
 4458                .then_with(|| b.range.end.cmp(&a.range.end))
 4459                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
 4460        });
 4461
 4462        let mut sanitized_diagnostics = Vec::new();
 4463        let edits_since_save = Patch::new(
 4464            snapshot
 4465                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
 4466                .collect(),
 4467        );
 4468        for entry in diagnostics {
 4469            let start;
 4470            let end;
 4471            if entry.diagnostic.is_disk_based {
 4472                // Some diagnostics are based on files on disk instead of buffers'
 4473                // current contents. Adjust these diagnostics' ranges to reflect
 4474                // any unsaved edits.
 4475                start = edits_since_save.old_to_new(entry.range.start);
 4476                end = edits_since_save.old_to_new(entry.range.end);
 4477            } else {
 4478                start = entry.range.start;
 4479                end = entry.range.end;
 4480            }
 4481
 4482            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
 4483                ..snapshot.clip_point_utf16(end, Bias::Right);
 4484
 4485            // Expand empty ranges by one codepoint
 4486            if range.start == range.end {
 4487                // This will be go to the next boundary when being clipped
 4488                range.end.column += 1;
 4489                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
 4490                if range.start == range.end && range.end.column > 0 {
 4491                    range.start.column -= 1;
 4492                    range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
 4493                }
 4494            }
 4495
 4496            sanitized_diagnostics.push(DiagnosticEntry {
 4497                range,
 4498                diagnostic: entry.diagnostic,
 4499            });
 4500        }
 4501        drop(edits_since_save);
 4502
 4503        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
 4504        buffer.update(cx, |buffer, cx| {
 4505            buffer.update_diagnostics(server_id, set, cx)
 4506        });
 4507        Ok(())
 4508    }
 4509
 4510    pub fn reload_buffers(
 4511        &self,
 4512        buffers: HashSet<Model<Buffer>>,
 4513        push_to_history: bool,
 4514        cx: &mut ModelContext<Self>,
 4515    ) -> Task<Result<ProjectTransaction>> {
 4516        let mut local_buffers = Vec::new();
 4517        let mut remote_buffers = None;
 4518        for buffer_handle in buffers {
 4519            let buffer = buffer_handle.read(cx);
 4520            if buffer.is_dirty() {
 4521                if let Some(file) = File::from_dyn(buffer.file()) {
 4522                    if file.is_local() {
 4523                        local_buffers.push(buffer_handle);
 4524                    } else {
 4525                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
 4526                    }
 4527                }
 4528            }
 4529        }
 4530
 4531        let remote_buffers = self.remote_id().zip(remote_buffers);
 4532        let client = self.client.clone();
 4533
 4534        cx.spawn(move |this, mut cx| async move {
 4535            let mut project_transaction = ProjectTransaction::default();
 4536
 4537            if let Some((project_id, remote_buffers)) = remote_buffers {
 4538                let response = client
 4539                    .request(proto::ReloadBuffers {
 4540                        project_id,
 4541                        buffer_ids: remote_buffers
 4542                            .iter()
 4543                            .filter_map(|buffer| {
 4544                                buffer
 4545                                    .update(&mut cx, |buffer, _| buffer.remote_id().into())
 4546                                    .ok()
 4547                            })
 4548                            .collect(),
 4549                    })
 4550                    .await?
 4551                    .transaction
 4552                    .ok_or_else(|| anyhow!("missing transaction"))?;
 4553                project_transaction = this
 4554                    .update(&mut cx, |this, cx| {
 4555                        this.deserialize_project_transaction(response, push_to_history, cx)
 4556                    })?
 4557                    .await?;
 4558            }
 4559
 4560            for buffer in local_buffers {
 4561                let transaction = buffer
 4562                    .update(&mut cx, |buffer, cx| buffer.reload(cx))?
 4563                    .await?;
 4564                buffer.update(&mut cx, |buffer, cx| {
 4565                    if let Some(transaction) = transaction {
 4566                        if !push_to_history {
 4567                            buffer.forget_transaction(transaction.id);
 4568                        }
 4569                        project_transaction.0.insert(cx.handle(), transaction);
 4570                    }
 4571                })?;
 4572            }
 4573
 4574            Ok(project_transaction)
 4575        })
 4576    }
 4577
 4578    pub fn format(
 4579        &mut self,
 4580        buffers: HashSet<Model<Buffer>>,
 4581        push_to_history: bool,
 4582        trigger: FormatTrigger,
 4583        cx: &mut ModelContext<Project>,
 4584    ) -> Task<anyhow::Result<ProjectTransaction>> {
 4585        if self.is_local() {
 4586            let buffers_with_paths = buffers
 4587                .into_iter()
 4588                .filter_map(|buffer_handle| {
 4589                    let buffer = buffer_handle.read(cx);
 4590                    let file = File::from_dyn(buffer.file())?;
 4591                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
 4592                    Some((buffer_handle, buffer_abs_path))
 4593                })
 4594                .collect::<Vec<_>>();
 4595
 4596            cx.spawn(move |project, mut cx| async move {
 4597                let result = Self::format_locally(
 4598                    project.clone(),
 4599                    buffers_with_paths,
 4600                    push_to_history,
 4601                    trigger,
 4602                    cx.clone(),
 4603                )
 4604                .await;
 4605
 4606                project.update(&mut cx, |project, _| match &result {
 4607                    Ok(_) => project.last_formatting_failure = None,
 4608                    Err(error) => {
 4609                        project.last_formatting_failure.replace(error.to_string());
 4610                    }
 4611                })?;
 4612
 4613                result
 4614            })
 4615        } else {
 4616            let remote_id = self.remote_id();
 4617            let client = self.client.clone();
 4618            cx.spawn(move |this, mut cx| async move {
 4619                let mut project_transaction = ProjectTransaction::default();
 4620                if let Some(project_id) = remote_id {
 4621                    let response = client
 4622                        .request(proto::FormatBuffers {
 4623                            project_id,
 4624                            trigger: trigger as i32,
 4625                            buffer_ids: buffers
 4626                                .iter()
 4627                                .map(|buffer| {
 4628                                    buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
 4629                                })
 4630                                .collect::<Result<_>>()?,
 4631                        })
 4632                        .await?
 4633                        .transaction
 4634                        .ok_or_else(|| anyhow!("missing transaction"))?;
 4635                    project_transaction = this
 4636                        .update(&mut cx, |this, cx| {
 4637                            this.deserialize_project_transaction(response, push_to_history, cx)
 4638                        })?
 4639                        .await?;
 4640                }
 4641                Ok(project_transaction)
 4642            })
 4643        }
 4644    }
 4645
 4646    async fn format_locally(
 4647        project: WeakModel<Project>,
 4648        mut buffers_with_paths: Vec<(Model<Buffer>, Option<PathBuf>)>,
 4649        push_to_history: bool,
 4650        trigger: FormatTrigger,
 4651        mut cx: AsyncAppContext,
 4652    ) -> anyhow::Result<ProjectTransaction> {
 4653        // Do not allow multiple concurrent formatting requests for the
 4654        // same buffer.
 4655        project.update(&mut cx, |this, cx| {
 4656            buffers_with_paths.retain(|(buffer, _)| {
 4657                this.buffers_being_formatted
 4658                    .insert(buffer.read(cx).remote_id())
 4659            });
 4660        })?;
 4661
 4662        let _cleanup = defer({
 4663            let this = project.clone();
 4664            let mut cx = cx.clone();
 4665            let buffers = &buffers_with_paths;
 4666            move || {
 4667                this.update(&mut cx, |this, cx| {
 4668                    for (buffer, _) in buffers {
 4669                        this.buffers_being_formatted
 4670                            .remove(&buffer.read(cx).remote_id());
 4671                    }
 4672                })
 4673                .ok();
 4674            }
 4675        });
 4676
 4677        let mut project_transaction = ProjectTransaction::default();
 4678        for (buffer, buffer_abs_path) in &buffers_with_paths {
 4679            let (primary_adapter_and_server, adapters_and_servers) =
 4680                project.update(&mut cx, |project, cx| {
 4681                    let buffer = buffer.read(cx);
 4682
 4683                    let adapters_and_servers = project
 4684                        .language_servers_for_buffer(buffer, cx)
 4685                        .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
 4686                        .collect::<Vec<_>>();
 4687
 4688                    let primary_adapter = project
 4689                        .primary_language_server_for_buffer(buffer, cx)
 4690                        .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()));
 4691
 4692                    (primary_adapter, adapters_and_servers)
 4693                })?;
 4694
 4695            let settings = buffer.update(&mut cx, |buffer, cx| {
 4696                language_settings(buffer.language(), buffer.file(), cx).clone()
 4697            })?;
 4698
 4699            let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
 4700            let ensure_final_newline = settings.ensure_final_newline_on_save;
 4701            let tab_size = settings.tab_size;
 4702
 4703            // First, format buffer's whitespace according to the settings.
 4704            let trailing_whitespace_diff = if remove_trailing_whitespace {
 4705                Some(
 4706                    buffer
 4707                        .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
 4708                        .await,
 4709                )
 4710            } else {
 4711                None
 4712            };
 4713            let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
 4714                buffer.finalize_last_transaction();
 4715                buffer.start_transaction();
 4716                if let Some(diff) = trailing_whitespace_diff {
 4717                    buffer.apply_diff(diff, cx);
 4718                }
 4719                if ensure_final_newline {
 4720                    buffer.ensure_final_newline(cx);
 4721                }
 4722                buffer.end_transaction(cx)
 4723            })?;
 4724
 4725            // Apply the `code_actions_on_format` before we run the formatter.
 4726            let code_actions = deserialize_code_actions(&settings.code_actions_on_format);
 4727            #[allow(clippy::nonminimal_bool)]
 4728            if !code_actions.is_empty()
 4729                && !(trigger == FormatTrigger::Save && settings.format_on_save == FormatOnSave::Off)
 4730            {
 4731                Self::execute_code_actions_on_servers(
 4732                    &project,
 4733                    &adapters_and_servers,
 4734                    code_actions,
 4735                    buffer,
 4736                    push_to_history,
 4737                    &mut project_transaction,
 4738                    &mut cx,
 4739                )
 4740                .await?;
 4741            }
 4742
 4743            // Apply language-specific formatting using either the primary language server
 4744            // or external command.
 4745            // Except for code actions, which are applied with all connected language servers.
 4746            let primary_language_server =
 4747                primary_adapter_and_server.map(|(_adapter, server)| server.clone());
 4748            let server_and_buffer = primary_language_server
 4749                .as_ref()
 4750                .zip(buffer_abs_path.as_ref());
 4751
 4752            let mut format_operation = None;
 4753            match (&settings.formatter, &settings.format_on_save) {
 4754                (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
 4755
 4756                (Formatter::CodeActions(code_actions), FormatOnSave::On | FormatOnSave::Off)
 4757                | (_, FormatOnSave::CodeActions(code_actions)) => {
 4758                    let code_actions = deserialize_code_actions(code_actions);
 4759                    if !code_actions.is_empty() {
 4760                        Self::execute_code_actions_on_servers(
 4761                            &project,
 4762                            &adapters_and_servers,
 4763                            code_actions,
 4764                            buffer,
 4765                            push_to_history,
 4766                            &mut project_transaction,
 4767                            &mut cx,
 4768                        )
 4769                        .await?;
 4770                    }
 4771                }
 4772                (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
 4773                | (_, FormatOnSave::LanguageServer) => {
 4774                    if let Some((language_server, buffer_abs_path)) = server_and_buffer {
 4775                        format_operation = Some(FormatOperation::Lsp(
 4776                            Self::format_via_lsp(
 4777                                &project,
 4778                                buffer,
 4779                                buffer_abs_path,
 4780                                language_server,
 4781                                tab_size,
 4782                                &mut cx,
 4783                            )
 4784                            .await
 4785                            .context("failed to format via language server")?,
 4786                        ));
 4787                    }
 4788                }
 4789
 4790                (
 4791                    Formatter::External { command, arguments },
 4792                    FormatOnSave::On | FormatOnSave::Off,
 4793                )
 4794                | (_, FormatOnSave::External { command, arguments }) => {
 4795                    if let Some(buffer_abs_path) = buffer_abs_path {
 4796                        format_operation = Self::format_via_external_command(
 4797                            buffer,
 4798                            buffer_abs_path,
 4799                            command,
 4800                            arguments,
 4801                            &mut cx,
 4802                        )
 4803                        .await
 4804                        .context(format!(
 4805                            "failed to format via external command {:?}",
 4806                            command
 4807                        ))?
 4808                        .map(FormatOperation::External);
 4809                    }
 4810                }
 4811                (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
 4812                    let prettier =
 4813                        prettier_support::format_with_prettier(&project, buffer, &mut cx).await;
 4814
 4815                    if let Some(operation) = prettier {
 4816                        format_operation = Some(operation?);
 4817                    } else if let Some((language_server, buffer_abs_path)) = server_and_buffer {
 4818                        format_operation = Some(FormatOperation::Lsp(
 4819                            Self::format_via_lsp(
 4820                                &project,
 4821                                buffer,
 4822                                buffer_abs_path,
 4823                                language_server,
 4824                                tab_size,
 4825                                &mut cx,
 4826                            )
 4827                            .await
 4828                            .context("failed to format via language server")?,
 4829                        ));
 4830                    }
 4831                }
 4832                (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
 4833                    let prettier =
 4834                        prettier_support::format_with_prettier(&project, buffer, &mut cx).await;
 4835
 4836                    if let Some(operation) = prettier {
 4837                        format_operation = Some(operation?);
 4838                    }
 4839                }
 4840            };
 4841
 4842            buffer.update(&mut cx, |b, cx| {
 4843                // If the buffer had its whitespace formatted and was edited while the language-specific
 4844                // formatting was being computed, avoid applying the language-specific formatting, because
 4845                // it can't be grouped with the whitespace formatting in the undo history.
 4846                if let Some(transaction_id) = whitespace_transaction_id {
 4847                    if b.peek_undo_stack()
 4848                        .map_or(true, |e| e.transaction_id() != transaction_id)
 4849                    {
 4850                        format_operation.take();
 4851                    }
 4852                }
 4853
 4854                // Apply any language-specific formatting, and group the two formatting operations
 4855                // in the buffer's undo history.
 4856                if let Some(operation) = format_operation {
 4857                    match operation {
 4858                        FormatOperation::Lsp(edits) => {
 4859                            b.edit(edits, None, cx);
 4860                        }
 4861                        FormatOperation::External(diff) => {
 4862                            b.apply_diff(diff, cx);
 4863                        }
 4864                        FormatOperation::Prettier(diff) => {
 4865                            b.apply_diff(diff, cx);
 4866                        }
 4867                    }
 4868
 4869                    if let Some(transaction_id) = whitespace_transaction_id {
 4870                        b.group_until_transaction(transaction_id);
 4871                    } else if let Some(transaction) = project_transaction.0.get(buffer) {
 4872                        b.group_until_transaction(transaction.id)
 4873                    }
 4874                }
 4875
 4876                if let Some(transaction) = b.finalize_last_transaction().cloned() {
 4877                    if !push_to_history {
 4878                        b.forget_transaction(transaction.id);
 4879                    }
 4880                    project_transaction.0.insert(buffer.clone(), transaction);
 4881                }
 4882            })?;
 4883        }
 4884
 4885        Ok(project_transaction)
 4886    }
 4887
 4888    async fn format_via_lsp(
 4889        this: &WeakModel<Self>,
 4890        buffer: &Model<Buffer>,
 4891        abs_path: &Path,
 4892        language_server: &Arc<LanguageServer>,
 4893        tab_size: NonZeroU32,
 4894        cx: &mut AsyncAppContext,
 4895    ) -> Result<Vec<(Range<Anchor>, String)>> {
 4896        let uri = lsp::Url::from_file_path(abs_path)
 4897            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
 4898        let text_document = lsp::TextDocumentIdentifier::new(uri);
 4899        let capabilities = &language_server.capabilities();
 4900
 4901        let formatting_provider = capabilities.document_formatting_provider.as_ref();
 4902        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
 4903
 4904        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
 4905            language_server
 4906                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
 4907                    text_document,
 4908                    options: lsp_command::lsp_formatting_options(tab_size.get()),
 4909                    work_done_progress_params: Default::default(),
 4910                })
 4911                .await?
 4912        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
 4913            let buffer_start = lsp::Position::new(0, 0);
 4914            let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
 4915
 4916            language_server
 4917                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
 4918                    text_document,
 4919                    range: lsp::Range::new(buffer_start, buffer_end),
 4920                    options: lsp_command::lsp_formatting_options(tab_size.get()),
 4921                    work_done_progress_params: Default::default(),
 4922                })
 4923                .await?
 4924        } else {
 4925            None
 4926        };
 4927
 4928        if let Some(lsp_edits) = lsp_edits {
 4929            this.update(cx, |this, cx| {
 4930                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
 4931            })?
 4932            .await
 4933        } else {
 4934            Ok(Vec::new())
 4935        }
 4936    }
 4937
 4938    async fn format_via_external_command(
 4939        buffer: &Model<Buffer>,
 4940        buffer_abs_path: &Path,
 4941        command: &str,
 4942        arguments: &[String],
 4943        cx: &mut AsyncAppContext,
 4944    ) -> Result<Option<Diff>> {
 4945        let working_dir_path = buffer.update(cx, |buffer, cx| {
 4946            let file = File::from_dyn(buffer.file())?;
 4947            let worktree = file.worktree.read(cx).as_local()?;
 4948            let mut worktree_path = worktree.abs_path().to_path_buf();
 4949            if worktree.root_entry()?.is_file() {
 4950                worktree_path.pop();
 4951            }
 4952            Some(worktree_path)
 4953        })?;
 4954
 4955        if let Some(working_dir_path) = working_dir_path {
 4956            let mut child =
 4957                smol::process::Command::new(command)
 4958                    .args(arguments.iter().map(|arg| {
 4959                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
 4960                    }))
 4961                    .current_dir(&working_dir_path)
 4962                    .stdin(smol::process::Stdio::piped())
 4963                    .stdout(smol::process::Stdio::piped())
 4964                    .stderr(smol::process::Stdio::piped())
 4965                    .spawn()?;
 4966            let stdin = child
 4967                .stdin
 4968                .as_mut()
 4969                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
 4970            let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
 4971            for chunk in text.chunks() {
 4972                stdin.write_all(chunk.as_bytes()).await?;
 4973            }
 4974            stdin.flush().await?;
 4975
 4976            let output = child.output().await?;
 4977            if !output.status.success() {
 4978                return Err(anyhow!(
 4979                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
 4980                    output.status.code(),
 4981                    String::from_utf8_lossy(&output.stdout),
 4982                    String::from_utf8_lossy(&output.stderr),
 4983                ));
 4984            }
 4985
 4986            let stdout = String::from_utf8(output.stdout)?;
 4987            Ok(Some(
 4988                buffer
 4989                    .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
 4990                    .await,
 4991            ))
 4992        } else {
 4993            Ok(None)
 4994        }
 4995    }
 4996
 4997    #[inline(never)]
 4998    fn definition_impl(
 4999        &self,
 5000        buffer: &Model<Buffer>,
 5001        position: PointUtf16,
 5002        cx: &mut ModelContext<Self>,
 5003    ) -> Task<Result<Vec<LocationLink>>> {
 5004        self.request_lsp(
 5005            buffer.clone(),
 5006            LanguageServerToQuery::Primary,
 5007            GetDefinition { position },
 5008            cx,
 5009        )
 5010    }
 5011    pub fn definition<T: ToPointUtf16>(
 5012        &self,
 5013        buffer: &Model<Buffer>,
 5014        position: T,
 5015        cx: &mut ModelContext<Self>,
 5016    ) -> Task<Result<Vec<LocationLink>>> {
 5017        let position = position.to_point_utf16(buffer.read(cx));
 5018        self.definition_impl(buffer, position, cx)
 5019    }
 5020
 5021    fn type_definition_impl(
 5022        &self,
 5023        buffer: &Model<Buffer>,
 5024        position: PointUtf16,
 5025        cx: &mut ModelContext<Self>,
 5026    ) -> Task<Result<Vec<LocationLink>>> {
 5027        self.request_lsp(
 5028            buffer.clone(),
 5029            LanguageServerToQuery::Primary,
 5030            GetTypeDefinition { position },
 5031            cx,
 5032        )
 5033    }
 5034
 5035    pub fn type_definition<T: ToPointUtf16>(
 5036        &self,
 5037        buffer: &Model<Buffer>,
 5038        position: T,
 5039        cx: &mut ModelContext<Self>,
 5040    ) -> Task<Result<Vec<LocationLink>>> {
 5041        let position = position.to_point_utf16(buffer.read(cx));
 5042        self.type_definition_impl(buffer, position, cx)
 5043    }
 5044
 5045    fn implementation_impl(
 5046        &self,
 5047        buffer: &Model<Buffer>,
 5048        position: PointUtf16,
 5049        cx: &mut ModelContext<Self>,
 5050    ) -> Task<Result<Vec<LocationLink>>> {
 5051        self.request_lsp(
 5052            buffer.clone(),
 5053            LanguageServerToQuery::Primary,
 5054            GetImplementation { position },
 5055            cx,
 5056        )
 5057    }
 5058
 5059    pub fn implementation<T: ToPointUtf16>(
 5060        &self,
 5061        buffer: &Model<Buffer>,
 5062        position: T,
 5063        cx: &mut ModelContext<Self>,
 5064    ) -> Task<Result<Vec<LocationLink>>> {
 5065        let position = position.to_point_utf16(buffer.read(cx));
 5066        self.implementation_impl(buffer, position, cx)
 5067    }
 5068
 5069    fn references_impl(
 5070        &self,
 5071        buffer: &Model<Buffer>,
 5072        position: PointUtf16,
 5073        cx: &mut ModelContext<Self>,
 5074    ) -> Task<Result<Vec<Location>>> {
 5075        self.request_lsp(
 5076            buffer.clone(),
 5077            LanguageServerToQuery::Primary,
 5078            GetReferences { position },
 5079            cx,
 5080        )
 5081    }
 5082    pub fn references<T: ToPointUtf16>(
 5083        &self,
 5084        buffer: &Model<Buffer>,
 5085        position: T,
 5086        cx: &mut ModelContext<Self>,
 5087    ) -> Task<Result<Vec<Location>>> {
 5088        let position = position.to_point_utf16(buffer.read(cx));
 5089        self.references_impl(buffer, position, cx)
 5090    }
 5091
 5092    fn document_highlights_impl(
 5093        &self,
 5094        buffer: &Model<Buffer>,
 5095        position: PointUtf16,
 5096        cx: &mut ModelContext<Self>,
 5097    ) -> Task<Result<Vec<DocumentHighlight>>> {
 5098        self.request_lsp(
 5099            buffer.clone(),
 5100            LanguageServerToQuery::Primary,
 5101            GetDocumentHighlights { position },
 5102            cx,
 5103        )
 5104    }
 5105
 5106    pub fn document_highlights<T: ToPointUtf16>(
 5107        &self,
 5108        buffer: &Model<Buffer>,
 5109        position: T,
 5110        cx: &mut ModelContext<Self>,
 5111    ) -> Task<Result<Vec<DocumentHighlight>>> {
 5112        let position = position.to_point_utf16(buffer.read(cx));
 5113        self.document_highlights_impl(buffer, position, cx)
 5114    }
 5115
 5116    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
 5117        let language_registry = self.languages.clone();
 5118
 5119        if self.is_local() {
 5120            let mut requests = Vec::new();
 5121            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
 5122                let Some(worktree_handle) = self.worktree_for_id(*worktree_id, cx) else {
 5123                    continue;
 5124                };
 5125                let worktree = worktree_handle.read(cx);
 5126                if !worktree.is_visible() {
 5127                    continue;
 5128                }
 5129                let Some(worktree) = worktree.as_local() else {
 5130                    continue;
 5131                };
 5132                let worktree_abs_path = worktree.abs_path().clone();
 5133
 5134                let (adapter, language, server) = match self.language_servers.get(server_id) {
 5135                    Some(LanguageServerState::Running {
 5136                        adapter,
 5137                        language,
 5138                        server,
 5139                        ..
 5140                    }) => (adapter.clone(), language.clone(), server),
 5141
 5142                    _ => continue,
 5143                };
 5144
 5145                requests.push(
 5146                    server
 5147                        .request::<lsp::request::WorkspaceSymbolRequest>(
 5148                            lsp::WorkspaceSymbolParams {
 5149                                query: query.to_string(),
 5150                                ..Default::default()
 5151                            },
 5152                        )
 5153                        .log_err()
 5154                        .map(move |response| {
 5155                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
 5156                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
 5157                                    flat_responses.into_iter().map(|lsp_symbol| {
 5158                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
 5159                                    }).collect::<Vec<_>>()
 5160                                }
 5161                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
 5162                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
 5163                                        let location = match lsp_symbol.location {
 5164                                            OneOf::Left(location) => location,
 5165                                            OneOf::Right(_) => {
 5166                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
 5167                                                return None
 5168                                            }
 5169                                        };
 5170                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
 5171                                    }).collect::<Vec<_>>()
 5172                                }
 5173                            }).unwrap_or_default();
 5174
 5175                            (
 5176                                adapter,
 5177                                language,
 5178                                worktree_handle.downgrade(),
 5179                                worktree_abs_path,
 5180                                lsp_symbols,
 5181                            )
 5182                        }),
 5183                );
 5184            }
 5185
 5186            cx.spawn(move |this, mut cx| async move {
 5187                let responses = futures::future::join_all(requests).await;
 5188                let this = match this.upgrade() {
 5189                    Some(this) => this,
 5190                    None => return Ok(Vec::new()),
 5191                };
 5192
 5193                let mut symbols = Vec::new();
 5194                for (adapter, adapter_language, source_worktree, worktree_abs_path, lsp_symbols) in
 5195                    responses
 5196                {
 5197                    let core_symbols = this.update(&mut cx, |this, cx| {
 5198                        lsp_symbols
 5199                            .into_iter()
 5200                            .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
 5201                                let abs_path = symbol_location.uri.to_file_path().ok()?;
 5202                                let source_worktree = source_worktree.upgrade()?;
 5203                                let source_worktree_id = source_worktree.read(cx).id();
 5204
 5205                                let path;
 5206                                let worktree;
 5207                                if let Some((tree, rel_path)) =
 5208                                    this.find_local_worktree(&abs_path, cx)
 5209                                {
 5210                                    worktree = tree;
 5211                                    path = rel_path;
 5212                                } else {
 5213                                    worktree = source_worktree.clone();
 5214                                    path = relativize_path(&worktree_abs_path, &abs_path);
 5215                                }
 5216
 5217                                let worktree_id = worktree.read(cx).id();
 5218                                let project_path = ProjectPath {
 5219                                    worktree_id,
 5220                                    path: path.into(),
 5221                                };
 5222                                let signature = this.symbol_signature(&project_path);
 5223                                Some(CoreSymbol {
 5224                                    language_server_name: adapter.name.clone(),
 5225                                    source_worktree_id,
 5226                                    path: project_path,
 5227                                    kind: symbol_kind,
 5228                                    name: symbol_name,
 5229                                    range: range_from_lsp(symbol_location.range),
 5230                                    signature,
 5231                                })
 5232                            })
 5233                            .collect()
 5234                    })?;
 5235
 5236                    populate_labels_for_symbols(
 5237                        core_symbols,
 5238                        &language_registry,
 5239                        Some(adapter_language),
 5240                        Some(adapter),
 5241                        &mut symbols,
 5242                    )
 5243                    .await;
 5244                }
 5245
 5246                Ok(symbols)
 5247            })
 5248        } else if let Some(project_id) = self.remote_id() {
 5249            let request = self.client.request(proto::GetProjectSymbols {
 5250                project_id,
 5251                query: query.to_string(),
 5252            });
 5253            cx.foreground_executor().spawn(async move {
 5254                let response = request.await?;
 5255                let mut symbols = Vec::new();
 5256                let core_symbols = response
 5257                    .symbols
 5258                    .into_iter()
 5259                    .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
 5260                    .collect::<Vec<_>>();
 5261                populate_labels_for_symbols(
 5262                    core_symbols,
 5263                    &language_registry,
 5264                    None,
 5265                    None,
 5266                    &mut symbols,
 5267                )
 5268                .await;
 5269                Ok(symbols)
 5270            })
 5271        } else {
 5272            Task::ready(Ok(Default::default()))
 5273        }
 5274    }
 5275
 5276    pub fn open_buffer_for_symbol(
 5277        &mut self,
 5278        symbol: &Symbol,
 5279        cx: &mut ModelContext<Self>,
 5280    ) -> Task<Result<Model<Buffer>>> {
 5281        if self.is_local() {
 5282            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
 5283                symbol.source_worktree_id,
 5284                symbol.language_server_name.clone(),
 5285            )) {
 5286                *id
 5287            } else {
 5288                return Task::ready(Err(anyhow!(
 5289                    "language server for worktree and language not found"
 5290                )));
 5291            };
 5292
 5293            let worktree_abs_path = if let Some(worktree_abs_path) = self
 5294                .worktree_for_id(symbol.path.worktree_id, cx)
 5295                .and_then(|worktree| worktree.read(cx).as_local())
 5296                .map(|local_worktree| local_worktree.abs_path())
 5297            {
 5298                worktree_abs_path
 5299            } else {
 5300                return Task::ready(Err(anyhow!("worktree not found for symbol")));
 5301            };
 5302
 5303            let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
 5304            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
 5305                uri
 5306            } else {
 5307                return Task::ready(Err(anyhow!("invalid symbol path")));
 5308            };
 5309
 5310            self.open_local_buffer_via_lsp(
 5311                symbol_uri,
 5312                language_server_id,
 5313                symbol.language_server_name.clone(),
 5314                cx,
 5315            )
 5316        } else if let Some(project_id) = self.remote_id() {
 5317            let request = self.client.request(proto::OpenBufferForSymbol {
 5318                project_id,
 5319                symbol: Some(serialize_symbol(symbol)),
 5320            });
 5321            cx.spawn(move |this, mut cx| async move {
 5322                let response = request.await?;
 5323                let buffer_id = BufferId::new(response.buffer_id)?;
 5324                this.update(&mut cx, |this, cx| {
 5325                    this.wait_for_remote_buffer(buffer_id, cx)
 5326                })?
 5327                .await
 5328            })
 5329        } else {
 5330            Task::ready(Err(anyhow!("project does not have a remote id")))
 5331        }
 5332    }
 5333
 5334    fn hover_impl(
 5335        &self,
 5336        buffer: &Model<Buffer>,
 5337        position: PointUtf16,
 5338        cx: &mut ModelContext<Self>,
 5339    ) -> Task<Vec<Hover>> {
 5340        if self.is_local() {
 5341            let all_actions_task = self.request_multiple_lsp_locally(
 5342                &buffer,
 5343                Some(position),
 5344                |server_capabilities| match server_capabilities.hover_provider {
 5345                    Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 5346                    Some(lsp::HoverProviderCapability::Options(_)) => true,
 5347                    None => false,
 5348                },
 5349                GetHover { position },
 5350                cx,
 5351            );
 5352            cx.spawn(|_, _| async move {
 5353                all_actions_task
 5354                    .await
 5355                    .into_iter()
 5356                    .filter_map(|hover| remove_empty_hover_blocks(hover?))
 5357                    .collect()
 5358            })
 5359        } else if let Some(project_id) = self.remote_id() {
 5360            let request_task = self.client().request(proto::MultiLspQuery {
 5361                buffer_id: buffer.read(cx).remote_id().into(),
 5362                version: serialize_version(&buffer.read(cx).version()),
 5363                project_id,
 5364                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5365                    proto::AllLanguageServers {},
 5366                )),
 5367                request: Some(proto::multi_lsp_query::Request::GetHover(
 5368                    GetHover { position }.to_proto(project_id, buffer.read(cx)),
 5369                )),
 5370            });
 5371            let buffer = buffer.clone();
 5372            cx.spawn(|weak_project, cx| async move {
 5373                let Some(project) = weak_project.upgrade() else {
 5374                    return Vec::new();
 5375                };
 5376                join_all(
 5377                    request_task
 5378                        .await
 5379                        .log_err()
 5380                        .map(|response| response.responses)
 5381                        .unwrap_or_default()
 5382                        .into_iter()
 5383                        .filter_map(|lsp_response| match lsp_response.response? {
 5384                            proto::lsp_response::Response::GetHoverResponse(response) => {
 5385                                Some(response)
 5386                            }
 5387                            unexpected => {
 5388                                debug_panic!("Unexpected response: {unexpected:?}");
 5389                                None
 5390                            }
 5391                        })
 5392                        .map(|hover_response| {
 5393                            let response = GetHover { position }.response_from_proto(
 5394                                hover_response,
 5395                                project.clone(),
 5396                                buffer.clone(),
 5397                                cx.clone(),
 5398                            );
 5399                            async move {
 5400                                response
 5401                                    .await
 5402                                    .log_err()
 5403                                    .flatten()
 5404                                    .and_then(remove_empty_hover_blocks)
 5405                            }
 5406                        }),
 5407                )
 5408                .await
 5409                .into_iter()
 5410                .flatten()
 5411                .collect()
 5412            })
 5413        } else {
 5414            log::error!("cannot show hovers: project does not have a remote id");
 5415            Task::ready(Vec::new())
 5416        }
 5417    }
 5418
 5419    pub fn hover<T: ToPointUtf16>(
 5420        &self,
 5421        buffer: &Model<Buffer>,
 5422        position: T,
 5423        cx: &mut ModelContext<Self>,
 5424    ) -> Task<Vec<Hover>> {
 5425        let position = position.to_point_utf16(buffer.read(cx));
 5426        self.hover_impl(buffer, position, cx)
 5427    }
 5428
 5429    #[inline(never)]
 5430    fn completions_impl(
 5431        &self,
 5432        buffer: &Model<Buffer>,
 5433        position: PointUtf16,
 5434        cx: &mut ModelContext<Self>,
 5435    ) -> Task<Result<Vec<Completion>>> {
 5436        let language_registry = self.languages.clone();
 5437
 5438        if self.is_local() {
 5439            let snapshot = buffer.read(cx).snapshot();
 5440            let offset = position.to_offset(&snapshot);
 5441            let scope = snapshot.language_scope_at(offset);
 5442            let language = snapshot.language().cloned();
 5443
 5444            let server_ids: Vec<_> = self
 5445                .language_servers_for_buffer(buffer.read(cx), cx)
 5446                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
 5447                .filter(|(adapter, _)| {
 5448                    scope
 5449                        .as_ref()
 5450                        .map(|scope| scope.language_allowed(&adapter.name))
 5451                        .unwrap_or(true)
 5452                })
 5453                .map(|(_, server)| server.server_id())
 5454                .collect();
 5455
 5456            let buffer = buffer.clone();
 5457            cx.spawn(move |this, mut cx| async move {
 5458                let mut tasks = Vec::with_capacity(server_ids.len());
 5459                this.update(&mut cx, |this, cx| {
 5460                    for server_id in server_ids {
 5461                        let lsp_adapter = this.language_server_adapter_for_id(server_id);
 5462                        tasks.push((
 5463                            lsp_adapter,
 5464                            this.request_lsp(
 5465                                buffer.clone(),
 5466                                LanguageServerToQuery::Other(server_id),
 5467                                GetCompletions { position },
 5468                                cx,
 5469                            ),
 5470                        ));
 5471                    }
 5472                })?;
 5473
 5474                let mut completions = Vec::new();
 5475                for (lsp_adapter, task) in tasks {
 5476                    if let Ok(new_completions) = task.await {
 5477                        populate_labels_for_completions(
 5478                            new_completions,
 5479                            &language_registry,
 5480                            language.clone(),
 5481                            lsp_adapter,
 5482                            &mut completions,
 5483                        )
 5484                        .await;
 5485                    }
 5486                }
 5487
 5488                Ok(completions)
 5489            })
 5490        } else if let Some(project_id) = self.remote_id() {
 5491            let task = self.send_lsp_proto_request(
 5492                buffer.clone(),
 5493                project_id,
 5494                GetCompletions { position },
 5495                cx,
 5496            );
 5497            let language = buffer.read(cx).language().cloned();
 5498
 5499            // In the future, we should provide project guests with the names of LSP adapters,
 5500            // so that they can use the correct LSP adapter when computing labels. For now,
 5501            // guests just use the first LSP adapter associated with the buffer's language.
 5502            let lsp_adapter = language
 5503                .as_ref()
 5504                .and_then(|language| language_registry.lsp_adapters(language).first().cloned());
 5505
 5506            cx.foreground_executor().spawn(async move {
 5507                let completions = task.await?;
 5508                let mut result = Vec::new();
 5509                populate_labels_for_completions(
 5510                    completions,
 5511                    &language_registry,
 5512                    language,
 5513                    lsp_adapter,
 5514                    &mut result,
 5515                )
 5516                .await;
 5517                Ok(result)
 5518            })
 5519        } else {
 5520            Task::ready(Ok(Default::default()))
 5521        }
 5522    }
 5523
 5524    pub fn completions<T: ToOffset + ToPointUtf16>(
 5525        &self,
 5526        buffer: &Model<Buffer>,
 5527        position: T,
 5528        cx: &mut ModelContext<Self>,
 5529    ) -> Task<Result<Vec<Completion>>> {
 5530        let position = position.to_point_utf16(buffer.read(cx));
 5531        self.completions_impl(buffer, position, cx)
 5532    }
 5533
 5534    pub fn resolve_completions(
 5535        &self,
 5536        completion_indices: Vec<usize>,
 5537        completions: Arc<RwLock<Box<[Completion]>>>,
 5538        cx: &mut ModelContext<Self>,
 5539    ) -> Task<Result<bool>> {
 5540        let client = self.client();
 5541        let language_registry = self.languages().clone();
 5542
 5543        let is_remote = self.is_remote();
 5544        let project_id = self.remote_id();
 5545
 5546        cx.spawn(move |this, mut cx| async move {
 5547            let mut did_resolve = false;
 5548            if is_remote {
 5549                let project_id =
 5550                    project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
 5551
 5552                for completion_index in completion_indices {
 5553                    let (server_id, completion) = {
 5554                        let completions_guard = completions.read();
 5555                        let completion = &completions_guard[completion_index];
 5556                        if completion.documentation.is_some() {
 5557                            continue;
 5558                        }
 5559
 5560                        did_resolve = true;
 5561                        let server_id = completion.server_id;
 5562                        let completion = completion.lsp_completion.clone();
 5563
 5564                        (server_id, completion)
 5565                    };
 5566
 5567                    Self::resolve_completion_documentation_remote(
 5568                        project_id,
 5569                        server_id,
 5570                        completions.clone(),
 5571                        completion_index,
 5572                        completion,
 5573                        client.clone(),
 5574                        language_registry.clone(),
 5575                    )
 5576                    .await;
 5577                }
 5578            } else {
 5579                for completion_index in completion_indices {
 5580                    let (server_id, completion) = {
 5581                        let completions_guard = completions.read();
 5582                        let completion = &completions_guard[completion_index];
 5583                        if completion.documentation.is_some() {
 5584                            continue;
 5585                        }
 5586
 5587                        let server_id = completion.server_id;
 5588                        let completion = completion.lsp_completion.clone();
 5589
 5590                        (server_id, completion)
 5591                    };
 5592
 5593                    let server = this
 5594                        .read_with(&mut cx, |project, _| {
 5595                            project.language_server_for_id(server_id)
 5596                        })
 5597                        .ok()
 5598                        .flatten();
 5599                    let Some(server) = server else {
 5600                        continue;
 5601                    };
 5602
 5603                    did_resolve = true;
 5604                    Self::resolve_completion_documentation_local(
 5605                        server,
 5606                        completions.clone(),
 5607                        completion_index,
 5608                        completion,
 5609                        language_registry.clone(),
 5610                    )
 5611                    .await;
 5612                }
 5613            }
 5614
 5615            Ok(did_resolve)
 5616        })
 5617    }
 5618
 5619    async fn resolve_completion_documentation_local(
 5620        server: Arc<lsp::LanguageServer>,
 5621        completions: Arc<RwLock<Box<[Completion]>>>,
 5622        completion_index: usize,
 5623        completion: lsp::CompletionItem,
 5624        language_registry: Arc<LanguageRegistry>,
 5625    ) {
 5626        let can_resolve = server
 5627            .capabilities()
 5628            .completion_provider
 5629            .as_ref()
 5630            .and_then(|options| options.resolve_provider)
 5631            .unwrap_or(false);
 5632        if !can_resolve {
 5633            return;
 5634        }
 5635
 5636        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
 5637        let Some(completion_item) = request.await.log_err() else {
 5638            return;
 5639        };
 5640
 5641        if let Some(lsp_documentation) = completion_item.documentation {
 5642            let documentation = language::prepare_completion_documentation(
 5643                &lsp_documentation,
 5644                &language_registry,
 5645                None, // TODO: Try to reasonably work out which language the completion is for
 5646            )
 5647            .await;
 5648
 5649            let mut completions = completions.write();
 5650            let completion = &mut completions[completion_index];
 5651            completion.documentation = Some(documentation);
 5652        } else {
 5653            let mut completions = completions.write();
 5654            let completion = &mut completions[completion_index];
 5655            completion.documentation = Some(Documentation::Undocumented);
 5656        }
 5657    }
 5658
 5659    async fn resolve_completion_documentation_remote(
 5660        project_id: u64,
 5661        server_id: LanguageServerId,
 5662        completions: Arc<RwLock<Box<[Completion]>>>,
 5663        completion_index: usize,
 5664        completion: lsp::CompletionItem,
 5665        client: Arc<Client>,
 5666        language_registry: Arc<LanguageRegistry>,
 5667    ) {
 5668        let request = proto::ResolveCompletionDocumentation {
 5669            project_id,
 5670            language_server_id: server_id.0 as u64,
 5671            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
 5672        };
 5673
 5674        let Some(response) = client
 5675            .request(request)
 5676            .await
 5677            .context("completion documentation resolve proto request")
 5678            .log_err()
 5679        else {
 5680            return;
 5681        };
 5682
 5683        if response.text.is_empty() {
 5684            let mut completions = completions.write();
 5685            let completion = &mut completions[completion_index];
 5686            completion.documentation = Some(Documentation::Undocumented);
 5687        }
 5688
 5689        let documentation = if response.is_markdown {
 5690            Documentation::MultiLineMarkdown(
 5691                markdown::parse_markdown(&response.text, &language_registry, None).await,
 5692            )
 5693        } else if response.text.lines().count() <= 1 {
 5694            Documentation::SingleLine(response.text)
 5695        } else {
 5696            Documentation::MultiLinePlainText(response.text)
 5697        };
 5698
 5699        let mut completions = completions.write();
 5700        let completion = &mut completions[completion_index];
 5701        completion.documentation = Some(documentation);
 5702    }
 5703
 5704    pub fn apply_additional_edits_for_completion(
 5705        &self,
 5706        buffer_handle: Model<Buffer>,
 5707        completion: Completion,
 5708        push_to_history: bool,
 5709        cx: &mut ModelContext<Self>,
 5710    ) -> Task<Result<Option<Transaction>>> {
 5711        let buffer = buffer_handle.read(cx);
 5712        let buffer_id = buffer.remote_id();
 5713
 5714        if self.is_local() {
 5715            let server_id = completion.server_id;
 5716            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
 5717                Some((_, server)) => server.clone(),
 5718                _ => return Task::ready(Ok(Default::default())),
 5719            };
 5720
 5721            cx.spawn(move |this, mut cx| async move {
 5722                let can_resolve = lang_server
 5723                    .capabilities()
 5724                    .completion_provider
 5725                    .as_ref()
 5726                    .and_then(|options| options.resolve_provider)
 5727                    .unwrap_or(false);
 5728                let additional_text_edits = if can_resolve {
 5729                    lang_server
 5730                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
 5731                        .await?
 5732                        .additional_text_edits
 5733                } else {
 5734                    completion.lsp_completion.additional_text_edits
 5735                };
 5736                if let Some(edits) = additional_text_edits {
 5737                    let edits = this
 5738                        .update(&mut cx, |this, cx| {
 5739                            this.edits_from_lsp(
 5740                                &buffer_handle,
 5741                                edits,
 5742                                lang_server.server_id(),
 5743                                None,
 5744                                cx,
 5745                            )
 5746                        })?
 5747                        .await?;
 5748
 5749                    buffer_handle.update(&mut cx, |buffer, cx| {
 5750                        buffer.finalize_last_transaction();
 5751                        buffer.start_transaction();
 5752
 5753                        for (range, text) in edits {
 5754                            let primary = &completion.old_range;
 5755                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
 5756                                && primary.end.cmp(&range.start, buffer).is_ge();
 5757                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
 5758                                && range.end.cmp(&primary.end, buffer).is_ge();
 5759
 5760                            //Skip additional edits which overlap with the primary completion edit
 5761                            //https://github.com/zed-industries/zed/pull/1871
 5762                            if !start_within && !end_within {
 5763                                buffer.edit([(range, text)], None, cx);
 5764                            }
 5765                        }
 5766
 5767                        let transaction = if buffer.end_transaction(cx).is_some() {
 5768                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 5769                            if !push_to_history {
 5770                                buffer.forget_transaction(transaction.id);
 5771                            }
 5772                            Some(transaction)
 5773                        } else {
 5774                            None
 5775                        };
 5776                        Ok(transaction)
 5777                    })?
 5778                } else {
 5779                    Ok(None)
 5780                }
 5781            })
 5782        } else if let Some(project_id) = self.remote_id() {
 5783            let client = self.client.clone();
 5784            cx.spawn(move |_, mut cx| async move {
 5785                let response = client
 5786                    .request(proto::ApplyCompletionAdditionalEdits {
 5787                        project_id,
 5788                        buffer_id: buffer_id.into(),
 5789                        completion: Some(Self::serialize_completion(&CoreCompletion {
 5790                            old_range: completion.old_range,
 5791                            new_text: completion.new_text,
 5792                            server_id: completion.server_id,
 5793                            lsp_completion: completion.lsp_completion,
 5794                        })),
 5795                    })
 5796                    .await?;
 5797
 5798                if let Some(transaction) = response.transaction {
 5799                    let transaction = language::proto::deserialize_transaction(transaction)?;
 5800                    buffer_handle
 5801                        .update(&mut cx, |buffer, _| {
 5802                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 5803                        })?
 5804                        .await?;
 5805                    if push_to_history {
 5806                        buffer_handle.update(&mut cx, |buffer, _| {
 5807                            buffer.push_transaction(transaction.clone(), Instant::now());
 5808                        })?;
 5809                    }
 5810                    Ok(Some(transaction))
 5811                } else {
 5812                    Ok(None)
 5813                }
 5814            })
 5815        } else {
 5816            Task::ready(Err(anyhow!("project does not have a remote id")))
 5817        }
 5818    }
 5819
 5820    fn code_actions_impl(
 5821        &mut self,
 5822        buffer_handle: &Model<Buffer>,
 5823        range: Range<Anchor>,
 5824        cx: &mut ModelContext<Self>,
 5825    ) -> Task<Vec<CodeAction>> {
 5826        if self.is_local() {
 5827            let all_actions_task = self.request_multiple_lsp_locally(
 5828                &buffer_handle,
 5829                Some(range.start),
 5830                GetCodeActions::supports_code_actions,
 5831                GetCodeActions {
 5832                    range: range.clone(),
 5833                    kinds: None,
 5834                },
 5835                cx,
 5836            );
 5837            cx.spawn(|_, _| async move { all_actions_task.await.into_iter().flatten().collect() })
 5838        } else if let Some(project_id) = self.remote_id() {
 5839            let request_task = self.client().request(proto::MultiLspQuery {
 5840                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5841                version: serialize_version(&buffer_handle.read(cx).version()),
 5842                project_id,
 5843                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5844                    proto::AllLanguageServers {},
 5845                )),
 5846                request: Some(proto::multi_lsp_query::Request::GetCodeActions(
 5847                    GetCodeActions {
 5848                        range: range.clone(),
 5849                        kinds: None,
 5850                    }
 5851                    .to_proto(project_id, buffer_handle.read(cx)),
 5852                )),
 5853            });
 5854            let buffer = buffer_handle.clone();
 5855            cx.spawn(|weak_project, cx| async move {
 5856                let Some(project) = weak_project.upgrade() else {
 5857                    return Vec::new();
 5858                };
 5859                join_all(
 5860                    request_task
 5861                        .await
 5862                        .log_err()
 5863                        .map(|response| response.responses)
 5864                        .unwrap_or_default()
 5865                        .into_iter()
 5866                        .filter_map(|lsp_response| match lsp_response.response? {
 5867                            proto::lsp_response::Response::GetCodeActionsResponse(response) => {
 5868                                Some(response)
 5869                            }
 5870                            unexpected => {
 5871                                debug_panic!("Unexpected response: {unexpected:?}");
 5872                                None
 5873                            }
 5874                        })
 5875                        .map(|code_actions_response| {
 5876                            let response = GetCodeActions {
 5877                                range: range.clone(),
 5878                                kinds: None,
 5879                            }
 5880                            .response_from_proto(
 5881                                code_actions_response,
 5882                                project.clone(),
 5883                                buffer.clone(),
 5884                                cx.clone(),
 5885                            );
 5886                            async move { response.await.log_err().unwrap_or_default() }
 5887                        }),
 5888                )
 5889                .await
 5890                .into_iter()
 5891                .flatten()
 5892                .collect()
 5893            })
 5894        } else {
 5895            log::error!("cannot fetch actions: project does not have a remote id");
 5896            Task::ready(Vec::new())
 5897        }
 5898    }
 5899
 5900    pub fn code_actions<T: Clone + ToOffset>(
 5901        &mut self,
 5902        buffer_handle: &Model<Buffer>,
 5903        range: Range<T>,
 5904        cx: &mut ModelContext<Self>,
 5905    ) -> Task<Vec<CodeAction>> {
 5906        let buffer = buffer_handle.read(cx);
 5907        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 5908        self.code_actions_impl(buffer_handle, range, cx)
 5909    }
 5910
 5911    pub fn apply_code_action(
 5912        &self,
 5913        buffer_handle: Model<Buffer>,
 5914        mut action: CodeAction,
 5915        push_to_history: bool,
 5916        cx: &mut ModelContext<Self>,
 5917    ) -> Task<Result<ProjectTransaction>> {
 5918        if self.is_local() {
 5919            let buffer = buffer_handle.read(cx);
 5920            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
 5921                self.language_server_for_buffer(buffer, action.server_id, cx)
 5922            {
 5923                (adapter.clone(), server.clone())
 5924            } else {
 5925                return Task::ready(Ok(Default::default()));
 5926            };
 5927            cx.spawn(move |this, mut cx| async move {
 5928                Self::try_resolve_code_action(&lang_server, &mut action)
 5929                    .await
 5930                    .context("resolving a code action")?;
 5931                if let Some(edit) = action.lsp_action.edit {
 5932                    if edit.changes.is_some() || edit.document_changes.is_some() {
 5933                        return Self::deserialize_workspace_edit(
 5934                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
 5935                            edit,
 5936                            push_to_history,
 5937                            lsp_adapter.clone(),
 5938                            lang_server.clone(),
 5939                            &mut cx,
 5940                        )
 5941                        .await;
 5942                    }
 5943                }
 5944
 5945                if let Some(command) = action.lsp_action.command {
 5946                    this.update(&mut cx, |this, _| {
 5947                        this.last_workspace_edits_by_language_server
 5948                            .remove(&lang_server.server_id());
 5949                    })?;
 5950
 5951                    let result = lang_server
 5952                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 5953                            command: command.command,
 5954                            arguments: command.arguments.unwrap_or_default(),
 5955                            ..Default::default()
 5956                        })
 5957                        .await;
 5958
 5959                    if let Err(err) = result {
 5960                        // TODO: LSP ERROR
 5961                        return Err(err);
 5962                    }
 5963
 5964                    return this.update(&mut cx, |this, _| {
 5965                        this.last_workspace_edits_by_language_server
 5966                            .remove(&lang_server.server_id())
 5967                            .unwrap_or_default()
 5968                    });
 5969                }
 5970
 5971                Ok(ProjectTransaction::default())
 5972            })
 5973        } else if let Some(project_id) = self.remote_id() {
 5974            let client = self.client.clone();
 5975            let request = proto::ApplyCodeAction {
 5976                project_id,
 5977                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5978                action: Some(Self::serialize_code_action(&action)),
 5979            };
 5980            cx.spawn(move |this, mut cx| async move {
 5981                let response = client
 5982                    .request(request)
 5983                    .await?
 5984                    .transaction
 5985                    .ok_or_else(|| anyhow!("missing transaction"))?;
 5986                this.update(&mut cx, |this, cx| {
 5987                    this.deserialize_project_transaction(response, push_to_history, cx)
 5988                })?
 5989                .await
 5990            })
 5991        } else {
 5992            Task::ready(Err(anyhow!("project does not have a remote id")))
 5993        }
 5994    }
 5995
 5996    fn apply_on_type_formatting(
 5997        &self,
 5998        buffer: Model<Buffer>,
 5999        position: Anchor,
 6000        trigger: String,
 6001        cx: &mut ModelContext<Self>,
 6002    ) -> Task<Result<Option<Transaction>>> {
 6003        if self.is_local() {
 6004            cx.spawn(move |this, mut cx| async move {
 6005                // Do not allow multiple concurrent formatting requests for the
 6006                // same buffer.
 6007                this.update(&mut cx, |this, cx| {
 6008                    this.buffers_being_formatted
 6009                        .insert(buffer.read(cx).remote_id())
 6010                })?;
 6011
 6012                let _cleanup = defer({
 6013                    let this = this.clone();
 6014                    let mut cx = cx.clone();
 6015                    let closure_buffer = buffer.clone();
 6016                    move || {
 6017                        this.update(&mut cx, |this, cx| {
 6018                            this.buffers_being_formatted
 6019                                .remove(&closure_buffer.read(cx).remote_id());
 6020                        })
 6021                        .ok();
 6022                    }
 6023                });
 6024
 6025                buffer
 6026                    .update(&mut cx, |buffer, _| {
 6027                        buffer.wait_for_edits(Some(position.timestamp))
 6028                    })?
 6029                    .await?;
 6030                this.update(&mut cx, |this, cx| {
 6031                    let position = position.to_point_utf16(buffer.read(cx));
 6032                    this.on_type_format(buffer, position, trigger, false, cx)
 6033                })?
 6034                .await
 6035            })
 6036        } else if let Some(project_id) = self.remote_id() {
 6037            let client = self.client.clone();
 6038            let request = proto::OnTypeFormatting {
 6039                project_id,
 6040                buffer_id: buffer.read(cx).remote_id().into(),
 6041                position: Some(serialize_anchor(&position)),
 6042                trigger,
 6043                version: serialize_version(&buffer.read(cx).version()),
 6044            };
 6045            cx.spawn(move |_, _| async move {
 6046                client
 6047                    .request(request)
 6048                    .await?
 6049                    .transaction
 6050                    .map(language::proto::deserialize_transaction)
 6051                    .transpose()
 6052            })
 6053        } else {
 6054            Task::ready(Err(anyhow!("project does not have a remote id")))
 6055        }
 6056    }
 6057
 6058    async fn deserialize_edits(
 6059        this: Model<Self>,
 6060        buffer_to_edit: Model<Buffer>,
 6061        edits: Vec<lsp::TextEdit>,
 6062        push_to_history: bool,
 6063        _: Arc<CachedLspAdapter>,
 6064        language_server: Arc<LanguageServer>,
 6065        cx: &mut AsyncAppContext,
 6066    ) -> Result<Option<Transaction>> {
 6067        let edits = this
 6068            .update(cx, |this, cx| {
 6069                this.edits_from_lsp(
 6070                    &buffer_to_edit,
 6071                    edits,
 6072                    language_server.server_id(),
 6073                    None,
 6074                    cx,
 6075                )
 6076            })?
 6077            .await?;
 6078
 6079        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 6080            buffer.finalize_last_transaction();
 6081            buffer.start_transaction();
 6082            for (range, text) in edits {
 6083                buffer.edit([(range, text)], None, cx);
 6084            }
 6085
 6086            if buffer.end_transaction(cx).is_some() {
 6087                let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6088                if !push_to_history {
 6089                    buffer.forget_transaction(transaction.id);
 6090                }
 6091                Some(transaction)
 6092            } else {
 6093                None
 6094            }
 6095        })?;
 6096
 6097        Ok(transaction)
 6098    }
 6099
 6100    async fn deserialize_workspace_edit(
 6101        this: Model<Self>,
 6102        edit: lsp::WorkspaceEdit,
 6103        push_to_history: bool,
 6104        lsp_adapter: Arc<CachedLspAdapter>,
 6105        language_server: Arc<LanguageServer>,
 6106        cx: &mut AsyncAppContext,
 6107    ) -> Result<ProjectTransaction> {
 6108        let fs = this.update(cx, |this, _| this.fs.clone())?;
 6109        let mut operations = Vec::new();
 6110        if let Some(document_changes) = edit.document_changes {
 6111            match document_changes {
 6112                lsp::DocumentChanges::Edits(edits) => {
 6113                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
 6114                }
 6115                lsp::DocumentChanges::Operations(ops) => operations = ops,
 6116            }
 6117        } else if let Some(changes) = edit.changes {
 6118            operations.extend(changes.into_iter().map(|(uri, edits)| {
 6119                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
 6120                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
 6121                        uri,
 6122                        version: None,
 6123                    },
 6124                    edits: edits.into_iter().map(OneOf::Left).collect(),
 6125                })
 6126            }));
 6127        }
 6128
 6129        let mut project_transaction = ProjectTransaction::default();
 6130        for operation in operations {
 6131            match operation {
 6132                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
 6133                    let abs_path = op
 6134                        .uri
 6135                        .to_file_path()
 6136                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6137
 6138                    if let Some(parent_path) = abs_path.parent() {
 6139                        fs.create_dir(parent_path).await?;
 6140                    }
 6141                    if abs_path.ends_with("/") {
 6142                        fs.create_dir(&abs_path).await?;
 6143                    } else {
 6144                        fs.create_file(
 6145                            &abs_path,
 6146                            op.options
 6147                                .map(|options| fs::CreateOptions {
 6148                                    overwrite: options.overwrite.unwrap_or(false),
 6149                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6150                                })
 6151                                .unwrap_or_default(),
 6152                        )
 6153                        .await?;
 6154                    }
 6155                }
 6156
 6157                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
 6158                    let source_abs_path = op
 6159                        .old_uri
 6160                        .to_file_path()
 6161                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6162                    let target_abs_path = op
 6163                        .new_uri
 6164                        .to_file_path()
 6165                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6166                    fs.rename(
 6167                        &source_abs_path,
 6168                        &target_abs_path,
 6169                        op.options
 6170                            .map(|options| fs::RenameOptions {
 6171                                overwrite: options.overwrite.unwrap_or(false),
 6172                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6173                            })
 6174                            .unwrap_or_default(),
 6175                    )
 6176                    .await?;
 6177                }
 6178
 6179                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
 6180                    let abs_path = op
 6181                        .uri
 6182                        .to_file_path()
 6183                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6184                    let options = op
 6185                        .options
 6186                        .map(|options| fs::RemoveOptions {
 6187                            recursive: options.recursive.unwrap_or(false),
 6188                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
 6189                        })
 6190                        .unwrap_or_default();
 6191                    if abs_path.ends_with("/") {
 6192                        fs.remove_dir(&abs_path, options).await?;
 6193                    } else {
 6194                        fs.remove_file(&abs_path, options).await?;
 6195                    }
 6196                }
 6197
 6198                lsp::DocumentChangeOperation::Edit(op) => {
 6199                    let buffer_to_edit = this
 6200                        .update(cx, |this, cx| {
 6201                            this.open_local_buffer_via_lsp(
 6202                                op.text_document.uri,
 6203                                language_server.server_id(),
 6204                                lsp_adapter.name.clone(),
 6205                                cx,
 6206                            )
 6207                        })?
 6208                        .await?;
 6209
 6210                    let edits = this
 6211                        .update(cx, |this, cx| {
 6212                            let edits = op.edits.into_iter().map(|edit| match edit {
 6213                                OneOf::Left(edit) => edit,
 6214                                OneOf::Right(edit) => edit.text_edit,
 6215                            });
 6216                            this.edits_from_lsp(
 6217                                &buffer_to_edit,
 6218                                edits,
 6219                                language_server.server_id(),
 6220                                op.text_document.version,
 6221                                cx,
 6222                            )
 6223                        })?
 6224                        .await?;
 6225
 6226                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 6227                        buffer.finalize_last_transaction();
 6228                        buffer.start_transaction();
 6229                        for (range, text) in edits {
 6230                            buffer.edit([(range, text)], None, cx);
 6231                        }
 6232                        let transaction = if buffer.end_transaction(cx).is_some() {
 6233                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6234                            if !push_to_history {
 6235                                buffer.forget_transaction(transaction.id);
 6236                            }
 6237                            Some(transaction)
 6238                        } else {
 6239                            None
 6240                        };
 6241
 6242                        transaction
 6243                    })?;
 6244                    if let Some(transaction) = transaction {
 6245                        project_transaction.0.insert(buffer_to_edit, transaction);
 6246                    }
 6247                }
 6248            }
 6249        }
 6250
 6251        Ok(project_transaction)
 6252    }
 6253
 6254    fn prepare_rename_impl(
 6255        &mut self,
 6256        buffer: Model<Buffer>,
 6257        position: PointUtf16,
 6258        cx: &mut ModelContext<Self>,
 6259    ) -> Task<Result<Option<Range<Anchor>>>> {
 6260        self.request_lsp(
 6261            buffer,
 6262            LanguageServerToQuery::Primary,
 6263            PrepareRename { position },
 6264            cx,
 6265        )
 6266    }
 6267    pub fn prepare_rename<T: ToPointUtf16>(
 6268        &mut self,
 6269        buffer: Model<Buffer>,
 6270        position: T,
 6271        cx: &mut ModelContext<Self>,
 6272    ) -> Task<Result<Option<Range<Anchor>>>> {
 6273        let position = position.to_point_utf16(buffer.read(cx));
 6274        self.prepare_rename_impl(buffer, position, cx)
 6275    }
 6276
 6277    fn perform_rename_impl(
 6278        &mut self,
 6279        buffer: Model<Buffer>,
 6280        position: PointUtf16,
 6281        new_name: String,
 6282        push_to_history: bool,
 6283        cx: &mut ModelContext<Self>,
 6284    ) -> Task<Result<ProjectTransaction>> {
 6285        let position = position.to_point_utf16(buffer.read(cx));
 6286        self.request_lsp(
 6287            buffer,
 6288            LanguageServerToQuery::Primary,
 6289            PerformRename {
 6290                position,
 6291                new_name,
 6292                push_to_history,
 6293            },
 6294            cx,
 6295        )
 6296    }
 6297    pub fn perform_rename<T: ToPointUtf16>(
 6298        &mut self,
 6299        buffer: Model<Buffer>,
 6300        position: T,
 6301        new_name: String,
 6302        push_to_history: bool,
 6303        cx: &mut ModelContext<Self>,
 6304    ) -> Task<Result<ProjectTransaction>> {
 6305        let position = position.to_point_utf16(buffer.read(cx));
 6306        self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
 6307    }
 6308
 6309    pub fn on_type_format_impl(
 6310        &mut self,
 6311        buffer: Model<Buffer>,
 6312        position: PointUtf16,
 6313        trigger: String,
 6314        push_to_history: bool,
 6315        cx: &mut ModelContext<Self>,
 6316    ) -> Task<Result<Option<Transaction>>> {
 6317        let tab_size = buffer.update(cx, |buffer, cx| {
 6318            language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
 6319        });
 6320        self.request_lsp(
 6321            buffer.clone(),
 6322            LanguageServerToQuery::Primary,
 6323            OnTypeFormatting {
 6324                position,
 6325                trigger,
 6326                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
 6327                push_to_history,
 6328            },
 6329            cx,
 6330        )
 6331    }
 6332
 6333    pub fn on_type_format<T: ToPointUtf16>(
 6334        &mut self,
 6335        buffer: Model<Buffer>,
 6336        position: T,
 6337        trigger: String,
 6338        push_to_history: bool,
 6339        cx: &mut ModelContext<Self>,
 6340    ) -> Task<Result<Option<Transaction>>> {
 6341        let position = position.to_point_utf16(buffer.read(cx));
 6342        self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
 6343    }
 6344
 6345    pub fn inlay_hints<T: ToOffset>(
 6346        &mut self,
 6347        buffer_handle: Model<Buffer>,
 6348        range: Range<T>,
 6349        cx: &mut ModelContext<Self>,
 6350    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 6351        let buffer = buffer_handle.read(cx);
 6352        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 6353        self.inlay_hints_impl(buffer_handle, range, cx)
 6354    }
 6355    fn inlay_hints_impl(
 6356        &mut self,
 6357        buffer_handle: Model<Buffer>,
 6358        range: Range<Anchor>,
 6359        cx: &mut ModelContext<Self>,
 6360    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 6361        let buffer = buffer_handle.read(cx);
 6362        let range_start = range.start;
 6363        let range_end = range.end;
 6364        let buffer_id = buffer.remote_id().into();
 6365        let lsp_request = InlayHints { range };
 6366
 6367        if self.is_local() {
 6368            let lsp_request_task = self.request_lsp(
 6369                buffer_handle.clone(),
 6370                LanguageServerToQuery::Primary,
 6371                lsp_request,
 6372                cx,
 6373            );
 6374            cx.spawn(move |_, mut cx| async move {
 6375                buffer_handle
 6376                    .update(&mut cx, |buffer, _| {
 6377                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
 6378                    })?
 6379                    .await
 6380                    .context("waiting for inlay hint request range edits")?;
 6381                lsp_request_task.await.context("inlay hints LSP request")
 6382            })
 6383        } else if let Some(project_id) = self.remote_id() {
 6384            let client = self.client.clone();
 6385            let request = proto::InlayHints {
 6386                project_id,
 6387                buffer_id,
 6388                start: Some(serialize_anchor(&range_start)),
 6389                end: Some(serialize_anchor(&range_end)),
 6390                version: serialize_version(&buffer_handle.read(cx).version()),
 6391            };
 6392            cx.spawn(move |project, cx| async move {
 6393                let response = client
 6394                    .request(request)
 6395                    .await
 6396                    .context("inlay hints proto request")?;
 6397                LspCommand::response_from_proto(
 6398                    lsp_request,
 6399                    response,
 6400                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
 6401                    buffer_handle.clone(),
 6402                    cx.clone(),
 6403                )
 6404                .await
 6405                .context("inlay hints proto response conversion")
 6406            })
 6407        } else {
 6408            Task::ready(Err(anyhow!("project does not have a remote id")))
 6409        }
 6410    }
 6411
 6412    pub fn resolve_inlay_hint(
 6413        &self,
 6414        hint: InlayHint,
 6415        buffer_handle: Model<Buffer>,
 6416        server_id: LanguageServerId,
 6417        cx: &mut ModelContext<Self>,
 6418    ) -> Task<anyhow::Result<InlayHint>> {
 6419        if self.is_local() {
 6420            let buffer = buffer_handle.read(cx);
 6421            let (_, lang_server) = if let Some((adapter, server)) =
 6422                self.language_server_for_buffer(buffer, server_id, cx)
 6423            {
 6424                (adapter.clone(), server.clone())
 6425            } else {
 6426                return Task::ready(Ok(hint));
 6427            };
 6428            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
 6429                return Task::ready(Ok(hint));
 6430            }
 6431
 6432            let buffer_snapshot = buffer.snapshot();
 6433            cx.spawn(move |_, mut cx| async move {
 6434                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
 6435                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
 6436                );
 6437                let resolved_hint = resolve_task
 6438                    .await
 6439                    .context("inlay hint resolve LSP request")?;
 6440                let resolved_hint = InlayHints::lsp_to_project_hint(
 6441                    resolved_hint,
 6442                    &buffer_handle,
 6443                    server_id,
 6444                    ResolveState::Resolved,
 6445                    false,
 6446                    &mut cx,
 6447                )
 6448                .await?;
 6449                Ok(resolved_hint)
 6450            })
 6451        } else if let Some(project_id) = self.remote_id() {
 6452            let client = self.client.clone();
 6453            let request = proto::ResolveInlayHint {
 6454                project_id,
 6455                buffer_id: buffer_handle.read(cx).remote_id().into(),
 6456                language_server_id: server_id.0 as u64,
 6457                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
 6458            };
 6459            cx.spawn(move |_, _| async move {
 6460                let response = client
 6461                    .request(request)
 6462                    .await
 6463                    .context("inlay hints proto request")?;
 6464                match response.hint {
 6465                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
 6466                        .context("inlay hints proto resolve response conversion"),
 6467                    None => Ok(hint),
 6468                }
 6469            })
 6470        } else {
 6471            Task::ready(Err(anyhow!("project does not have a remote id")))
 6472        }
 6473    }
 6474
 6475    #[allow(clippy::type_complexity)]
 6476    pub fn search(
 6477        &self,
 6478        query: SearchQuery,
 6479        cx: &mut ModelContext<Self>,
 6480    ) -> Receiver<SearchResult> {
 6481        if self.is_local() {
 6482            self.search_local(query, cx)
 6483        } else if let Some(project_id) = self.remote_id() {
 6484            let (tx, rx) = smol::channel::unbounded();
 6485            let request = self.client.request(query.to_proto(project_id));
 6486            cx.spawn(move |this, mut cx| async move {
 6487                let response = request.await?;
 6488                let mut result = HashMap::default();
 6489                for location in response.locations {
 6490                    let buffer_id = BufferId::new(location.buffer_id)?;
 6491                    let target_buffer = this
 6492                        .update(&mut cx, |this, cx| {
 6493                            this.wait_for_remote_buffer(buffer_id, cx)
 6494                        })?
 6495                        .await?;
 6496                    let start = location
 6497                        .start
 6498                        .and_then(deserialize_anchor)
 6499                        .ok_or_else(|| anyhow!("missing target start"))?;
 6500                    let end = location
 6501                        .end
 6502                        .and_then(deserialize_anchor)
 6503                        .ok_or_else(|| anyhow!("missing target end"))?;
 6504                    result
 6505                        .entry(target_buffer)
 6506                        .or_insert(Vec::new())
 6507                        .push(start..end)
 6508                }
 6509                for (buffer, ranges) in result {
 6510                    let _ = tx.send(SearchResult::Buffer { buffer, ranges }).await;
 6511                }
 6512
 6513                if response.limit_reached {
 6514                    let _ = tx.send(SearchResult::LimitReached).await;
 6515                }
 6516
 6517                Result::<(), anyhow::Error>::Ok(())
 6518            })
 6519            .detach_and_log_err(cx);
 6520            rx
 6521        } else {
 6522            unimplemented!();
 6523        }
 6524    }
 6525
 6526    pub fn search_local(
 6527        &self,
 6528        query: SearchQuery,
 6529        cx: &mut ModelContext<Self>,
 6530    ) -> Receiver<SearchResult> {
 6531        // Local search is split into several phases.
 6532        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
 6533        // and the second phase that finds positions of all the matches found in the candidate files.
 6534        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
 6535        //
 6536        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
 6537        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
 6538        //
 6539        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
 6540        //    Then, we go through a worktree and check for files that do match a predicate. If the file had an opened version, we skip the scan
 6541        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
 6542        // 2. At this point, we have a list of all potentially matching buffers/files.
 6543        //    We sort that list by buffer path - this list is retained for later use.
 6544        //    We ensure that all buffers are now opened and available in project.
 6545        // 3. We run a scan over all the candidate buffers on multiple background threads.
 6546        //    We cannot assume that there will even be a match - while at least one match
 6547        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
 6548        //    There is also an auxiliary background thread responsible for result gathering.
 6549        //    This is where the sorted list of buffers comes into play to maintain sorted order; Whenever this background thread receives a notification (buffer has/doesn't have matches),
 6550        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
 6551        //    As soon as the match info on next position in sorted order becomes available, it reports it (if it's a match) or skips to the next
 6552        //    entry - which might already be available thanks to out-of-order processing.
 6553        //
 6554        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
 6555        // This however would mean that project search (that is the main user of this function) would have to do the sorting itself, on the go.
 6556        // This isn't as straightforward as running an insertion sort sadly, and would also mean that it would have to care about maintaining match index
 6557        // in face of constantly updating list of sorted matches.
 6558        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
 6559        let snapshots = self
 6560            .visible_worktrees(cx)
 6561            .filter_map(|tree| {
 6562                let tree = tree.read(cx).as_local()?;
 6563                Some(tree.snapshot())
 6564            })
 6565            .collect::<Vec<_>>();
 6566        let include_root = snapshots.len() > 1;
 6567
 6568        let background = cx.background_executor().clone();
 6569        let path_count: usize = snapshots
 6570            .iter()
 6571            .map(|s| {
 6572                if query.include_ignored() {
 6573                    s.file_count()
 6574                } else {
 6575                    s.visible_file_count()
 6576                }
 6577            })
 6578            .sum();
 6579        if path_count == 0 {
 6580            let (_, rx) = smol::channel::bounded(1024);
 6581            return rx;
 6582        }
 6583        let workers = background.num_cpus().min(path_count);
 6584        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
 6585        let mut unnamed_files = vec![];
 6586        let opened_buffers = self
 6587            .opened_buffers
 6588            .iter()
 6589            .filter_map(|(_, b)| {
 6590                let buffer = b.upgrade()?;
 6591                let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
 6592                    let is_ignored = buffer
 6593                        .project_path(cx)
 6594                        .and_then(|path| self.entry_for_path(&path, cx))
 6595                        .map_or(false, |entry| entry.is_ignored);
 6596                    (is_ignored, buffer.snapshot())
 6597                });
 6598                if is_ignored && !query.include_ignored() {
 6599                    return None;
 6600                } else if let Some(file) = snapshot.file() {
 6601                    let matched_path = if include_root {
 6602                        query.file_matches(Some(&file.full_path(cx)))
 6603                    } else {
 6604                        query.file_matches(Some(file.path()))
 6605                    };
 6606
 6607                    if matched_path {
 6608                        Some((file.path().clone(), (buffer, snapshot)))
 6609                    } else {
 6610                        None
 6611                    }
 6612                } else {
 6613                    unnamed_files.push(buffer);
 6614                    None
 6615                }
 6616            })
 6617            .collect();
 6618        cx.background_executor()
 6619            .spawn(Self::background_search(
 6620                unnamed_files,
 6621                opened_buffers,
 6622                cx.background_executor().clone(),
 6623                self.fs.clone(),
 6624                workers,
 6625                query.clone(),
 6626                include_root,
 6627                path_count,
 6628                snapshots,
 6629                matching_paths_tx,
 6630            ))
 6631            .detach();
 6632
 6633        let (result_tx, result_rx) = smol::channel::bounded(1024);
 6634
 6635        cx.spawn(|this, mut cx| async move {
 6636            const MAX_SEARCH_RESULT_FILES: usize = 5_000;
 6637            const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
 6638
 6639            let mut matching_paths = matching_paths_rx
 6640                .take(MAX_SEARCH_RESULT_FILES + 1)
 6641                .collect::<Vec<_>>()
 6642                .await;
 6643            let mut limit_reached = if matching_paths.len() > MAX_SEARCH_RESULT_FILES {
 6644                matching_paths.pop();
 6645                true
 6646            } else {
 6647                false
 6648            };
 6649            matching_paths.sort_by_key(|candidate| (candidate.is_ignored(), candidate.path()));
 6650
 6651            let mut range_count = 0;
 6652            let query = Arc::new(query);
 6653
 6654            // Now that we know what paths match the query, we will load at most
 6655            // 64 buffers at a time to avoid overwhelming the main thread. For each
 6656            // opened buffer, we will spawn a background task that retrieves all the
 6657            // ranges in the buffer matched by the query.
 6658            'outer: for matching_paths_chunk in matching_paths.chunks(64) {
 6659                let mut chunk_results = Vec::new();
 6660                for matching_path in matching_paths_chunk {
 6661                    let query = query.clone();
 6662                    let buffer = match matching_path {
 6663                        SearchMatchCandidate::OpenBuffer { buffer, .. } => {
 6664                            Task::ready(Ok(buffer.clone()))
 6665                        }
 6666                        SearchMatchCandidate::Path {
 6667                            worktree_id, path, ..
 6668                        } => this.update(&mut cx, |this, cx| {
 6669                            this.open_buffer((*worktree_id, path.clone()), cx)
 6670                        })?,
 6671                    };
 6672
 6673                    chunk_results.push(cx.spawn(|cx| async move {
 6674                        let buffer = buffer.await?;
 6675                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
 6676                        let ranges = cx
 6677                            .background_executor()
 6678                            .spawn(async move {
 6679                                query
 6680                                    .search(&snapshot, None)
 6681                                    .await
 6682                                    .iter()
 6683                                    .map(|range| {
 6684                                        snapshot.anchor_before(range.start)
 6685                                            ..snapshot.anchor_after(range.end)
 6686                                    })
 6687                                    .collect::<Vec<_>>()
 6688                            })
 6689                            .await;
 6690                        anyhow::Ok((buffer, ranges))
 6691                    }));
 6692                }
 6693
 6694                let chunk_results = futures::future::join_all(chunk_results).await;
 6695                for result in chunk_results {
 6696                    if let Some((buffer, ranges)) = result.log_err() {
 6697                        range_count += ranges.len();
 6698                        result_tx
 6699                            .send(SearchResult::Buffer { buffer, ranges })
 6700                            .await?;
 6701                        if range_count > MAX_SEARCH_RESULT_RANGES {
 6702                            limit_reached = true;
 6703                            break 'outer;
 6704                        }
 6705                    }
 6706                }
 6707            }
 6708
 6709            if limit_reached {
 6710                result_tx.send(SearchResult::LimitReached).await?;
 6711            }
 6712
 6713            anyhow::Ok(())
 6714        })
 6715        .detach();
 6716
 6717        result_rx
 6718    }
 6719
 6720    /// Pick paths that might potentially contain a match of a given search query.
 6721    #[allow(clippy::too_many_arguments)]
 6722    async fn background_search(
 6723        unnamed_buffers: Vec<Model<Buffer>>,
 6724        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
 6725        executor: BackgroundExecutor,
 6726        fs: Arc<dyn Fs>,
 6727        workers: usize,
 6728        query: SearchQuery,
 6729        include_root: bool,
 6730        path_count: usize,
 6731        snapshots: Vec<LocalSnapshot>,
 6732        matching_paths_tx: Sender<SearchMatchCandidate>,
 6733    ) {
 6734        let fs = &fs;
 6735        let query = &query;
 6736        let matching_paths_tx = &matching_paths_tx;
 6737        let snapshots = &snapshots;
 6738        for buffer in unnamed_buffers {
 6739            matching_paths_tx
 6740                .send(SearchMatchCandidate::OpenBuffer {
 6741                    buffer: buffer.clone(),
 6742                    path: None,
 6743                })
 6744                .await
 6745                .log_err();
 6746        }
 6747        for (path, (buffer, _)) in opened_buffers.iter() {
 6748            matching_paths_tx
 6749                .send(SearchMatchCandidate::OpenBuffer {
 6750                    buffer: buffer.clone(),
 6751                    path: Some(path.clone()),
 6752                })
 6753                .await
 6754                .log_err();
 6755        }
 6756
 6757        let paths_per_worker = (path_count + workers - 1) / workers;
 6758
 6759        executor
 6760            .scoped(|scope| {
 6761                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
 6762
 6763                for worker_ix in 0..workers {
 6764                    let worker_start_ix = worker_ix * paths_per_worker;
 6765                    let worker_end_ix = worker_start_ix + paths_per_worker;
 6766                    let opened_buffers = opened_buffers.clone();
 6767                    let limiter = Arc::clone(&max_concurrent_workers);
 6768                    scope.spawn({
 6769                        async move {
 6770                            let _guard = limiter.acquire().await;
 6771                            search_snapshots(
 6772                                snapshots,
 6773                                worker_start_ix,
 6774                                worker_end_ix,
 6775                                query,
 6776                                matching_paths_tx,
 6777                                &opened_buffers,
 6778                                include_root,
 6779                                fs,
 6780                            )
 6781                            .await;
 6782                        }
 6783                    });
 6784                }
 6785
 6786                if query.include_ignored() {
 6787                    for snapshot in snapshots {
 6788                        for ignored_entry in snapshot.entries(true).filter(|e| e.is_ignored) {
 6789                            let limiter = Arc::clone(&max_concurrent_workers);
 6790                            scope.spawn(async move {
 6791                                let _guard = limiter.acquire().await;
 6792                                search_ignored_entry(
 6793                                    snapshot,
 6794                                    ignored_entry,
 6795                                    fs,
 6796                                    query,
 6797                                    matching_paths_tx,
 6798                                )
 6799                                .await;
 6800                            });
 6801                        }
 6802                    }
 6803                }
 6804            })
 6805            .await;
 6806    }
 6807
 6808    pub fn request_lsp<R: LspCommand>(
 6809        &self,
 6810        buffer_handle: Model<Buffer>,
 6811        server: LanguageServerToQuery,
 6812        request: R,
 6813        cx: &mut ModelContext<Self>,
 6814    ) -> Task<Result<R::Response>>
 6815    where
 6816        <R::LspRequest as lsp::request::Request>::Result: Send,
 6817        <R::LspRequest as lsp::request::Request>::Params: Send,
 6818    {
 6819        let buffer = buffer_handle.read(cx);
 6820        if self.is_local() {
 6821            let language_server = match server {
 6822                LanguageServerToQuery::Primary => {
 6823                    match self.primary_language_server_for_buffer(buffer, cx) {
 6824                        Some((_, server)) => Some(Arc::clone(server)),
 6825                        None => return Task::ready(Ok(Default::default())),
 6826                    }
 6827                }
 6828                LanguageServerToQuery::Other(id) => self
 6829                    .language_server_for_buffer(buffer, id, cx)
 6830                    .map(|(_, server)| Arc::clone(server)),
 6831            };
 6832            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
 6833            if let (Some(file), Some(language_server)) = (file, language_server) {
 6834                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
 6835                let status = request.status();
 6836                return cx.spawn(move |this, cx| async move {
 6837                    if !request.check_capabilities(language_server.capabilities()) {
 6838                        return Ok(Default::default());
 6839                    }
 6840
 6841                    let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
 6842
 6843                    let id = lsp_request.id();
 6844                    let _cleanup = if status.is_some() {
 6845                        cx.update(|cx| {
 6846                            this.update(cx, |this, cx| {
 6847                                this.on_lsp_work_start(
 6848                                    language_server.server_id(),
 6849                                    id.to_string(),
 6850                                    LanguageServerProgress {
 6851                                        message: status.clone(),
 6852                                        percentage: None,
 6853                                        last_update_at: Instant::now(),
 6854                                    },
 6855                                    cx,
 6856                                );
 6857                            })
 6858                        })
 6859                        .log_err();
 6860
 6861                        Some(defer(|| {
 6862                            cx.update(|cx| {
 6863                                this.update(cx, |this, cx| {
 6864                                    this.on_lsp_work_end(
 6865                                        language_server.server_id(),
 6866                                        id.to_string(),
 6867                                        cx,
 6868                                    );
 6869                                })
 6870                            })
 6871                            .log_err();
 6872                        }))
 6873                    } else {
 6874                        None
 6875                    };
 6876
 6877                    let result = lsp_request.await;
 6878
 6879                    let response = result.map_err(|err| {
 6880                        log::warn!(
 6881                            "Generic lsp request to {} failed: {}",
 6882                            language_server.name(),
 6883                            err
 6884                        );
 6885                        err
 6886                    })?;
 6887
 6888                    request
 6889                        .response_from_lsp(
 6890                            response,
 6891                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
 6892                            buffer_handle,
 6893                            language_server.server_id(),
 6894                            cx.clone(),
 6895                        )
 6896                        .await
 6897                });
 6898            }
 6899        } else if let Some(project_id) = self.remote_id() {
 6900            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
 6901        }
 6902
 6903        Task::ready(Ok(Default::default()))
 6904    }
 6905
 6906    fn request_multiple_lsp_locally<P, R>(
 6907        &self,
 6908        buffer: &Model<Buffer>,
 6909        position: Option<P>,
 6910        server_capabilities_check: fn(&ServerCapabilities) -> bool,
 6911        request: R,
 6912        cx: &mut ModelContext<'_, Self>,
 6913    ) -> Task<Vec<R::Response>>
 6914    where
 6915        P: ToOffset,
 6916        R: LspCommand + Clone,
 6917        <R::LspRequest as lsp::request::Request>::Result: Send,
 6918        <R::LspRequest as lsp::request::Request>::Params: Send,
 6919    {
 6920        if !self.is_local() {
 6921            debug_panic!("Should not request multiple lsp commands in non-local project");
 6922            return Task::ready(Vec::new());
 6923        }
 6924        let snapshot = buffer.read(cx).snapshot();
 6925        let scope = position.and_then(|position| snapshot.language_scope_at(position));
 6926        let mut response_results = self
 6927            .language_servers_for_buffer(buffer.read(cx), cx)
 6928            .filter(|(_, server)| server_capabilities_check(server.capabilities()))
 6929            .filter(|(adapter, _)| {
 6930                scope
 6931                    .as_ref()
 6932                    .map(|scope| scope.language_allowed(&adapter.name))
 6933                    .unwrap_or(true)
 6934            })
 6935            .map(|(_, server)| server.server_id())
 6936            .map(|server_id| {
 6937                self.request_lsp(
 6938                    buffer.clone(),
 6939                    LanguageServerToQuery::Other(server_id),
 6940                    request.clone(),
 6941                    cx,
 6942                )
 6943            })
 6944            .collect::<FuturesUnordered<_>>();
 6945
 6946        return cx.spawn(|_, _| async move {
 6947            let mut responses = Vec::with_capacity(response_results.len());
 6948            while let Some(response_result) = response_results.next().await {
 6949                if let Some(response) = response_result.log_err() {
 6950                    responses.push(response);
 6951                }
 6952            }
 6953            responses
 6954        });
 6955    }
 6956
 6957    fn send_lsp_proto_request<R: LspCommand>(
 6958        &self,
 6959        buffer: Model<Buffer>,
 6960        project_id: u64,
 6961        request: R,
 6962        cx: &mut ModelContext<'_, Project>,
 6963    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
 6964        let rpc = self.client.clone();
 6965        let message = request.to_proto(project_id, buffer.read(cx));
 6966        cx.spawn(move |this, mut cx| async move {
 6967            // Ensure the project is still alive by the time the task
 6968            // is scheduled.
 6969            this.upgrade().context("project dropped")?;
 6970            let response = rpc.request(message).await?;
 6971            let this = this.upgrade().context("project dropped")?;
 6972            if this.update(&mut cx, |this, _| this.is_disconnected())? {
 6973                Err(anyhow!("disconnected before completing request"))
 6974            } else {
 6975                request
 6976                    .response_from_proto(response, this, buffer, cx)
 6977                    .await
 6978            }
 6979        })
 6980    }
 6981
 6982    pub fn find_or_create_local_worktree(
 6983        &mut self,
 6984        abs_path: impl AsRef<Path>,
 6985        visible: bool,
 6986        cx: &mut ModelContext<Self>,
 6987    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
 6988        let abs_path = abs_path.as_ref();
 6989        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
 6990            Task::ready(Ok((tree, relative_path)))
 6991        } else {
 6992            let worktree = self.create_local_worktree(abs_path, visible, cx);
 6993            cx.background_executor()
 6994                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
 6995        }
 6996    }
 6997
 6998    pub fn find_local_worktree(
 6999        &self,
 7000        abs_path: &Path,
 7001        cx: &AppContext,
 7002    ) -> Option<(Model<Worktree>, PathBuf)> {
 7003        for tree in &self.worktrees {
 7004            if let Some(tree) = tree.upgrade() {
 7005                if let Some(relative_path) = tree
 7006                    .read(cx)
 7007                    .as_local()
 7008                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
 7009                {
 7010                    return Some((tree.clone(), relative_path.into()));
 7011                }
 7012            }
 7013        }
 7014        None
 7015    }
 7016
 7017    pub fn is_shared(&self) -> bool {
 7018        match &self.client_state {
 7019            ProjectClientState::Shared { .. } => true,
 7020            ProjectClientState::Local => false,
 7021            ProjectClientState::Remote { in_room, .. } => *in_room,
 7022        }
 7023    }
 7024
 7025    fn create_local_worktree(
 7026        &mut self,
 7027        abs_path: impl AsRef<Path>,
 7028        visible: bool,
 7029        cx: &mut ModelContext<Self>,
 7030    ) -> Task<Result<Model<Worktree>>> {
 7031        let fs = self.fs.clone();
 7032        let client = self.client.clone();
 7033        let next_entry_id = self.next_entry_id.clone();
 7034        let path: Arc<Path> = abs_path.as_ref().into();
 7035        let task = self
 7036            .loading_local_worktrees
 7037            .entry(path.clone())
 7038            .or_insert_with(|| {
 7039                cx.spawn(move |project, mut cx| {
 7040                    async move {
 7041                        let worktree = Worktree::local(
 7042                            client.clone(),
 7043                            path.clone(),
 7044                            visible,
 7045                            fs,
 7046                            next_entry_id,
 7047                            &mut cx,
 7048                        )
 7049                        .await;
 7050
 7051                        project.update(&mut cx, |project, _| {
 7052                            project.loading_local_worktrees.remove(&path);
 7053                        })?;
 7054
 7055                        let worktree = worktree?;
 7056                        project
 7057                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
 7058
 7059                        if visible {
 7060                            cx.update(|cx| {
 7061                                cx.add_recent_document(&path);
 7062                            })
 7063                            .log_err();
 7064                        }
 7065
 7066                        Ok(worktree)
 7067                    }
 7068                    .map_err(Arc::new)
 7069                })
 7070                .shared()
 7071            })
 7072            .clone();
 7073        cx.background_executor().spawn(async move {
 7074            match task.await {
 7075                Ok(worktree) => Ok(worktree),
 7076                Err(err) => Err(anyhow!("{}", err)),
 7077            }
 7078        })
 7079    }
 7080
 7081    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
 7082        let mut servers_to_remove = HashMap::default();
 7083        let mut servers_to_preserve = HashSet::default();
 7084        for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
 7085            if worktree_id == &id_to_remove {
 7086                servers_to_remove.insert(server_id, server_name.clone());
 7087            } else {
 7088                servers_to_preserve.insert(server_id);
 7089            }
 7090        }
 7091        servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
 7092        for (server_id_to_remove, server_name) in servers_to_remove {
 7093            self.language_server_ids
 7094                .remove(&(id_to_remove, server_name));
 7095            self.language_server_statuses.remove(&server_id_to_remove);
 7096            self.language_server_watched_paths
 7097                .remove(&server_id_to_remove);
 7098            self.last_workspace_edits_by_language_server
 7099                .remove(&server_id_to_remove);
 7100            self.language_servers.remove(&server_id_to_remove);
 7101            cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
 7102        }
 7103
 7104        let mut prettier_instances_to_clean = FuturesUnordered::new();
 7105        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
 7106            for path in prettier_paths.iter().flatten() {
 7107                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
 7108                    prettier_instances_to_clean.push(async move {
 7109                        prettier_instance
 7110                            .server()
 7111                            .await
 7112                            .map(|server| server.server_id())
 7113                    });
 7114                }
 7115            }
 7116        }
 7117        cx.spawn(|project, mut cx| async move {
 7118            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
 7119                if let Some(prettier_server_id) = prettier_server_id {
 7120                    project
 7121                        .update(&mut cx, |project, cx| {
 7122                            project
 7123                                .supplementary_language_servers
 7124                                .remove(&prettier_server_id);
 7125                            cx.emit(Event::LanguageServerRemoved(prettier_server_id));
 7126                        })
 7127                        .ok();
 7128                }
 7129            }
 7130        })
 7131        .detach();
 7132
 7133        self.task_inventory().update(cx, |inventory, _| {
 7134            inventory.remove_worktree_sources(id_to_remove);
 7135        });
 7136
 7137        self.worktrees.retain(|worktree| {
 7138            if let Some(worktree) = worktree.upgrade() {
 7139                let id = worktree.read(cx).id();
 7140                if id == id_to_remove {
 7141                    cx.emit(Event::WorktreeRemoved(id));
 7142                    false
 7143                } else {
 7144                    true
 7145                }
 7146            } else {
 7147                false
 7148            }
 7149        });
 7150        self.metadata_changed(cx);
 7151    }
 7152
 7153    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
 7154        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
 7155        cx.subscribe(worktree, |this, worktree, event, cx| {
 7156            let is_local = worktree.read(cx).is_local();
 7157            match event {
 7158                worktree::Event::UpdatedEntries(changes) => {
 7159                    if is_local {
 7160                        this.update_local_worktree_buffers(&worktree, changes, cx);
 7161                        this.update_local_worktree_language_servers(&worktree, changes, cx);
 7162                        this.update_local_worktree_settings(&worktree, changes, cx);
 7163                        this.update_prettier_settings(&worktree, changes, cx);
 7164                    }
 7165
 7166                    cx.emit(Event::WorktreeUpdatedEntries(
 7167                        worktree.read(cx).id(),
 7168                        changes.clone(),
 7169                    ));
 7170                }
 7171                worktree::Event::UpdatedGitRepositories(updated_repos) => {
 7172                    if is_local {
 7173                        this.update_local_worktree_buffers_git_repos(
 7174                            worktree.clone(),
 7175                            updated_repos,
 7176                            cx,
 7177                        )
 7178                    }
 7179                    cx.emit(Event::WorktreeUpdatedGitRepositories);
 7180                }
 7181            }
 7182        })
 7183        .detach();
 7184
 7185        let push_strong_handle = {
 7186            let worktree = worktree.read(cx);
 7187            self.is_shared() || worktree.is_visible() || worktree.is_remote()
 7188        };
 7189        if push_strong_handle {
 7190            self.worktrees
 7191                .push(WorktreeHandle::Strong(worktree.clone()));
 7192        } else {
 7193            self.worktrees
 7194                .push(WorktreeHandle::Weak(worktree.downgrade()));
 7195        }
 7196
 7197        let handle_id = worktree.entity_id();
 7198        cx.observe_release(worktree, move |this, worktree, cx| {
 7199            let _ = this.remove_worktree(worktree.id(), cx);
 7200            cx.update_global::<SettingsStore, _>(|store, cx| {
 7201                store
 7202                    .clear_local_settings(handle_id.as_u64() as usize, cx)
 7203                    .log_err()
 7204            });
 7205        })
 7206        .detach();
 7207
 7208        cx.emit(Event::WorktreeAdded);
 7209        self.metadata_changed(cx);
 7210    }
 7211
 7212    fn update_local_worktree_buffers(
 7213        &mut self,
 7214        worktree_handle: &Model<Worktree>,
 7215        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7216        cx: &mut ModelContext<Self>,
 7217    ) {
 7218        let snapshot = worktree_handle.read(cx).snapshot();
 7219
 7220        let mut renamed_buffers = Vec::new();
 7221        for (path, entry_id, _) in changes {
 7222            let worktree_id = worktree_handle.read(cx).id();
 7223            let project_path = ProjectPath {
 7224                worktree_id,
 7225                path: path.clone(),
 7226            };
 7227
 7228            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
 7229                Some(&buffer_id) => buffer_id,
 7230                None => match self.local_buffer_ids_by_path.get(&project_path) {
 7231                    Some(&buffer_id) => buffer_id,
 7232                    None => {
 7233                        continue;
 7234                    }
 7235                },
 7236            };
 7237
 7238            let open_buffer = self.opened_buffers.get(&buffer_id);
 7239            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
 7240                buffer
 7241            } else {
 7242                self.opened_buffers.remove(&buffer_id);
 7243                self.local_buffer_ids_by_path.remove(&project_path);
 7244                self.local_buffer_ids_by_entry_id.remove(entry_id);
 7245                continue;
 7246            };
 7247
 7248            buffer.update(cx, |buffer, cx| {
 7249                if let Some(old_file) = File::from_dyn(buffer.file()) {
 7250                    if old_file.worktree != *worktree_handle {
 7251                        return;
 7252                    }
 7253
 7254                    let new_file = if let Some(entry) = old_file
 7255                        .entry_id
 7256                        .and_then(|entry_id| snapshot.entry_for_id(entry_id))
 7257                    {
 7258                        File {
 7259                            is_local: true,
 7260                            entry_id: Some(entry.id),
 7261                            mtime: entry.mtime,
 7262                            path: entry.path.clone(),
 7263                            worktree: worktree_handle.clone(),
 7264                            is_deleted: false,
 7265                            is_private: entry.is_private,
 7266                        }
 7267                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
 7268                        File {
 7269                            is_local: true,
 7270                            entry_id: Some(entry.id),
 7271                            mtime: entry.mtime,
 7272                            path: entry.path.clone(),
 7273                            worktree: worktree_handle.clone(),
 7274                            is_deleted: false,
 7275                            is_private: entry.is_private,
 7276                        }
 7277                    } else {
 7278                        File {
 7279                            is_local: true,
 7280                            entry_id: old_file.entry_id,
 7281                            path: old_file.path().clone(),
 7282                            mtime: old_file.mtime(),
 7283                            worktree: worktree_handle.clone(),
 7284                            is_deleted: true,
 7285                            is_private: old_file.is_private,
 7286                        }
 7287                    };
 7288
 7289                    let old_path = old_file.abs_path(cx);
 7290                    if new_file.abs_path(cx) != old_path {
 7291                        renamed_buffers.push((cx.handle(), old_file.clone()));
 7292                        self.local_buffer_ids_by_path.remove(&project_path);
 7293                        self.local_buffer_ids_by_path.insert(
 7294                            ProjectPath {
 7295                                worktree_id,
 7296                                path: path.clone(),
 7297                            },
 7298                            buffer_id,
 7299                        );
 7300                    }
 7301
 7302                    if new_file.entry_id != Some(*entry_id) {
 7303                        self.local_buffer_ids_by_entry_id.remove(entry_id);
 7304                        if let Some(entry_id) = new_file.entry_id {
 7305                            self.local_buffer_ids_by_entry_id
 7306                                .insert(entry_id, buffer_id);
 7307                        }
 7308                    }
 7309
 7310                    if new_file != *old_file {
 7311                        if let Some(project_id) = self.remote_id() {
 7312                            self.client
 7313                                .send(proto::UpdateBufferFile {
 7314                                    project_id,
 7315                                    buffer_id: buffer_id.into(),
 7316                                    file: Some(new_file.to_proto()),
 7317                                })
 7318                                .log_err();
 7319                        }
 7320
 7321                        buffer.file_updated(Arc::new(new_file), cx);
 7322                    }
 7323                }
 7324            });
 7325        }
 7326
 7327        for (buffer, old_file) in renamed_buffers {
 7328            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
 7329            self.detect_language_for_buffer(&buffer, cx);
 7330            self.register_buffer_with_language_servers(&buffer, cx);
 7331        }
 7332    }
 7333
 7334    fn update_local_worktree_language_servers(
 7335        &mut self,
 7336        worktree_handle: &Model<Worktree>,
 7337        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7338        cx: &mut ModelContext<Self>,
 7339    ) {
 7340        if changes.is_empty() {
 7341            return;
 7342        }
 7343
 7344        let worktree_id = worktree_handle.read(cx).id();
 7345        let mut language_server_ids = self
 7346            .language_server_ids
 7347            .iter()
 7348            .filter_map(|((server_worktree_id, _), server_id)| {
 7349                (*server_worktree_id == worktree_id).then_some(*server_id)
 7350            })
 7351            .collect::<Vec<_>>();
 7352        language_server_ids.sort();
 7353        language_server_ids.dedup();
 7354
 7355        let abs_path = worktree_handle.read(cx).abs_path();
 7356        for server_id in &language_server_ids {
 7357            if let Some(LanguageServerState::Running { server, .. }) =
 7358                self.language_servers.get(server_id)
 7359            {
 7360                if let Some(watched_paths) = self
 7361                    .language_server_watched_paths
 7362                    .get(&server_id)
 7363                    .and_then(|paths| paths.get(&worktree_id))
 7364                {
 7365                    let params = lsp::DidChangeWatchedFilesParams {
 7366                        changes: changes
 7367                            .iter()
 7368                            .filter_map(|(path, _, change)| {
 7369                                if !watched_paths.is_match(&path) {
 7370                                    return None;
 7371                                }
 7372                                let typ = match change {
 7373                                    PathChange::Loaded => return None,
 7374                                    PathChange::Added => lsp::FileChangeType::CREATED,
 7375                                    PathChange::Removed => lsp::FileChangeType::DELETED,
 7376                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
 7377                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
 7378                                };
 7379                                Some(lsp::FileEvent {
 7380                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
 7381                                    typ,
 7382                                })
 7383                            })
 7384                            .collect(),
 7385                    };
 7386                    if !params.changes.is_empty() {
 7387                        server
 7388                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
 7389                            .log_err();
 7390                    }
 7391                }
 7392            }
 7393        }
 7394    }
 7395
 7396    fn update_local_worktree_buffers_git_repos(
 7397        &mut self,
 7398        worktree_handle: Model<Worktree>,
 7399        changed_repos: &UpdatedGitRepositoriesSet,
 7400        cx: &mut ModelContext<Self>,
 7401    ) {
 7402        debug_assert!(worktree_handle.read(cx).is_local());
 7403
 7404        // Identify the loading buffers whose containing repository that has changed.
 7405        let future_buffers = self
 7406            .loading_buffers_by_path
 7407            .iter()
 7408            .filter_map(|(project_path, receiver)| {
 7409                if project_path.worktree_id != worktree_handle.read(cx).id() {
 7410                    return None;
 7411                }
 7412                let path = &project_path.path;
 7413                changed_repos
 7414                    .iter()
 7415                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 7416                let receiver = receiver.clone();
 7417                let path = path.clone();
 7418                let abs_path = worktree_handle.read(cx).absolutize(&path).ok()?;
 7419                Some(async move {
 7420                    wait_for_loading_buffer(receiver)
 7421                        .await
 7422                        .ok()
 7423                        .map(|buffer| (buffer, path, abs_path))
 7424                })
 7425            })
 7426            .collect::<FuturesUnordered<_>>();
 7427
 7428        // Identify the current buffers whose containing repository has changed.
 7429        let current_buffers = self
 7430            .opened_buffers
 7431            .values()
 7432            .filter_map(|buffer| {
 7433                let buffer = buffer.upgrade()?;
 7434                let file = File::from_dyn(buffer.read(cx).file())?;
 7435                if file.worktree != worktree_handle {
 7436                    return None;
 7437                }
 7438                let path = file.path();
 7439                changed_repos
 7440                    .iter()
 7441                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 7442                Some((buffer, path.clone(), file.abs_path(cx)))
 7443            })
 7444            .collect::<Vec<_>>();
 7445
 7446        if future_buffers.len() + current_buffers.len() == 0 {
 7447            return;
 7448        }
 7449
 7450        let remote_id = self.remote_id();
 7451        let client = self.client.clone();
 7452        let fs = self.fs.clone();
 7453        cx.spawn(move |_, mut cx| async move {
 7454            // Wait for all of the buffers to load.
 7455            let future_buffers = future_buffers.collect::<Vec<_>>().await;
 7456
 7457            // Reload the diff base for every buffer whose containing git repository has changed.
 7458            let snapshot =
 7459                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
 7460            let diff_bases_by_buffer = cx
 7461                .background_executor()
 7462                .spawn(async move {
 7463                    let mut diff_base_tasks = future_buffers
 7464                        .into_iter()
 7465                        .flatten()
 7466                        .chain(current_buffers)
 7467                        .filter_map(|(buffer, path, abs_path)| {
 7468                            let (work_directory, repo) =
 7469                                snapshot.repository_and_work_directory_for_path(&path)?;
 7470                            let repo_entry = snapshot.get_local_repo(&repo)?;
 7471                            Some((buffer, path, abs_path, work_directory, repo_entry))
 7472                        })
 7473                        .map(|(buffer, path, abs_path, work_directory, repo_entry)| {
 7474                            let fs = fs.clone();
 7475                            async move {
 7476                                let abs_path_metadata = fs
 7477                                    .metadata(&abs_path)
 7478                                    .await
 7479                                    .with_context(|| {
 7480                                        format!("loading file and FS metadata for {path:?}")
 7481                                    })
 7482                                    .log_err()
 7483                                    .flatten()?;
 7484                                let base_text = if abs_path_metadata.is_dir
 7485                                    || abs_path_metadata.is_symlink
 7486                                {
 7487                                    None
 7488                                } else {
 7489                                    let relative_path = path.strip_prefix(&work_directory).ok()?;
 7490                                    repo_entry.repo().lock().load_index_text(relative_path)
 7491                                };
 7492                                Some((buffer, base_text))
 7493                            }
 7494                        })
 7495                        .collect::<FuturesUnordered<_>>();
 7496
 7497                    let mut diff_bases = Vec::with_capacity(diff_base_tasks.len());
 7498                    while let Some(diff_base) = diff_base_tasks.next().await {
 7499                        if let Some(diff_base) = diff_base {
 7500                            diff_bases.push(diff_base);
 7501                        }
 7502                    }
 7503                    diff_bases
 7504                })
 7505                .await;
 7506
 7507            // Assign the new diff bases on all of the buffers.
 7508            for (buffer, diff_base) in diff_bases_by_buffer {
 7509                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
 7510                    buffer.set_diff_base(diff_base.clone(), cx);
 7511                    buffer.remote_id().into()
 7512                })?;
 7513                if let Some(project_id) = remote_id {
 7514                    client
 7515                        .send(proto::UpdateDiffBase {
 7516                            project_id,
 7517                            buffer_id,
 7518                            diff_base,
 7519                        })
 7520                        .log_err();
 7521                }
 7522            }
 7523
 7524            anyhow::Ok(())
 7525        })
 7526        .detach();
 7527    }
 7528
 7529    fn update_local_worktree_settings(
 7530        &mut self,
 7531        worktree: &Model<Worktree>,
 7532        changes: &UpdatedEntriesSet,
 7533        cx: &mut ModelContext<Self>,
 7534    ) {
 7535        if worktree.read(cx).as_local().is_none() {
 7536            return;
 7537        }
 7538        let project_id = self.remote_id();
 7539        let worktree_id = worktree.entity_id();
 7540        let remote_worktree_id = worktree.read(cx).id();
 7541
 7542        let mut settings_contents = Vec::new();
 7543        for (path, _, change) in changes.iter() {
 7544            let removed = change == &PathChange::Removed;
 7545            let abs_path = match worktree.read(cx).absolutize(path) {
 7546                Ok(abs_path) => abs_path,
 7547                Err(e) => {
 7548                    log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
 7549                    continue;
 7550                }
 7551            };
 7552
 7553            if abs_path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
 7554                let settings_dir = Arc::from(
 7555                    path.ancestors()
 7556                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
 7557                        .unwrap(),
 7558                );
 7559                let fs = self.fs.clone();
 7560                settings_contents.push(async move {
 7561                    (
 7562                        settings_dir,
 7563                        if removed {
 7564                            None
 7565                        } else {
 7566                            Some(async move { fs.load(&abs_path).await }.await)
 7567                        },
 7568                    )
 7569                });
 7570            } else if abs_path.ends_with(&*LOCAL_TASKS_RELATIVE_PATH) {
 7571                self.task_inventory().update(cx, |task_inventory, cx| {
 7572                    if removed {
 7573                        task_inventory.remove_local_static_source(&abs_path);
 7574                    } else {
 7575                        let fs = self.fs.clone();
 7576                        let task_abs_path = abs_path.clone();
 7577                        task_inventory.add_source(
 7578                            TaskSourceKind::Worktree {
 7579                                id: remote_worktree_id,
 7580                                abs_path,
 7581                                id_base: "local_tasks_for_worktree",
 7582                            },
 7583                            |cx| {
 7584                                let tasks_file_rx =
 7585                                    watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7586                                StaticSource::new(TrackedFile::new(tasks_file_rx, cx), cx)
 7587                            },
 7588                            cx,
 7589                        );
 7590                    }
 7591                })
 7592            } else if abs_path.ends_with(&*LOCAL_VSCODE_TASKS_RELATIVE_PATH) {
 7593                self.task_inventory().update(cx, |task_inventory, cx| {
 7594                    if removed {
 7595                        task_inventory.remove_local_static_source(&abs_path);
 7596                    } else {
 7597                        let fs = self.fs.clone();
 7598                        let task_abs_path = abs_path.clone();
 7599                        task_inventory.add_source(
 7600                            TaskSourceKind::Worktree {
 7601                                id: remote_worktree_id,
 7602                                abs_path,
 7603                                id_base: "local_vscode_tasks_for_worktree",
 7604                            },
 7605                            |cx| {
 7606                                let tasks_file_rx =
 7607                                    watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7608                                StaticSource::new(
 7609                                    TrackedFile::new_convertible::<task::VsCodeTaskFile>(
 7610                                        tasks_file_rx,
 7611                                        cx,
 7612                                    ),
 7613                                    cx,
 7614                                )
 7615                            },
 7616                            cx,
 7617                        );
 7618                    }
 7619                })
 7620            }
 7621        }
 7622
 7623        if settings_contents.is_empty() {
 7624            return;
 7625        }
 7626
 7627        let client = self.client.clone();
 7628        cx.spawn(move |_, cx| async move {
 7629            let settings_contents: Vec<(Arc<Path>, _)> =
 7630                futures::future::join_all(settings_contents).await;
 7631            cx.update(|cx| {
 7632                cx.update_global::<SettingsStore, _>(|store, cx| {
 7633                    for (directory, file_content) in settings_contents {
 7634                        let file_content = file_content.and_then(|content| content.log_err());
 7635                        store
 7636                            .set_local_settings(
 7637                                worktree_id.as_u64() as usize,
 7638                                directory.clone(),
 7639                                file_content.as_deref(),
 7640                                cx,
 7641                            )
 7642                            .log_err();
 7643                        if let Some(remote_id) = project_id {
 7644                            client
 7645                                .send(proto::UpdateWorktreeSettings {
 7646                                    project_id: remote_id,
 7647                                    worktree_id: remote_worktree_id.to_proto(),
 7648                                    path: directory.to_string_lossy().into_owned(),
 7649                                    content: file_content,
 7650                                })
 7651                                .log_err();
 7652                        }
 7653                    }
 7654                });
 7655            })
 7656            .ok();
 7657        })
 7658        .detach();
 7659    }
 7660
 7661    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
 7662        let new_active_entry = entry.and_then(|project_path| {
 7663            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 7664            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
 7665            Some(entry.id)
 7666        });
 7667        if new_active_entry != self.active_entry {
 7668            self.active_entry = new_active_entry;
 7669            cx.emit(Event::ActiveEntryChanged(new_active_entry));
 7670        }
 7671    }
 7672
 7673    pub fn language_servers_running_disk_based_diagnostics(
 7674        &self,
 7675    ) -> impl Iterator<Item = LanguageServerId> + '_ {
 7676        self.language_server_statuses
 7677            .iter()
 7678            .filter_map(|(id, status)| {
 7679                if status.has_pending_diagnostic_updates {
 7680                    Some(*id)
 7681                } else {
 7682                    None
 7683                }
 7684            })
 7685    }
 7686
 7687    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
 7688        let mut summary = DiagnosticSummary::default();
 7689        for (_, _, path_summary) in
 7690            self.diagnostic_summaries(include_ignored, cx)
 7691                .filter(|(path, _, _)| {
 7692                    let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
 7693                    include_ignored || worktree == Some(false)
 7694                })
 7695        {
 7696            summary.error_count += path_summary.error_count;
 7697            summary.warning_count += path_summary.warning_count;
 7698        }
 7699        summary
 7700    }
 7701
 7702    pub fn diagnostic_summaries<'a>(
 7703        &'a self,
 7704        include_ignored: bool,
 7705        cx: &'a AppContext,
 7706    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
 7707        self.visible_worktrees(cx)
 7708            .flat_map(move |worktree| {
 7709                let worktree = worktree.read(cx);
 7710                let worktree_id = worktree.id();
 7711                worktree
 7712                    .diagnostic_summaries()
 7713                    .map(move |(path, server_id, summary)| {
 7714                        (ProjectPath { worktree_id, path }, server_id, summary)
 7715                    })
 7716            })
 7717            .filter(move |(path, _, _)| {
 7718                let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
 7719                include_ignored || worktree == Some(false)
 7720            })
 7721    }
 7722
 7723    pub fn disk_based_diagnostics_started(
 7724        &mut self,
 7725        language_server_id: LanguageServerId,
 7726        cx: &mut ModelContext<Self>,
 7727    ) {
 7728        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
 7729    }
 7730
 7731    pub fn disk_based_diagnostics_finished(
 7732        &mut self,
 7733        language_server_id: LanguageServerId,
 7734        cx: &mut ModelContext<Self>,
 7735    ) {
 7736        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
 7737    }
 7738
 7739    pub fn active_entry(&self) -> Option<ProjectEntryId> {
 7740        self.active_entry
 7741    }
 7742
 7743    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
 7744        self.worktree_for_id(path.worktree_id, cx)?
 7745            .read(cx)
 7746            .entry_for_path(&path.path)
 7747            .cloned()
 7748    }
 7749
 7750    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
 7751        let worktree = self.worktree_for_entry(entry_id, cx)?;
 7752        let worktree = worktree.read(cx);
 7753        let worktree_id = worktree.id();
 7754        let path = worktree.entry_for_id(entry_id)?.path.clone();
 7755        Some(ProjectPath { worktree_id, path })
 7756    }
 7757
 7758    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
 7759        let workspace_root = self
 7760            .worktree_for_id(project_path.worktree_id, cx)?
 7761            .read(cx)
 7762            .abs_path();
 7763        let project_path = project_path.path.as_ref();
 7764
 7765        Some(if project_path == Path::new("") {
 7766            workspace_root.to_path_buf()
 7767        } else {
 7768            workspace_root.join(project_path)
 7769        })
 7770    }
 7771
 7772    pub fn get_workspace_root(
 7773        &self,
 7774        project_path: &ProjectPath,
 7775        cx: &AppContext,
 7776    ) -> Option<PathBuf> {
 7777        Some(
 7778            self.worktree_for_id(project_path.worktree_id, cx)?
 7779                .read(cx)
 7780                .abs_path()
 7781                .to_path_buf(),
 7782        )
 7783    }
 7784
 7785    pub fn get_repo(
 7786        &self,
 7787        project_path: &ProjectPath,
 7788        cx: &AppContext,
 7789    ) -> Option<Arc<Mutex<dyn GitRepository>>> {
 7790        self.worktree_for_id(project_path.worktree_id, cx)?
 7791            .read(cx)
 7792            .as_local()?
 7793            .snapshot()
 7794            .local_git_repo(&project_path.path)
 7795    }
 7796
 7797    pub fn blame_buffer(
 7798        &self,
 7799        buffer: &Model<Buffer>,
 7800        version: Option<clock::Global>,
 7801        cx: &AppContext,
 7802    ) -> Task<Result<Blame>> {
 7803        if self.is_local() {
 7804            let blame_params = maybe!({
 7805                let buffer = buffer.read(cx);
 7806                let buffer_project_path = buffer
 7807                    .project_path(cx)
 7808                    .context("failed to get buffer project path")?;
 7809
 7810                let worktree = self
 7811                    .worktree_for_id(buffer_project_path.worktree_id, cx)
 7812                    .context("failed to get worktree")?
 7813                    .read(cx)
 7814                    .as_local()
 7815                    .context("worktree was not local")?
 7816                    .snapshot();
 7817
 7818                let (work_directory, repo) = match worktree
 7819                    .repository_and_work_directory_for_path(&buffer_project_path.path)
 7820                {
 7821                    Some(work_dir_repo) => work_dir_repo,
 7822                    None => anyhow::bail!(NoRepositoryError {}),
 7823                };
 7824
 7825                let repo_entry = match worktree.get_local_repo(&repo) {
 7826                    Some(repo_entry) => repo_entry,
 7827                    None => anyhow::bail!(NoRepositoryError {}),
 7828                };
 7829
 7830                let repo = repo_entry.repo().clone();
 7831
 7832                let relative_path = buffer_project_path
 7833                    .path
 7834                    .strip_prefix(&work_directory)?
 7835                    .to_path_buf();
 7836
 7837                let content = match version {
 7838                    Some(version) => buffer.rope_for_version(&version).clone(),
 7839                    None => buffer.as_rope().clone(),
 7840                };
 7841
 7842                anyhow::Ok((repo, relative_path, content))
 7843            });
 7844
 7845            cx.background_executor().spawn(async move {
 7846                let (repo, relative_path, content) = blame_params?;
 7847                let lock = repo.lock();
 7848                lock.blame(&relative_path, content)
 7849                    .with_context(|| format!("Failed to blame {relative_path:?}"))
 7850            })
 7851        } else {
 7852            let project_id = self.remote_id();
 7853            let buffer_id = buffer.read(cx).remote_id();
 7854            let client = self.client.clone();
 7855            let version = buffer.read(cx).version();
 7856
 7857            cx.spawn(|_| async move {
 7858                let project_id = project_id.context("unable to get project id for buffer")?;
 7859                let response = client
 7860                    .request(proto::BlameBuffer {
 7861                        project_id,
 7862                        buffer_id: buffer_id.into(),
 7863                        version: serialize_version(&version),
 7864                    })
 7865                    .await?;
 7866
 7867                Ok(deserialize_blame_buffer_response(response))
 7868            })
 7869        }
 7870    }
 7871
 7872    // RPC message handlers
 7873
 7874    async fn handle_blame_buffer(
 7875        this: Model<Self>,
 7876        envelope: TypedEnvelope<proto::BlameBuffer>,
 7877        _: Arc<Client>,
 7878        mut cx: AsyncAppContext,
 7879    ) -> Result<proto::BlameBufferResponse> {
 7880        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 7881        let version = deserialize_version(&envelope.payload.version);
 7882
 7883        let buffer = this.update(&mut cx, |this, _cx| {
 7884            this.opened_buffers
 7885                .get(&buffer_id)
 7886                .and_then(|buffer| buffer.upgrade())
 7887                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 7888        })??;
 7889
 7890        buffer
 7891            .update(&mut cx, |buffer, _| {
 7892                buffer.wait_for_version(version.clone())
 7893            })?
 7894            .await?;
 7895
 7896        let blame = this
 7897            .update(&mut cx, |this, cx| {
 7898                this.blame_buffer(&buffer, Some(version), cx)
 7899            })?
 7900            .await?;
 7901
 7902        Ok(serialize_blame_buffer_response(blame))
 7903    }
 7904
 7905    async fn handle_multi_lsp_query(
 7906        project: Model<Self>,
 7907        envelope: TypedEnvelope<proto::MultiLspQuery>,
 7908        _: Arc<Client>,
 7909        mut cx: AsyncAppContext,
 7910    ) -> Result<proto::MultiLspQueryResponse> {
 7911        let sender_id = envelope.original_sender_id()?;
 7912        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 7913        let version = deserialize_version(&envelope.payload.version);
 7914        let buffer = project.update(&mut cx, |project, _cx| {
 7915            project
 7916                .opened_buffers
 7917                .get(&buffer_id)
 7918                .and_then(|buffer| buffer.upgrade())
 7919                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 7920        })??;
 7921        buffer
 7922            .update(&mut cx, |buffer, _| {
 7923                buffer.wait_for_version(version.clone())
 7924            })?
 7925            .await?;
 7926        let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
 7927        match envelope
 7928            .payload
 7929            .strategy
 7930            .context("invalid request without the strategy")?
 7931        {
 7932            proto::multi_lsp_query::Strategy::All(_) => {
 7933                // currently, there's only one multiple language servers query strategy,
 7934                // so just ensure it's specified correctly
 7935            }
 7936        }
 7937        match envelope.payload.request {
 7938            Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
 7939                let get_hover =
 7940                    GetHover::from_proto(get_hover, project.clone(), buffer.clone(), cx.clone())
 7941                        .await?;
 7942                let all_hovers = project
 7943                    .update(&mut cx, |project, cx| {
 7944                        project.request_multiple_lsp_locally(
 7945                            &buffer,
 7946                            Some(get_hover.position),
 7947                            |server_capabilities| match server_capabilities.hover_provider {
 7948                                Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 7949                                Some(lsp::HoverProviderCapability::Options(_)) => true,
 7950                                None => false,
 7951                            },
 7952                            get_hover,
 7953                            cx,
 7954                        )
 7955                    })?
 7956                    .await
 7957                    .into_iter()
 7958                    .filter_map(|hover| remove_empty_hover_blocks(hover?));
 7959                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 7960                    responses: all_hovers
 7961                        .map(|hover| proto::LspResponse {
 7962                            response: Some(proto::lsp_response::Response::GetHoverResponse(
 7963                                GetHover::response_to_proto(
 7964                                    Some(hover),
 7965                                    project,
 7966                                    sender_id,
 7967                                    &buffer_version,
 7968                                    cx,
 7969                                ),
 7970                            )),
 7971                        })
 7972                        .collect(),
 7973                })
 7974            }
 7975            Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
 7976                let get_code_actions = GetCodeActions::from_proto(
 7977                    get_code_actions,
 7978                    project.clone(),
 7979                    buffer.clone(),
 7980                    cx.clone(),
 7981                )
 7982                .await?;
 7983
 7984                let all_actions = project
 7985                    .update(&mut cx, |project, cx| {
 7986                        project.request_multiple_lsp_locally(
 7987                            &buffer,
 7988                            Some(get_code_actions.range.start),
 7989                            GetCodeActions::supports_code_actions,
 7990                            get_code_actions,
 7991                            cx,
 7992                        )
 7993                    })?
 7994                    .await
 7995                    .into_iter();
 7996
 7997                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 7998                    responses: all_actions
 7999                        .map(|code_actions| proto::LspResponse {
 8000                            response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
 8001                                GetCodeActions::response_to_proto(
 8002                                    code_actions,
 8003                                    project,
 8004                                    sender_id,
 8005                                    &buffer_version,
 8006                                    cx,
 8007                                ),
 8008                            )),
 8009                        })
 8010                        .collect(),
 8011                })
 8012            }
 8013            None => anyhow::bail!("empty multi lsp query request"),
 8014        }
 8015    }
 8016
 8017    async fn handle_unshare_project(
 8018        this: Model<Self>,
 8019        _: TypedEnvelope<proto::UnshareProject>,
 8020        _: Arc<Client>,
 8021        mut cx: AsyncAppContext,
 8022    ) -> Result<()> {
 8023        this.update(&mut cx, |this, cx| {
 8024            if this.is_local() {
 8025                this.unshare(cx)?;
 8026            } else {
 8027                this.disconnected_from_host(cx);
 8028            }
 8029            Ok(())
 8030        })?
 8031    }
 8032
 8033    async fn handle_add_collaborator(
 8034        this: Model<Self>,
 8035        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
 8036        _: Arc<Client>,
 8037        mut cx: AsyncAppContext,
 8038    ) -> Result<()> {
 8039        let collaborator = envelope
 8040            .payload
 8041            .collaborator
 8042            .take()
 8043            .ok_or_else(|| anyhow!("empty collaborator"))?;
 8044
 8045        let collaborator = Collaborator::from_proto(collaborator)?;
 8046        this.update(&mut cx, |this, cx| {
 8047            this.shared_buffers.remove(&collaborator.peer_id);
 8048            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
 8049            this.collaborators
 8050                .insert(collaborator.peer_id, collaborator);
 8051            cx.notify();
 8052        })?;
 8053
 8054        Ok(())
 8055    }
 8056
 8057    async fn handle_update_project_collaborator(
 8058        this: Model<Self>,
 8059        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
 8060        _: Arc<Client>,
 8061        mut cx: AsyncAppContext,
 8062    ) -> Result<()> {
 8063        let old_peer_id = envelope
 8064            .payload
 8065            .old_peer_id
 8066            .ok_or_else(|| anyhow!("missing old peer id"))?;
 8067        let new_peer_id = envelope
 8068            .payload
 8069            .new_peer_id
 8070            .ok_or_else(|| anyhow!("missing new peer id"))?;
 8071        this.update(&mut cx, |this, cx| {
 8072            let collaborator = this
 8073                .collaborators
 8074                .remove(&old_peer_id)
 8075                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
 8076            let is_host = collaborator.replica_id == 0;
 8077            this.collaborators.insert(new_peer_id, collaborator);
 8078
 8079            let buffers = this.shared_buffers.remove(&old_peer_id);
 8080            log::info!(
 8081                "peer {} became {}. moving buffers {:?}",
 8082                old_peer_id,
 8083                new_peer_id,
 8084                &buffers
 8085            );
 8086            if let Some(buffers) = buffers {
 8087                this.shared_buffers.insert(new_peer_id, buffers);
 8088            }
 8089
 8090            if is_host {
 8091                this.opened_buffers
 8092                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
 8093                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 8094                    .unwrap();
 8095            }
 8096
 8097            cx.emit(Event::CollaboratorUpdated {
 8098                old_peer_id,
 8099                new_peer_id,
 8100            });
 8101            cx.notify();
 8102            Ok(())
 8103        })?
 8104    }
 8105
 8106    async fn handle_remove_collaborator(
 8107        this: Model<Self>,
 8108        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
 8109        _: Arc<Client>,
 8110        mut cx: AsyncAppContext,
 8111    ) -> Result<()> {
 8112        this.update(&mut cx, |this, cx| {
 8113            let peer_id = envelope
 8114                .payload
 8115                .peer_id
 8116                .ok_or_else(|| anyhow!("invalid peer id"))?;
 8117            let replica_id = this
 8118                .collaborators
 8119                .remove(&peer_id)
 8120                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
 8121                .replica_id;
 8122            for buffer in this.opened_buffers.values() {
 8123                if let Some(buffer) = buffer.upgrade() {
 8124                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
 8125                }
 8126            }
 8127            this.shared_buffers.remove(&peer_id);
 8128
 8129            cx.emit(Event::CollaboratorLeft(peer_id));
 8130            cx.notify();
 8131            Ok(())
 8132        })?
 8133    }
 8134
 8135    async fn handle_update_project(
 8136        this: Model<Self>,
 8137        envelope: TypedEnvelope<proto::UpdateProject>,
 8138        _: Arc<Client>,
 8139        mut cx: AsyncAppContext,
 8140    ) -> Result<()> {
 8141        this.update(&mut cx, |this, cx| {
 8142            // Don't handle messages that were sent before the response to us joining the project
 8143            if envelope.message_id > this.join_project_response_message_id {
 8144                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
 8145            }
 8146            Ok(())
 8147        })?
 8148    }
 8149
 8150    async fn handle_update_worktree(
 8151        this: Model<Self>,
 8152        envelope: TypedEnvelope<proto::UpdateWorktree>,
 8153        _: Arc<Client>,
 8154        mut cx: AsyncAppContext,
 8155    ) -> Result<()> {
 8156        this.update(&mut cx, |this, cx| {
 8157            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8158            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8159                worktree.update(cx, |worktree, _| {
 8160                    let worktree = worktree.as_remote_mut().unwrap();
 8161                    worktree.update_from_remote(envelope.payload);
 8162                });
 8163            }
 8164            Ok(())
 8165        })?
 8166    }
 8167
 8168    async fn handle_update_worktree_settings(
 8169        this: Model<Self>,
 8170        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
 8171        _: Arc<Client>,
 8172        mut cx: AsyncAppContext,
 8173    ) -> Result<()> {
 8174        this.update(&mut cx, |this, cx| {
 8175            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8176            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8177                cx.update_global::<SettingsStore, _>(|store, cx| {
 8178                    store
 8179                        .set_local_settings(
 8180                            worktree.entity_id().as_u64() as usize,
 8181                            PathBuf::from(&envelope.payload.path).into(),
 8182                            envelope.payload.content.as_deref(),
 8183                            cx,
 8184                        )
 8185                        .log_err();
 8186                });
 8187            }
 8188            Ok(())
 8189        })?
 8190    }
 8191
 8192    async fn handle_create_project_entry(
 8193        this: Model<Self>,
 8194        envelope: TypedEnvelope<proto::CreateProjectEntry>,
 8195        _: Arc<Client>,
 8196        mut cx: AsyncAppContext,
 8197    ) -> Result<proto::ProjectEntryResponse> {
 8198        let worktree = this.update(&mut cx, |this, cx| {
 8199            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8200            this.worktree_for_id(worktree_id, cx)
 8201                .ok_or_else(|| anyhow!("worktree not found"))
 8202        })??;
 8203        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8204        let entry = worktree
 8205            .update(&mut cx, |worktree, cx| {
 8206                let worktree = worktree.as_local_mut().unwrap();
 8207                let path = PathBuf::from(envelope.payload.path);
 8208                worktree.create_entry(path, envelope.payload.is_directory, cx)
 8209            })?
 8210            .await?;
 8211        Ok(proto::ProjectEntryResponse {
 8212            entry: entry.as_ref().map(|e| e.into()),
 8213            worktree_scan_id: worktree_scan_id as u64,
 8214        })
 8215    }
 8216
 8217    async fn handle_rename_project_entry(
 8218        this: Model<Self>,
 8219        envelope: TypedEnvelope<proto::RenameProjectEntry>,
 8220        _: Arc<Client>,
 8221        mut cx: AsyncAppContext,
 8222    ) -> Result<proto::ProjectEntryResponse> {
 8223        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8224        let worktree = this.update(&mut cx, |this, cx| {
 8225            this.worktree_for_entry(entry_id, cx)
 8226                .ok_or_else(|| anyhow!("worktree not found"))
 8227        })??;
 8228        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8229        let entry = worktree
 8230            .update(&mut cx, |worktree, cx| {
 8231                let new_path = PathBuf::from(envelope.payload.new_path);
 8232                worktree
 8233                    .as_local_mut()
 8234                    .unwrap()
 8235                    .rename_entry(entry_id, new_path, cx)
 8236            })?
 8237            .await?;
 8238        Ok(proto::ProjectEntryResponse {
 8239            entry: entry.as_ref().map(|e| e.into()),
 8240            worktree_scan_id: worktree_scan_id as u64,
 8241        })
 8242    }
 8243
 8244    async fn handle_copy_project_entry(
 8245        this: Model<Self>,
 8246        envelope: TypedEnvelope<proto::CopyProjectEntry>,
 8247        _: Arc<Client>,
 8248        mut cx: AsyncAppContext,
 8249    ) -> Result<proto::ProjectEntryResponse> {
 8250        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8251        let worktree = this.update(&mut cx, |this, cx| {
 8252            this.worktree_for_entry(entry_id, cx)
 8253                .ok_or_else(|| anyhow!("worktree not found"))
 8254        })??;
 8255        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8256        let entry = worktree
 8257            .update(&mut cx, |worktree, cx| {
 8258                let new_path = PathBuf::from(envelope.payload.new_path);
 8259                worktree
 8260                    .as_local_mut()
 8261                    .unwrap()
 8262                    .copy_entry(entry_id, new_path, cx)
 8263            })?
 8264            .await?;
 8265        Ok(proto::ProjectEntryResponse {
 8266            entry: entry.as_ref().map(|e| e.into()),
 8267            worktree_scan_id: worktree_scan_id as u64,
 8268        })
 8269    }
 8270
 8271    async fn handle_delete_project_entry(
 8272        this: Model<Self>,
 8273        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
 8274        _: Arc<Client>,
 8275        mut cx: AsyncAppContext,
 8276    ) -> Result<proto::ProjectEntryResponse> {
 8277        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8278
 8279        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
 8280
 8281        let worktree = this.update(&mut cx, |this, cx| {
 8282            this.worktree_for_entry(entry_id, cx)
 8283                .ok_or_else(|| anyhow!("worktree not found"))
 8284        })??;
 8285        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8286        worktree
 8287            .update(&mut cx, |worktree, cx| {
 8288                worktree
 8289                    .as_local_mut()
 8290                    .unwrap()
 8291                    .delete_entry(entry_id, cx)
 8292                    .ok_or_else(|| anyhow!("invalid entry"))
 8293            })??
 8294            .await?;
 8295        Ok(proto::ProjectEntryResponse {
 8296            entry: None,
 8297            worktree_scan_id: worktree_scan_id as u64,
 8298        })
 8299    }
 8300
 8301    async fn handle_expand_project_entry(
 8302        this: Model<Self>,
 8303        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
 8304        _: Arc<Client>,
 8305        mut cx: AsyncAppContext,
 8306    ) -> Result<proto::ExpandProjectEntryResponse> {
 8307        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8308        let worktree = this
 8309            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
 8310            .ok_or_else(|| anyhow!("invalid request"))?;
 8311        worktree
 8312            .update(&mut cx, |worktree, cx| {
 8313                worktree
 8314                    .as_local_mut()
 8315                    .unwrap()
 8316                    .expand_entry(entry_id, cx)
 8317                    .ok_or_else(|| anyhow!("invalid entry"))
 8318            })??
 8319            .await?;
 8320        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
 8321        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
 8322    }
 8323
 8324    async fn handle_update_diagnostic_summary(
 8325        this: Model<Self>,
 8326        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 8327        _: Arc<Client>,
 8328        mut cx: AsyncAppContext,
 8329    ) -> Result<()> {
 8330        this.update(&mut cx, |this, cx| {
 8331            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8332            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8333                if let Some(summary) = envelope.payload.summary {
 8334                    let project_path = ProjectPath {
 8335                        worktree_id,
 8336                        path: Path::new(&summary.path).into(),
 8337                    };
 8338                    worktree.update(cx, |worktree, _| {
 8339                        worktree
 8340                            .as_remote_mut()
 8341                            .unwrap()
 8342                            .update_diagnostic_summary(project_path.path.clone(), &summary);
 8343                    });
 8344                    cx.emit(Event::DiagnosticsUpdated {
 8345                        language_server_id: LanguageServerId(summary.language_server_id as usize),
 8346                        path: project_path,
 8347                    });
 8348                }
 8349            }
 8350            Ok(())
 8351        })?
 8352    }
 8353
 8354    async fn handle_start_language_server(
 8355        this: Model<Self>,
 8356        envelope: TypedEnvelope<proto::StartLanguageServer>,
 8357        _: Arc<Client>,
 8358        mut cx: AsyncAppContext,
 8359    ) -> Result<()> {
 8360        let server = envelope
 8361            .payload
 8362            .server
 8363            .ok_or_else(|| anyhow!("invalid server"))?;
 8364        this.update(&mut cx, |this, cx| {
 8365            this.language_server_statuses.insert(
 8366                LanguageServerId(server.id as usize),
 8367                LanguageServerStatus {
 8368                    name: server.name,
 8369                    pending_work: Default::default(),
 8370                    has_pending_diagnostic_updates: false,
 8371                    progress_tokens: Default::default(),
 8372                },
 8373            );
 8374            cx.notify();
 8375        })?;
 8376        Ok(())
 8377    }
 8378
 8379    async fn handle_update_language_server(
 8380        this: Model<Self>,
 8381        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
 8382        _: Arc<Client>,
 8383        mut cx: AsyncAppContext,
 8384    ) -> Result<()> {
 8385        this.update(&mut cx, |this, cx| {
 8386            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8387
 8388            match envelope
 8389                .payload
 8390                .variant
 8391                .ok_or_else(|| anyhow!("invalid variant"))?
 8392            {
 8393                proto::update_language_server::Variant::WorkStart(payload) => {
 8394                    this.on_lsp_work_start(
 8395                        language_server_id,
 8396                        payload.token,
 8397                        LanguageServerProgress {
 8398                            message: payload.message,
 8399                            percentage: payload.percentage.map(|p| p as usize),
 8400                            last_update_at: Instant::now(),
 8401                        },
 8402                        cx,
 8403                    );
 8404                }
 8405
 8406                proto::update_language_server::Variant::WorkProgress(payload) => {
 8407                    this.on_lsp_work_progress(
 8408                        language_server_id,
 8409                        payload.token,
 8410                        LanguageServerProgress {
 8411                            message: payload.message,
 8412                            percentage: payload.percentage.map(|p| p as usize),
 8413                            last_update_at: Instant::now(),
 8414                        },
 8415                        cx,
 8416                    );
 8417                }
 8418
 8419                proto::update_language_server::Variant::WorkEnd(payload) => {
 8420                    this.on_lsp_work_end(language_server_id, payload.token, cx);
 8421                }
 8422
 8423                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
 8424                    this.disk_based_diagnostics_started(language_server_id, cx);
 8425                }
 8426
 8427                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
 8428                    this.disk_based_diagnostics_finished(language_server_id, cx)
 8429                }
 8430            }
 8431
 8432            Ok(())
 8433        })?
 8434    }
 8435
 8436    async fn handle_update_buffer(
 8437        this: Model<Self>,
 8438        envelope: TypedEnvelope<proto::UpdateBuffer>,
 8439        _: Arc<Client>,
 8440        mut cx: AsyncAppContext,
 8441    ) -> Result<proto::Ack> {
 8442        this.update(&mut cx, |this, cx| {
 8443            let payload = envelope.payload.clone();
 8444            let buffer_id = BufferId::new(payload.buffer_id)?;
 8445            let ops = payload
 8446                .operations
 8447                .into_iter()
 8448                .map(language::proto::deserialize_operation)
 8449                .collect::<Result<Vec<_>, _>>()?;
 8450            let is_remote = this.is_remote();
 8451            match this.opened_buffers.entry(buffer_id) {
 8452                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
 8453                    OpenBuffer::Strong(buffer) => {
 8454                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
 8455                    }
 8456                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
 8457                    OpenBuffer::Weak(_) => {}
 8458                },
 8459                hash_map::Entry::Vacant(e) => {
 8460                    if !is_remote {
 8461                        debug_panic!(
 8462                            "received buffer update from {:?}",
 8463                            envelope.original_sender_id
 8464                        );
 8465                        return Err(anyhow!("received buffer update for non-remote project"));
 8466                    }
 8467                    e.insert(OpenBuffer::Operations(ops));
 8468                }
 8469            }
 8470            Ok(proto::Ack {})
 8471        })?
 8472    }
 8473
 8474    async fn handle_create_buffer_for_peer(
 8475        this: Model<Self>,
 8476        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 8477        _: Arc<Client>,
 8478        mut cx: AsyncAppContext,
 8479    ) -> Result<()> {
 8480        this.update(&mut cx, |this, cx| {
 8481            match envelope
 8482                .payload
 8483                .variant
 8484                .ok_or_else(|| anyhow!("missing variant"))?
 8485            {
 8486                proto::create_buffer_for_peer::Variant::State(mut state) => {
 8487                    let buffer_id = BufferId::new(state.id)?;
 8488
 8489                    let buffer_result = maybe!({
 8490                        let mut buffer_file = None;
 8491                        if let Some(file) = state.file.take() {
 8492                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
 8493                            let worktree =
 8494                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
 8495                                    anyhow!("no worktree found for id {}", file.worktree_id)
 8496                                })?;
 8497                            buffer_file =
 8498                                Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
 8499                                    as Arc<dyn language::File>);
 8500                        }
 8501                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
 8502                    });
 8503
 8504                    match buffer_result {
 8505                        Ok(buffer) => {
 8506                            let buffer = cx.new_model(|_| buffer);
 8507                            this.incomplete_remote_buffers.insert(buffer_id, buffer);
 8508                        }
 8509                        Err(error) => {
 8510                            if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 8511                                for listener in listeners {
 8512                                    listener.send(Err(anyhow!(error.cloned()))).ok();
 8513                                }
 8514                            }
 8515                        }
 8516                    };
 8517                }
 8518                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
 8519                    let buffer_id = BufferId::new(chunk.buffer_id)?;
 8520                    let buffer = this
 8521                        .incomplete_remote_buffers
 8522                        .get(&buffer_id)
 8523                        .cloned()
 8524                        .ok_or_else(|| {
 8525                            anyhow!(
 8526                                "received chunk for buffer {} without initial state",
 8527                                chunk.buffer_id
 8528                            )
 8529                        })?;
 8530
 8531                    let result = maybe!({
 8532                        let operations = chunk
 8533                            .operations
 8534                            .into_iter()
 8535                            .map(language::proto::deserialize_operation)
 8536                            .collect::<Result<Vec<_>>>()?;
 8537                        buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))
 8538                    });
 8539
 8540                    if let Err(error) = result {
 8541                        this.incomplete_remote_buffers.remove(&buffer_id);
 8542                        if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 8543                            for listener in listeners {
 8544                                listener.send(Err(error.cloned())).ok();
 8545                            }
 8546                        }
 8547                    } else {
 8548                        if chunk.is_last {
 8549                            this.incomplete_remote_buffers.remove(&buffer_id);
 8550                            this.register_buffer(&buffer, cx)?;
 8551                        }
 8552                    }
 8553                }
 8554            }
 8555
 8556            Ok(())
 8557        })?
 8558    }
 8559
 8560    async fn handle_update_diff_base(
 8561        this: Model<Self>,
 8562        envelope: TypedEnvelope<proto::UpdateDiffBase>,
 8563        _: Arc<Client>,
 8564        mut cx: AsyncAppContext,
 8565    ) -> Result<()> {
 8566        this.update(&mut cx, |this, cx| {
 8567            let buffer_id = envelope.payload.buffer_id;
 8568            let buffer_id = BufferId::new(buffer_id)?;
 8569            let diff_base = envelope.payload.diff_base;
 8570            if let Some(buffer) = this
 8571                .opened_buffers
 8572                .get_mut(&buffer_id)
 8573                .and_then(|b| b.upgrade())
 8574                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 8575            {
 8576                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
 8577            }
 8578            Ok(())
 8579        })?
 8580    }
 8581
 8582    async fn handle_update_buffer_file(
 8583        this: Model<Self>,
 8584        envelope: TypedEnvelope<proto::UpdateBufferFile>,
 8585        _: Arc<Client>,
 8586        mut cx: AsyncAppContext,
 8587    ) -> Result<()> {
 8588        let buffer_id = envelope.payload.buffer_id;
 8589        let buffer_id = BufferId::new(buffer_id)?;
 8590
 8591        this.update(&mut cx, |this, cx| {
 8592            let payload = envelope.payload.clone();
 8593            if let Some(buffer) = this
 8594                .opened_buffers
 8595                .get(&buffer_id)
 8596                .and_then(|b| b.upgrade())
 8597                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 8598            {
 8599                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
 8600                let worktree = this
 8601                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
 8602                    .ok_or_else(|| anyhow!("no such worktree"))?;
 8603                let file = File::from_proto(file, worktree, cx)?;
 8604                buffer.update(cx, |buffer, cx| {
 8605                    buffer.file_updated(Arc::new(file), cx);
 8606                });
 8607                this.detect_language_for_buffer(&buffer, cx);
 8608            }
 8609            Ok(())
 8610        })?
 8611    }
 8612
 8613    async fn handle_save_buffer(
 8614        this: Model<Self>,
 8615        envelope: TypedEnvelope<proto::SaveBuffer>,
 8616        _: Arc<Client>,
 8617        mut cx: AsyncAppContext,
 8618    ) -> Result<proto::BufferSaved> {
 8619        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8620        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
 8621            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
 8622            let buffer = this
 8623                .opened_buffers
 8624                .get(&buffer_id)
 8625                .and_then(|buffer| buffer.upgrade())
 8626                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 8627            anyhow::Ok((project_id, buffer))
 8628        })??;
 8629        buffer
 8630            .update(&mut cx, |buffer, _| {
 8631                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 8632            })?
 8633            .await?;
 8634        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
 8635
 8636        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
 8637            .await?;
 8638        buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
 8639            project_id,
 8640            buffer_id: buffer_id.into(),
 8641            version: serialize_version(buffer.saved_version()),
 8642            mtime: buffer.saved_mtime().map(|time| time.into()),
 8643        })
 8644    }
 8645
 8646    async fn handle_reload_buffers(
 8647        this: Model<Self>,
 8648        envelope: TypedEnvelope<proto::ReloadBuffers>,
 8649        _: Arc<Client>,
 8650        mut cx: AsyncAppContext,
 8651    ) -> Result<proto::ReloadBuffersResponse> {
 8652        let sender_id = envelope.original_sender_id()?;
 8653        let reload = this.update(&mut cx, |this, cx| {
 8654            let mut buffers = HashSet::default();
 8655            for buffer_id in &envelope.payload.buffer_ids {
 8656                let buffer_id = BufferId::new(*buffer_id)?;
 8657                buffers.insert(
 8658                    this.opened_buffers
 8659                        .get(&buffer_id)
 8660                        .and_then(|buffer| buffer.upgrade())
 8661                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 8662                );
 8663            }
 8664            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
 8665        })??;
 8666
 8667        let project_transaction = reload.await?;
 8668        let project_transaction = this.update(&mut cx, |this, cx| {
 8669            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8670        })?;
 8671        Ok(proto::ReloadBuffersResponse {
 8672            transaction: Some(project_transaction),
 8673        })
 8674    }
 8675
 8676    async fn handle_synchronize_buffers(
 8677        this: Model<Self>,
 8678        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
 8679        _: Arc<Client>,
 8680        mut cx: AsyncAppContext,
 8681    ) -> Result<proto::SynchronizeBuffersResponse> {
 8682        let project_id = envelope.payload.project_id;
 8683        let mut response = proto::SynchronizeBuffersResponse {
 8684            buffers: Default::default(),
 8685        };
 8686
 8687        this.update(&mut cx, |this, cx| {
 8688            let Some(guest_id) = envelope.original_sender_id else {
 8689                error!("missing original_sender_id on SynchronizeBuffers request");
 8690                bail!("missing original_sender_id on SynchronizeBuffers request");
 8691            };
 8692
 8693            this.shared_buffers.entry(guest_id).or_default().clear();
 8694            for buffer in envelope.payload.buffers {
 8695                let buffer_id = BufferId::new(buffer.id)?;
 8696                let remote_version = language::proto::deserialize_version(&buffer.version);
 8697                if let Some(buffer) = this.buffer_for_id(buffer_id) {
 8698                    this.shared_buffers
 8699                        .entry(guest_id)
 8700                        .or_default()
 8701                        .insert(buffer_id);
 8702
 8703                    let buffer = buffer.read(cx);
 8704                    response.buffers.push(proto::BufferVersion {
 8705                        id: buffer_id.into(),
 8706                        version: language::proto::serialize_version(&buffer.version),
 8707                    });
 8708
 8709                    let operations = buffer.serialize_ops(Some(remote_version), cx);
 8710                    let client = this.client.clone();
 8711                    if let Some(file) = buffer.file() {
 8712                        client
 8713                            .send(proto::UpdateBufferFile {
 8714                                project_id,
 8715                                buffer_id: buffer_id.into(),
 8716                                file: Some(file.to_proto()),
 8717                            })
 8718                            .log_err();
 8719                    }
 8720
 8721                    client
 8722                        .send(proto::UpdateDiffBase {
 8723                            project_id,
 8724                            buffer_id: buffer_id.into(),
 8725                            diff_base: buffer.diff_base().map(Into::into),
 8726                        })
 8727                        .log_err();
 8728
 8729                    client
 8730                        .send(proto::BufferReloaded {
 8731                            project_id,
 8732                            buffer_id: buffer_id.into(),
 8733                            version: language::proto::serialize_version(buffer.saved_version()),
 8734                            mtime: buffer.saved_mtime().map(|time| time.into()),
 8735                            line_ending: language::proto::serialize_line_ending(
 8736                                buffer.line_ending(),
 8737                            ) as i32,
 8738                        })
 8739                        .log_err();
 8740
 8741                    cx.background_executor()
 8742                        .spawn(
 8743                            async move {
 8744                                let operations = operations.await;
 8745                                for chunk in split_operations(operations) {
 8746                                    client
 8747                                        .request(proto::UpdateBuffer {
 8748                                            project_id,
 8749                                            buffer_id: buffer_id.into(),
 8750                                            operations: chunk,
 8751                                        })
 8752                                        .await?;
 8753                                }
 8754                                anyhow::Ok(())
 8755                            }
 8756                            .log_err(),
 8757                        )
 8758                        .detach();
 8759                }
 8760            }
 8761            Ok(())
 8762        })??;
 8763
 8764        Ok(response)
 8765    }
 8766
 8767    async fn handle_format_buffers(
 8768        this: Model<Self>,
 8769        envelope: TypedEnvelope<proto::FormatBuffers>,
 8770        _: Arc<Client>,
 8771        mut cx: AsyncAppContext,
 8772    ) -> Result<proto::FormatBuffersResponse> {
 8773        let sender_id = envelope.original_sender_id()?;
 8774        let format = this.update(&mut cx, |this, cx| {
 8775            let mut buffers = HashSet::default();
 8776            for buffer_id in &envelope.payload.buffer_ids {
 8777                let buffer_id = BufferId::new(*buffer_id)?;
 8778                buffers.insert(
 8779                    this.opened_buffers
 8780                        .get(&buffer_id)
 8781                        .and_then(|buffer| buffer.upgrade())
 8782                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 8783                );
 8784            }
 8785            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
 8786            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
 8787        })??;
 8788
 8789        let project_transaction = format.await?;
 8790        let project_transaction = this.update(&mut cx, |this, cx| {
 8791            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8792        })?;
 8793        Ok(proto::FormatBuffersResponse {
 8794            transaction: Some(project_transaction),
 8795        })
 8796    }
 8797
 8798    async fn handle_apply_additional_edits_for_completion(
 8799        this: Model<Self>,
 8800        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 8801        _: Arc<Client>,
 8802        mut cx: AsyncAppContext,
 8803    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
 8804        let (buffer, completion) = this.update(&mut cx, |this, _| {
 8805            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8806            let buffer = this
 8807                .opened_buffers
 8808                .get(&buffer_id)
 8809                .and_then(|buffer| buffer.upgrade())
 8810                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 8811            let completion = Self::deserialize_completion(
 8812                envelope
 8813                    .payload
 8814                    .completion
 8815                    .ok_or_else(|| anyhow!("invalid completion"))?,
 8816            )?;
 8817            anyhow::Ok((buffer, completion))
 8818        })??;
 8819
 8820        let apply_additional_edits = this.update(&mut cx, |this, cx| {
 8821            this.apply_additional_edits_for_completion(
 8822                buffer,
 8823                Completion {
 8824                    old_range: completion.old_range,
 8825                    new_text: completion.new_text,
 8826                    lsp_completion: completion.lsp_completion,
 8827                    server_id: completion.server_id,
 8828                    documentation: None,
 8829                    label: CodeLabel {
 8830                        text: Default::default(),
 8831                        runs: Default::default(),
 8832                        filter_range: Default::default(),
 8833                    },
 8834                },
 8835                false,
 8836                cx,
 8837            )
 8838        })?;
 8839
 8840        Ok(proto::ApplyCompletionAdditionalEditsResponse {
 8841            transaction: apply_additional_edits
 8842                .await?
 8843                .as_ref()
 8844                .map(language::proto::serialize_transaction),
 8845        })
 8846    }
 8847
 8848    async fn handle_resolve_completion_documentation(
 8849        this: Model<Self>,
 8850        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
 8851        _: Arc<Client>,
 8852        mut cx: AsyncAppContext,
 8853    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
 8854        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
 8855
 8856        let completion = this
 8857            .read_with(&mut cx, |this, _| {
 8858                let id = LanguageServerId(envelope.payload.language_server_id as usize);
 8859                let Some(server) = this.language_server_for_id(id) else {
 8860                    return Err(anyhow!("No language server {id}"));
 8861                };
 8862
 8863                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
 8864            })??
 8865            .await?;
 8866
 8867        let mut is_markdown = false;
 8868        let text = match completion.documentation {
 8869            Some(lsp::Documentation::String(text)) => text,
 8870
 8871            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
 8872                is_markdown = kind == lsp::MarkupKind::Markdown;
 8873                value
 8874            }
 8875
 8876            _ => String::new(),
 8877        };
 8878
 8879        Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
 8880    }
 8881
 8882    async fn handle_apply_code_action(
 8883        this: Model<Self>,
 8884        envelope: TypedEnvelope<proto::ApplyCodeAction>,
 8885        _: Arc<Client>,
 8886        mut cx: AsyncAppContext,
 8887    ) -> Result<proto::ApplyCodeActionResponse> {
 8888        let sender_id = envelope.original_sender_id()?;
 8889        let action = Self::deserialize_code_action(
 8890            envelope
 8891                .payload
 8892                .action
 8893                .ok_or_else(|| anyhow!("invalid action"))?,
 8894        )?;
 8895        let apply_code_action = this.update(&mut cx, |this, cx| {
 8896            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8897            let buffer = this
 8898                .opened_buffers
 8899                .get(&buffer_id)
 8900                .and_then(|buffer| buffer.upgrade())
 8901                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
 8902            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
 8903        })??;
 8904
 8905        let project_transaction = apply_code_action.await?;
 8906        let project_transaction = this.update(&mut cx, |this, cx| {
 8907            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8908        })?;
 8909        Ok(proto::ApplyCodeActionResponse {
 8910            transaction: Some(project_transaction),
 8911        })
 8912    }
 8913
 8914    async fn handle_on_type_formatting(
 8915        this: Model<Self>,
 8916        envelope: TypedEnvelope<proto::OnTypeFormatting>,
 8917        _: Arc<Client>,
 8918        mut cx: AsyncAppContext,
 8919    ) -> Result<proto::OnTypeFormattingResponse> {
 8920        let on_type_formatting = this.update(&mut cx, |this, cx| {
 8921            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8922            let buffer = this
 8923                .opened_buffers
 8924                .get(&buffer_id)
 8925                .and_then(|buffer| buffer.upgrade())
 8926                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 8927            let position = envelope
 8928                .payload
 8929                .position
 8930                .and_then(deserialize_anchor)
 8931                .ok_or_else(|| anyhow!("invalid position"))?;
 8932            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
 8933                buffer,
 8934                position,
 8935                envelope.payload.trigger.clone(),
 8936                cx,
 8937            ))
 8938        })??;
 8939
 8940        let transaction = on_type_formatting
 8941            .await?
 8942            .as_ref()
 8943            .map(language::proto::serialize_transaction);
 8944        Ok(proto::OnTypeFormattingResponse { transaction })
 8945    }
 8946
 8947    async fn handle_inlay_hints(
 8948        this: Model<Self>,
 8949        envelope: TypedEnvelope<proto::InlayHints>,
 8950        _: Arc<Client>,
 8951        mut cx: AsyncAppContext,
 8952    ) -> Result<proto::InlayHintsResponse> {
 8953        let sender_id = envelope.original_sender_id()?;
 8954        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8955        let buffer = this.update(&mut cx, |this, _| {
 8956            this.opened_buffers
 8957                .get(&buffer_id)
 8958                .and_then(|buffer| buffer.upgrade())
 8959                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
 8960        })??;
 8961        buffer
 8962            .update(&mut cx, |buffer, _| {
 8963                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 8964            })?
 8965            .await
 8966            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
 8967
 8968        let start = envelope
 8969            .payload
 8970            .start
 8971            .and_then(deserialize_anchor)
 8972            .context("missing range start")?;
 8973        let end = envelope
 8974            .payload
 8975            .end
 8976            .and_then(deserialize_anchor)
 8977            .context("missing range end")?;
 8978        let buffer_hints = this
 8979            .update(&mut cx, |project, cx| {
 8980                project.inlay_hints(buffer.clone(), start..end, cx)
 8981            })?
 8982            .await
 8983            .context("inlay hints fetch")?;
 8984
 8985        this.update(&mut cx, |project, cx| {
 8986            InlayHints::response_to_proto(
 8987                buffer_hints,
 8988                project,
 8989                sender_id,
 8990                &buffer.read(cx).version(),
 8991                cx,
 8992            )
 8993        })
 8994    }
 8995
 8996    async fn handle_resolve_inlay_hint(
 8997        this: Model<Self>,
 8998        envelope: TypedEnvelope<proto::ResolveInlayHint>,
 8999        _: Arc<Client>,
 9000        mut cx: AsyncAppContext,
 9001    ) -> Result<proto::ResolveInlayHintResponse> {
 9002        let proto_hint = envelope
 9003            .payload
 9004            .hint
 9005            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
 9006        let hint = InlayHints::proto_to_project_hint(proto_hint)
 9007            .context("resolved proto inlay hint conversion")?;
 9008        let buffer = this.update(&mut cx, |this, _cx| {
 9009            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9010            this.opened_buffers
 9011                .get(&buffer_id)
 9012                .and_then(|buffer| buffer.upgrade())
 9013                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 9014        })??;
 9015        let response_hint = this
 9016            .update(&mut cx, |project, cx| {
 9017                project.resolve_inlay_hint(
 9018                    hint,
 9019                    buffer,
 9020                    LanguageServerId(envelope.payload.language_server_id as usize),
 9021                    cx,
 9022                )
 9023            })?
 9024            .await
 9025            .context("inlay hints fetch")?;
 9026        Ok(proto::ResolveInlayHintResponse {
 9027            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
 9028        })
 9029    }
 9030
 9031    async fn try_resolve_code_action(
 9032        lang_server: &LanguageServer,
 9033        action: &mut CodeAction,
 9034    ) -> anyhow::Result<()> {
 9035        if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
 9036            if action.lsp_action.data.is_some()
 9037                && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
 9038            {
 9039                action.lsp_action = lang_server
 9040                    .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
 9041                    .await?;
 9042            }
 9043        }
 9044
 9045        anyhow::Ok(())
 9046    }
 9047
 9048    async fn execute_code_actions_on_servers(
 9049        project: &WeakModel<Project>,
 9050        adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
 9051        code_actions: Vec<lsp::CodeActionKind>,
 9052        buffer: &Model<Buffer>,
 9053        push_to_history: bool,
 9054        project_transaction: &mut ProjectTransaction,
 9055        cx: &mut AsyncAppContext,
 9056    ) -> Result<(), anyhow::Error> {
 9057        for (lsp_adapter, language_server) in adapters_and_servers.iter() {
 9058            let code_actions = code_actions.clone();
 9059
 9060            let actions = project
 9061                .update(cx, move |this, cx| {
 9062                    let request = GetCodeActions {
 9063                        range: text::Anchor::MIN..text::Anchor::MAX,
 9064                        kinds: Some(code_actions),
 9065                    };
 9066                    let server = LanguageServerToQuery::Other(language_server.server_id());
 9067                    this.request_lsp(buffer.clone(), server, request, cx)
 9068                })?
 9069                .await?;
 9070
 9071            for mut action in actions {
 9072                Self::try_resolve_code_action(&language_server, &mut action)
 9073                    .await
 9074                    .context("resolving a formatting code action")?;
 9075
 9076                if let Some(edit) = action.lsp_action.edit {
 9077                    if edit.changes.is_none() && edit.document_changes.is_none() {
 9078                        continue;
 9079                    }
 9080
 9081                    let new = Self::deserialize_workspace_edit(
 9082                        project
 9083                            .upgrade()
 9084                            .ok_or_else(|| anyhow!("project dropped"))?,
 9085                        edit,
 9086                        push_to_history,
 9087                        lsp_adapter.clone(),
 9088                        language_server.clone(),
 9089                        cx,
 9090                    )
 9091                    .await?;
 9092                    project_transaction.0.extend(new.0);
 9093                }
 9094
 9095                if let Some(command) = action.lsp_action.command {
 9096                    project.update(cx, |this, _| {
 9097                        this.last_workspace_edits_by_language_server
 9098                            .remove(&language_server.server_id());
 9099                    })?;
 9100
 9101                    language_server
 9102                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 9103                            command: command.command,
 9104                            arguments: command.arguments.unwrap_or_default(),
 9105                            ..Default::default()
 9106                        })
 9107                        .await?;
 9108
 9109                    project.update(cx, |this, _| {
 9110                        project_transaction.0.extend(
 9111                            this.last_workspace_edits_by_language_server
 9112                                .remove(&language_server.server_id())
 9113                                .unwrap_or_default()
 9114                                .0,
 9115                        )
 9116                    })?;
 9117                }
 9118            }
 9119        }
 9120
 9121        Ok(())
 9122    }
 9123
 9124    async fn handle_refresh_inlay_hints(
 9125        this: Model<Self>,
 9126        _: TypedEnvelope<proto::RefreshInlayHints>,
 9127        _: Arc<Client>,
 9128        mut cx: AsyncAppContext,
 9129    ) -> Result<proto::Ack> {
 9130        this.update(&mut cx, |_, cx| {
 9131            cx.emit(Event::RefreshInlayHints);
 9132        })?;
 9133        Ok(proto::Ack {})
 9134    }
 9135
 9136    async fn handle_lsp_command<T: LspCommand>(
 9137        this: Model<Self>,
 9138        envelope: TypedEnvelope<T::ProtoRequest>,
 9139        _: Arc<Client>,
 9140        mut cx: AsyncAppContext,
 9141    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
 9142    where
 9143        <T::LspRequest as lsp::request::Request>::Params: Send,
 9144        <T::LspRequest as lsp::request::Request>::Result: Send,
 9145    {
 9146        let sender_id = envelope.original_sender_id()?;
 9147        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
 9148        let buffer_handle = this.update(&mut cx, |this, _cx| {
 9149            this.opened_buffers
 9150                .get(&buffer_id)
 9151                .and_then(|buffer| buffer.upgrade())
 9152                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 9153        })??;
 9154        let request = T::from_proto(
 9155            envelope.payload,
 9156            this.clone(),
 9157            buffer_handle.clone(),
 9158            cx.clone(),
 9159        )
 9160        .await?;
 9161        let response = this
 9162            .update(&mut cx, |this, cx| {
 9163                this.request_lsp(
 9164                    buffer_handle.clone(),
 9165                    LanguageServerToQuery::Primary,
 9166                    request,
 9167                    cx,
 9168                )
 9169            })?
 9170            .await?;
 9171        this.update(&mut cx, |this, cx| {
 9172            Ok(T::response_to_proto(
 9173                response,
 9174                this,
 9175                sender_id,
 9176                &buffer_handle.read(cx).version(),
 9177                cx,
 9178            ))
 9179        })?
 9180    }
 9181
 9182    async fn handle_get_project_symbols(
 9183        this: Model<Self>,
 9184        envelope: TypedEnvelope<proto::GetProjectSymbols>,
 9185        _: Arc<Client>,
 9186        mut cx: AsyncAppContext,
 9187    ) -> Result<proto::GetProjectSymbolsResponse> {
 9188        let symbols = this
 9189            .update(&mut cx, |this, cx| {
 9190                this.symbols(&envelope.payload.query, cx)
 9191            })?
 9192            .await?;
 9193
 9194        Ok(proto::GetProjectSymbolsResponse {
 9195            symbols: symbols.iter().map(serialize_symbol).collect(),
 9196        })
 9197    }
 9198
 9199    async fn handle_search_project(
 9200        this: Model<Self>,
 9201        envelope: TypedEnvelope<proto::SearchProject>,
 9202        _: Arc<Client>,
 9203        mut cx: AsyncAppContext,
 9204    ) -> Result<proto::SearchProjectResponse> {
 9205        let peer_id = envelope.original_sender_id()?;
 9206        let query = SearchQuery::from_proto(envelope.payload)?;
 9207        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
 9208
 9209        cx.spawn(move |mut cx| async move {
 9210            let mut locations = Vec::new();
 9211            let mut limit_reached = false;
 9212            while let Some(result) = result.next().await {
 9213                match result {
 9214                    SearchResult::Buffer { buffer, ranges } => {
 9215                        for range in ranges {
 9216                            let start = serialize_anchor(&range.start);
 9217                            let end = serialize_anchor(&range.end);
 9218                            let buffer_id = this.update(&mut cx, |this, cx| {
 9219                                this.create_buffer_for_peer(&buffer, peer_id, cx).into()
 9220                            })?;
 9221                            locations.push(proto::Location {
 9222                                buffer_id,
 9223                                start: Some(start),
 9224                                end: Some(end),
 9225                            });
 9226                        }
 9227                    }
 9228                    SearchResult::LimitReached => limit_reached = true,
 9229                }
 9230            }
 9231            Ok(proto::SearchProjectResponse {
 9232                locations,
 9233                limit_reached,
 9234            })
 9235        })
 9236        .await
 9237    }
 9238
 9239    async fn handle_open_buffer_for_symbol(
 9240        this: Model<Self>,
 9241        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
 9242        _: Arc<Client>,
 9243        mut cx: AsyncAppContext,
 9244    ) -> Result<proto::OpenBufferForSymbolResponse> {
 9245        let peer_id = envelope.original_sender_id()?;
 9246        let symbol = envelope
 9247            .payload
 9248            .symbol
 9249            .ok_or_else(|| anyhow!("invalid symbol"))?;
 9250        let symbol = Self::deserialize_symbol(symbol)?;
 9251        let symbol = this.update(&mut cx, |this, _| {
 9252            let signature = this.symbol_signature(&symbol.path);
 9253            if signature == symbol.signature {
 9254                Ok(symbol)
 9255            } else {
 9256                Err(anyhow!("invalid symbol signature"))
 9257            }
 9258        })??;
 9259        let buffer = this
 9260            .update(&mut cx, |this, cx| {
 9261                this.open_buffer_for_symbol(
 9262                    &Symbol {
 9263                        language_server_name: symbol.language_server_name,
 9264                        source_worktree_id: symbol.source_worktree_id,
 9265                        path: symbol.path,
 9266                        name: symbol.name,
 9267                        kind: symbol.kind,
 9268                        range: symbol.range,
 9269                        signature: symbol.signature,
 9270                        label: CodeLabel {
 9271                            text: Default::default(),
 9272                            runs: Default::default(),
 9273                            filter_range: Default::default(),
 9274                        },
 9275                    },
 9276                    cx,
 9277                )
 9278            })?
 9279            .await?;
 9280
 9281        this.update(&mut cx, |this, cx| {
 9282            let is_private = buffer
 9283                .read(cx)
 9284                .file()
 9285                .map(|f| f.is_private())
 9286                .unwrap_or_default();
 9287            if is_private {
 9288                Err(anyhow!(ErrorCode::UnsharedItem))
 9289            } else {
 9290                Ok(proto::OpenBufferForSymbolResponse {
 9291                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9292                })
 9293            }
 9294        })?
 9295    }
 9296
 9297    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
 9298        let mut hasher = Sha256::new();
 9299        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
 9300        hasher.update(project_path.path.to_string_lossy().as_bytes());
 9301        hasher.update(self.nonce.to_be_bytes());
 9302        hasher.finalize().as_slice().try_into().unwrap()
 9303    }
 9304
 9305    async fn handle_open_buffer_by_id(
 9306        this: Model<Self>,
 9307        envelope: TypedEnvelope<proto::OpenBufferById>,
 9308        _: Arc<Client>,
 9309        mut cx: AsyncAppContext,
 9310    ) -> Result<proto::OpenBufferResponse> {
 9311        let peer_id = envelope.original_sender_id()?;
 9312        let buffer_id = BufferId::new(envelope.payload.id)?;
 9313        let buffer = this
 9314            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
 9315            .await?;
 9316        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9317    }
 9318
 9319    async fn handle_open_buffer_by_path(
 9320        this: Model<Self>,
 9321        envelope: TypedEnvelope<proto::OpenBufferByPath>,
 9322        _: Arc<Client>,
 9323        mut cx: AsyncAppContext,
 9324    ) -> Result<proto::OpenBufferResponse> {
 9325        let peer_id = envelope.original_sender_id()?;
 9326        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 9327        let open_buffer = this.update(&mut cx, |this, cx| {
 9328            this.open_buffer(
 9329                ProjectPath {
 9330                    worktree_id,
 9331                    path: PathBuf::from(envelope.payload.path).into(),
 9332                },
 9333                cx,
 9334            )
 9335        })?;
 9336
 9337        let buffer = open_buffer.await?;
 9338        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9339    }
 9340
 9341    fn respond_to_open_buffer_request(
 9342        this: Model<Self>,
 9343        buffer: Model<Buffer>,
 9344        peer_id: proto::PeerId,
 9345        cx: &mut AsyncAppContext,
 9346    ) -> Result<proto::OpenBufferResponse> {
 9347        this.update(cx, |this, cx| {
 9348            let is_private = buffer
 9349                .read(cx)
 9350                .file()
 9351                .map(|f| f.is_private())
 9352                .unwrap_or_default();
 9353            if is_private {
 9354                Err(anyhow!(ErrorCode::UnsharedItem))
 9355            } else {
 9356                Ok(proto::OpenBufferResponse {
 9357                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9358                })
 9359            }
 9360        })?
 9361    }
 9362
 9363    fn serialize_project_transaction_for_peer(
 9364        &mut self,
 9365        project_transaction: ProjectTransaction,
 9366        peer_id: proto::PeerId,
 9367        cx: &mut AppContext,
 9368    ) -> proto::ProjectTransaction {
 9369        let mut serialized_transaction = proto::ProjectTransaction {
 9370            buffer_ids: Default::default(),
 9371            transactions: Default::default(),
 9372        };
 9373        for (buffer, transaction) in project_transaction.0 {
 9374            serialized_transaction
 9375                .buffer_ids
 9376                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
 9377            serialized_transaction
 9378                .transactions
 9379                .push(language::proto::serialize_transaction(&transaction));
 9380        }
 9381        serialized_transaction
 9382    }
 9383
 9384    fn deserialize_project_transaction(
 9385        &mut self,
 9386        message: proto::ProjectTransaction,
 9387        push_to_history: bool,
 9388        cx: &mut ModelContext<Self>,
 9389    ) -> Task<Result<ProjectTransaction>> {
 9390        cx.spawn(move |this, mut cx| async move {
 9391            let mut project_transaction = ProjectTransaction::default();
 9392            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
 9393            {
 9394                let buffer_id = BufferId::new(buffer_id)?;
 9395                let buffer = this
 9396                    .update(&mut cx, |this, cx| {
 9397                        this.wait_for_remote_buffer(buffer_id, cx)
 9398                    })?
 9399                    .await?;
 9400                let transaction = language::proto::deserialize_transaction(transaction)?;
 9401                project_transaction.0.insert(buffer, transaction);
 9402            }
 9403
 9404            for (buffer, transaction) in &project_transaction.0 {
 9405                buffer
 9406                    .update(&mut cx, |buffer, _| {
 9407                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 9408                    })?
 9409                    .await?;
 9410
 9411                if push_to_history {
 9412                    buffer.update(&mut cx, |buffer, _| {
 9413                        buffer.push_transaction(transaction.clone(), Instant::now());
 9414                    })?;
 9415                }
 9416            }
 9417
 9418            Ok(project_transaction)
 9419        })
 9420    }
 9421
 9422    fn create_buffer_for_peer(
 9423        &mut self,
 9424        buffer: &Model<Buffer>,
 9425        peer_id: proto::PeerId,
 9426        cx: &mut AppContext,
 9427    ) -> BufferId {
 9428        let buffer_id = buffer.read(cx).remote_id();
 9429        if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
 9430            updates_tx
 9431                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
 9432                .ok();
 9433        }
 9434        buffer_id
 9435    }
 9436
 9437    fn wait_for_remote_buffer(
 9438        &mut self,
 9439        id: BufferId,
 9440        cx: &mut ModelContext<Self>,
 9441    ) -> Task<Result<Model<Buffer>>> {
 9442        let buffer = self
 9443            .opened_buffers
 9444            .get(&id)
 9445            .and_then(|buffer| buffer.upgrade());
 9446
 9447        if let Some(buffer) = buffer {
 9448            return Task::ready(Ok(buffer));
 9449        }
 9450
 9451        let (tx, rx) = oneshot::channel();
 9452        self.loading_buffers.entry(id).or_default().push(tx);
 9453
 9454        cx.background_executor().spawn(async move { rx.await? })
 9455    }
 9456
 9457    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 9458        let project_id = match self.client_state {
 9459            ProjectClientState::Remote {
 9460                sharing_has_stopped,
 9461                remote_id,
 9462                ..
 9463            } => {
 9464                if sharing_has_stopped {
 9465                    return Task::ready(Err(anyhow!(
 9466                        "can't synchronize remote buffers on a readonly project"
 9467                    )));
 9468                } else {
 9469                    remote_id
 9470                }
 9471            }
 9472            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
 9473                return Task::ready(Err(anyhow!(
 9474                    "can't synchronize remote buffers on a local project"
 9475                )))
 9476            }
 9477        };
 9478
 9479        let client = self.client.clone();
 9480        cx.spawn(move |this, mut cx| async move {
 9481            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
 9482                let buffers = this
 9483                    .opened_buffers
 9484                    .iter()
 9485                    .filter_map(|(id, buffer)| {
 9486                        let buffer = buffer.upgrade()?;
 9487                        Some(proto::BufferVersion {
 9488                            id: (*id).into(),
 9489                            version: language::proto::serialize_version(&buffer.read(cx).version),
 9490                        })
 9491                    })
 9492                    .collect();
 9493                let incomplete_buffer_ids = this
 9494                    .incomplete_remote_buffers
 9495                    .keys()
 9496                    .copied()
 9497                    .collect::<Vec<_>>();
 9498
 9499                (buffers, incomplete_buffer_ids)
 9500            })?;
 9501            let response = client
 9502                .request(proto::SynchronizeBuffers {
 9503                    project_id,
 9504                    buffers,
 9505                })
 9506                .await?;
 9507
 9508            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
 9509                response
 9510                    .buffers
 9511                    .into_iter()
 9512                    .map(|buffer| {
 9513                        let client = client.clone();
 9514                        let buffer_id = match BufferId::new(buffer.id) {
 9515                            Ok(id) => id,
 9516                            Err(e) => {
 9517                                return Task::ready(Err(e));
 9518                            }
 9519                        };
 9520                        let remote_version = language::proto::deserialize_version(&buffer.version);
 9521                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
 9522                            let operations =
 9523                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
 9524                            cx.background_executor().spawn(async move {
 9525                                let operations = operations.await;
 9526                                for chunk in split_operations(operations) {
 9527                                    client
 9528                                        .request(proto::UpdateBuffer {
 9529                                            project_id,
 9530                                            buffer_id: buffer_id.into(),
 9531                                            operations: chunk,
 9532                                        })
 9533                                        .await?;
 9534                                }
 9535                                anyhow::Ok(())
 9536                            })
 9537                        } else {
 9538                            Task::ready(Ok(()))
 9539                        }
 9540                    })
 9541                    .collect::<Vec<_>>()
 9542            })?;
 9543
 9544            // Any incomplete buffers have open requests waiting. Request that the host sends
 9545            // creates these buffers for us again to unblock any waiting futures.
 9546            for id in incomplete_buffer_ids {
 9547                cx.background_executor()
 9548                    .spawn(client.request(proto::OpenBufferById {
 9549                        project_id,
 9550                        id: id.into(),
 9551                    }))
 9552                    .detach();
 9553            }
 9554
 9555            futures::future::join_all(send_updates_for_buffers)
 9556                .await
 9557                .into_iter()
 9558                .collect()
 9559        })
 9560    }
 9561
 9562    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
 9563        self.worktrees()
 9564            .map(|worktree| {
 9565                let worktree = worktree.read(cx);
 9566                proto::WorktreeMetadata {
 9567                    id: worktree.id().to_proto(),
 9568                    root_name: worktree.root_name().into(),
 9569                    visible: worktree.is_visible(),
 9570                    abs_path: worktree.abs_path().to_string_lossy().into(),
 9571                }
 9572            })
 9573            .collect()
 9574    }
 9575
 9576    fn set_worktrees_from_proto(
 9577        &mut self,
 9578        worktrees: Vec<proto::WorktreeMetadata>,
 9579        cx: &mut ModelContext<Project>,
 9580    ) -> Result<()> {
 9581        let replica_id = self.replica_id();
 9582        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
 9583
 9584        let mut old_worktrees_by_id = self
 9585            .worktrees
 9586            .drain(..)
 9587            .filter_map(|worktree| {
 9588                let worktree = worktree.upgrade()?;
 9589                Some((worktree.read(cx).id(), worktree))
 9590            })
 9591            .collect::<HashMap<_, _>>();
 9592
 9593        for worktree in worktrees {
 9594            if let Some(old_worktree) =
 9595                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
 9596            {
 9597                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
 9598            } else {
 9599                let worktree =
 9600                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
 9601                let _ = self.add_worktree(&worktree, cx);
 9602            }
 9603        }
 9604
 9605        self.metadata_changed(cx);
 9606        for id in old_worktrees_by_id.keys() {
 9607            cx.emit(Event::WorktreeRemoved(*id));
 9608        }
 9609
 9610        Ok(())
 9611    }
 9612
 9613    fn set_collaborators_from_proto(
 9614        &mut self,
 9615        messages: Vec<proto::Collaborator>,
 9616        cx: &mut ModelContext<Self>,
 9617    ) -> Result<()> {
 9618        let mut collaborators = HashMap::default();
 9619        for message in messages {
 9620            let collaborator = Collaborator::from_proto(message)?;
 9621            collaborators.insert(collaborator.peer_id, collaborator);
 9622        }
 9623        for old_peer_id in self.collaborators.keys() {
 9624            if !collaborators.contains_key(old_peer_id) {
 9625                cx.emit(Event::CollaboratorLeft(*old_peer_id));
 9626            }
 9627        }
 9628        self.collaborators = collaborators;
 9629        Ok(())
 9630    }
 9631
 9632    fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
 9633        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
 9634        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
 9635        let kind = unsafe { mem::transmute(serialized_symbol.kind) };
 9636        let path = ProjectPath {
 9637            worktree_id,
 9638            path: PathBuf::from(serialized_symbol.path).into(),
 9639        };
 9640
 9641        let start = serialized_symbol
 9642            .start
 9643            .ok_or_else(|| anyhow!("invalid start"))?;
 9644        let end = serialized_symbol
 9645            .end
 9646            .ok_or_else(|| anyhow!("invalid end"))?;
 9647        Ok(CoreSymbol {
 9648            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
 9649            source_worktree_id,
 9650            path,
 9651            name: serialized_symbol.name,
 9652            range: Unclipped(PointUtf16::new(start.row, start.column))
 9653                ..Unclipped(PointUtf16::new(end.row, end.column)),
 9654            kind,
 9655            signature: serialized_symbol
 9656                .signature
 9657                .try_into()
 9658                .map_err(|_| anyhow!("invalid signature"))?,
 9659        })
 9660    }
 9661
 9662    fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
 9663        proto::Completion {
 9664            old_start: Some(serialize_anchor(&completion.old_range.start)),
 9665            old_end: Some(serialize_anchor(&completion.old_range.end)),
 9666            new_text: completion.new_text.clone(),
 9667            server_id: completion.server_id.0 as u64,
 9668            lsp_completion: serde_json::to_vec(&completion.lsp_completion).unwrap(),
 9669        }
 9670    }
 9671
 9672    fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
 9673        let old_start = completion
 9674            .old_start
 9675            .and_then(deserialize_anchor)
 9676            .ok_or_else(|| anyhow!("invalid old start"))?;
 9677        let old_end = completion
 9678            .old_end
 9679            .and_then(deserialize_anchor)
 9680            .ok_or_else(|| anyhow!("invalid old end"))?;
 9681        let lsp_completion = serde_json::from_slice(&completion.lsp_completion)?;
 9682
 9683        Ok(CoreCompletion {
 9684            old_range: old_start..old_end,
 9685            new_text: completion.new_text,
 9686            server_id: LanguageServerId(completion.server_id as usize),
 9687            lsp_completion,
 9688        })
 9689    }
 9690
 9691    fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
 9692        proto::CodeAction {
 9693            server_id: action.server_id.0 as u64,
 9694            start: Some(serialize_anchor(&action.range.start)),
 9695            end: Some(serialize_anchor(&action.range.end)),
 9696            lsp_action: serde_json::to_vec(&action.lsp_action).unwrap(),
 9697        }
 9698    }
 9699
 9700    fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
 9701        let start = action
 9702            .start
 9703            .and_then(deserialize_anchor)
 9704            .ok_or_else(|| anyhow!("invalid start"))?;
 9705        let end = action
 9706            .end
 9707            .and_then(deserialize_anchor)
 9708            .ok_or_else(|| anyhow!("invalid end"))?;
 9709        let lsp_action = serde_json::from_slice(&action.lsp_action)?;
 9710        Ok(CodeAction {
 9711            server_id: LanguageServerId(action.server_id as usize),
 9712            range: start..end,
 9713            lsp_action,
 9714        })
 9715    }
 9716
 9717    async fn handle_buffer_saved(
 9718        this: Model<Self>,
 9719        envelope: TypedEnvelope<proto::BufferSaved>,
 9720        _: Arc<Client>,
 9721        mut cx: AsyncAppContext,
 9722    ) -> Result<()> {
 9723        let version = deserialize_version(&envelope.payload.version);
 9724        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9725        let mtime = envelope.payload.mtime.map(|time| time.into());
 9726
 9727        this.update(&mut cx, |this, cx| {
 9728            let buffer = this
 9729                .opened_buffers
 9730                .get(&buffer_id)
 9731                .and_then(|buffer| buffer.upgrade())
 9732                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
 9733            if let Some(buffer) = buffer {
 9734                buffer.update(cx, |buffer, cx| {
 9735                    buffer.did_save(version, mtime, cx);
 9736                });
 9737            }
 9738            Ok(())
 9739        })?
 9740    }
 9741
 9742    async fn handle_buffer_reloaded(
 9743        this: Model<Self>,
 9744        envelope: TypedEnvelope<proto::BufferReloaded>,
 9745        _: Arc<Client>,
 9746        mut cx: AsyncAppContext,
 9747    ) -> Result<()> {
 9748        let payload = envelope.payload;
 9749        let version = deserialize_version(&payload.version);
 9750        let line_ending = deserialize_line_ending(
 9751            proto::LineEnding::from_i32(payload.line_ending)
 9752                .ok_or_else(|| anyhow!("missing line ending"))?,
 9753        );
 9754        let mtime = payload.mtime.map(|time| time.into());
 9755        let buffer_id = BufferId::new(payload.buffer_id)?;
 9756        this.update(&mut cx, |this, cx| {
 9757            let buffer = this
 9758                .opened_buffers
 9759                .get(&buffer_id)
 9760                .and_then(|buffer| buffer.upgrade())
 9761                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
 9762            if let Some(buffer) = buffer {
 9763                buffer.update(cx, |buffer, cx| {
 9764                    buffer.did_reload(version, line_ending, mtime, cx);
 9765                });
 9766            }
 9767            Ok(())
 9768        })?
 9769    }
 9770
 9771    #[allow(clippy::type_complexity)]
 9772    fn edits_from_lsp(
 9773        &mut self,
 9774        buffer: &Model<Buffer>,
 9775        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
 9776        server_id: LanguageServerId,
 9777        version: Option<i32>,
 9778        cx: &mut ModelContext<Self>,
 9779    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
 9780        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
 9781        cx.background_executor().spawn(async move {
 9782            let snapshot = snapshot?;
 9783            let mut lsp_edits = lsp_edits
 9784                .into_iter()
 9785                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
 9786                .collect::<Vec<_>>();
 9787            lsp_edits.sort_by_key(|(range, _)| range.start);
 9788
 9789            let mut lsp_edits = lsp_edits.into_iter().peekable();
 9790            let mut edits = Vec::new();
 9791            while let Some((range, mut new_text)) = lsp_edits.next() {
 9792                // Clip invalid ranges provided by the language server.
 9793                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
 9794                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
 9795
 9796                // Combine any LSP edits that are adjacent.
 9797                //
 9798                // Also, combine LSP edits that are separated from each other by only
 9799                // a newline. This is important because for some code actions,
 9800                // Rust-analyzer rewrites the entire buffer via a series of edits that
 9801                // are separated by unchanged newline characters.
 9802                //
 9803                // In order for the diffing logic below to work properly, any edits that
 9804                // cancel each other out must be combined into one.
 9805                while let Some((next_range, next_text)) = lsp_edits.peek() {
 9806                    if next_range.start.0 > range.end {
 9807                        if next_range.start.0.row > range.end.row + 1
 9808                            || next_range.start.0.column > 0
 9809                            || snapshot.clip_point_utf16(
 9810                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
 9811                                Bias::Left,
 9812                            ) > range.end
 9813                        {
 9814                            break;
 9815                        }
 9816                        new_text.push('\n');
 9817                    }
 9818                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
 9819                    new_text.push_str(next_text);
 9820                    lsp_edits.next();
 9821                }
 9822
 9823                // For multiline edits, perform a diff of the old and new text so that
 9824                // we can identify the changes more precisely, preserving the locations
 9825                // of any anchors positioned in the unchanged regions.
 9826                if range.end.row > range.start.row {
 9827                    let mut offset = range.start.to_offset(&snapshot);
 9828                    let old_text = snapshot.text_for_range(range).collect::<String>();
 9829
 9830                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
 9831                    let mut moved_since_edit = true;
 9832                    for change in diff.iter_all_changes() {
 9833                        let tag = change.tag();
 9834                        let value = change.value();
 9835                        match tag {
 9836                            ChangeTag::Equal => {
 9837                                offset += value.len();
 9838                                moved_since_edit = true;
 9839                            }
 9840                            ChangeTag::Delete => {
 9841                                let start = snapshot.anchor_after(offset);
 9842                                let end = snapshot.anchor_before(offset + value.len());
 9843                                if moved_since_edit {
 9844                                    edits.push((start..end, String::new()));
 9845                                } else {
 9846                                    edits.last_mut().unwrap().0.end = end;
 9847                                }
 9848                                offset += value.len();
 9849                                moved_since_edit = false;
 9850                            }
 9851                            ChangeTag::Insert => {
 9852                                if moved_since_edit {
 9853                                    let anchor = snapshot.anchor_after(offset);
 9854                                    edits.push((anchor..anchor, value.to_string()));
 9855                                } else {
 9856                                    edits.last_mut().unwrap().1.push_str(value);
 9857                                }
 9858                                moved_since_edit = false;
 9859                            }
 9860                        }
 9861                    }
 9862                } else if range.end == range.start {
 9863                    let anchor = snapshot.anchor_after(range.start);
 9864                    edits.push((anchor..anchor, new_text));
 9865                } else {
 9866                    let edit_start = snapshot.anchor_after(range.start);
 9867                    let edit_end = snapshot.anchor_before(range.end);
 9868                    edits.push((edit_start..edit_end, new_text));
 9869                }
 9870            }
 9871
 9872            Ok(edits)
 9873        })
 9874    }
 9875
 9876    fn buffer_snapshot_for_lsp_version(
 9877        &mut self,
 9878        buffer: &Model<Buffer>,
 9879        server_id: LanguageServerId,
 9880        version: Option<i32>,
 9881        cx: &AppContext,
 9882    ) -> Result<TextBufferSnapshot> {
 9883        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
 9884
 9885        if let Some(version) = version {
 9886            let buffer_id = buffer.read(cx).remote_id();
 9887            let snapshots = self
 9888                .buffer_snapshots
 9889                .get_mut(&buffer_id)
 9890                .and_then(|m| m.get_mut(&server_id))
 9891                .ok_or_else(|| {
 9892                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
 9893                })?;
 9894
 9895            let found_snapshot = snapshots
 9896                .binary_search_by_key(&version, |e| e.version)
 9897                .map(|ix| snapshots[ix].snapshot.clone())
 9898                .map_err(|_| {
 9899                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
 9900                })?;
 9901
 9902            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
 9903            Ok(found_snapshot)
 9904        } else {
 9905            Ok((buffer.read(cx)).text_snapshot())
 9906        }
 9907    }
 9908
 9909    pub fn language_servers(
 9910        &self,
 9911    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
 9912        self.language_server_ids
 9913            .iter()
 9914            .map(|((worktree_id, server_name), server_id)| {
 9915                (*server_id, server_name.clone(), *worktree_id)
 9916            })
 9917    }
 9918
 9919    pub fn supplementary_language_servers(
 9920        &self,
 9921    ) -> impl '_
 9922           + Iterator<
 9923        Item = (
 9924            &LanguageServerId,
 9925            &(LanguageServerName, Arc<LanguageServer>),
 9926        ),
 9927    > {
 9928        self.supplementary_language_servers.iter()
 9929    }
 9930
 9931    pub fn language_server_adapter_for_id(
 9932        &self,
 9933        id: LanguageServerId,
 9934    ) -> Option<Arc<CachedLspAdapter>> {
 9935        if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
 9936            Some(adapter.clone())
 9937        } else {
 9938            None
 9939        }
 9940    }
 9941
 9942    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
 9943        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
 9944            Some(server.clone())
 9945        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
 9946            Some(Arc::clone(server))
 9947        } else {
 9948            None
 9949        }
 9950    }
 9951
 9952    pub fn language_servers_for_buffer(
 9953        &self,
 9954        buffer: &Buffer,
 9955        cx: &AppContext,
 9956    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
 9957        self.language_server_ids_for_buffer(buffer, cx)
 9958            .into_iter()
 9959            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
 9960                LanguageServerState::Running {
 9961                    adapter, server, ..
 9962                } => Some((adapter, server)),
 9963                _ => None,
 9964            })
 9965    }
 9966
 9967    fn primary_language_server_for_buffer(
 9968        &self,
 9969        buffer: &Buffer,
 9970        cx: &AppContext,
 9971    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
 9972        self.language_servers_for_buffer(buffer, cx)
 9973            .find(|s| s.0.is_primary)
 9974    }
 9975
 9976    pub fn language_server_for_buffer(
 9977        &self,
 9978        buffer: &Buffer,
 9979        server_id: LanguageServerId,
 9980        cx: &AppContext,
 9981    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
 9982        self.language_servers_for_buffer(buffer, cx)
 9983            .find(|(_, s)| s.server_id() == server_id)
 9984    }
 9985
 9986    fn language_server_ids_for_buffer(
 9987        &self,
 9988        buffer: &Buffer,
 9989        cx: &AppContext,
 9990    ) -> Vec<LanguageServerId> {
 9991        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
 9992            let worktree_id = file.worktree_id(cx);
 9993            self.languages
 9994                .lsp_adapters(&language)
 9995                .iter()
 9996                .flat_map(|adapter| {
 9997                    let key = (worktree_id, adapter.name.clone());
 9998                    self.language_server_ids.get(&key).copied()
 9999                })
10000                .collect()
10001        } else {
10002            Vec::new()
10003        }
10004    }
10005}
10006
10007async fn populate_labels_for_symbols(
10008    symbols: Vec<CoreSymbol>,
10009    language_registry: &Arc<LanguageRegistry>,
10010    default_language: Option<Arc<Language>>,
10011    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10012    output: &mut Vec<Symbol>,
10013) {
10014    let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
10015
10016    let mut unknown_path = None;
10017    for symbol in symbols {
10018        let language = language_registry
10019            .language_for_file_path(&symbol.path.path)
10020            .await
10021            .ok()
10022            .or_else(|| {
10023                unknown_path.get_or_insert(symbol.path.path.clone());
10024                default_language.clone()
10025            });
10026        symbols_by_language
10027            .entry(language)
10028            .or_default()
10029            .push(symbol);
10030    }
10031
10032    if let Some(unknown_path) = unknown_path {
10033        log::info!(
10034            "no language found for symbol path {}",
10035            unknown_path.display()
10036        );
10037    }
10038
10039    let mut label_params = Vec::new();
10040    for (language, mut symbols) in symbols_by_language {
10041        label_params.clear();
10042        label_params.extend(
10043            symbols
10044                .iter_mut()
10045                .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
10046        );
10047
10048        let mut labels = Vec::new();
10049        if let Some(language) = language {
10050            let lsp_adapter = lsp_adapter
10051                .clone()
10052                .or_else(|| language_registry.lsp_adapters(&language).first().cloned());
10053            if let Some(lsp_adapter) = lsp_adapter {
10054                labels = lsp_adapter
10055                    .labels_for_symbols(&label_params, &language)
10056                    .await
10057                    .log_err()
10058                    .unwrap_or_default();
10059            }
10060        }
10061
10062        for ((symbol, (name, _)), label) in symbols
10063            .into_iter()
10064            .zip(label_params.drain(..))
10065            .zip(labels.into_iter().chain(iter::repeat(None)))
10066        {
10067            output.push(Symbol {
10068                language_server_name: symbol.language_server_name,
10069                source_worktree_id: symbol.source_worktree_id,
10070                path: symbol.path,
10071                label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
10072                name,
10073                kind: symbol.kind,
10074                range: symbol.range,
10075                signature: symbol.signature,
10076            });
10077        }
10078    }
10079}
10080
10081async fn populate_labels_for_completions(
10082    mut new_completions: Vec<CoreCompletion>,
10083    language_registry: &Arc<LanguageRegistry>,
10084    language: Option<Arc<Language>>,
10085    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10086    completions: &mut Vec<Completion>,
10087) {
10088    let lsp_completions = new_completions
10089        .iter_mut()
10090        .map(|completion| mem::take(&mut completion.lsp_completion))
10091        .collect::<Vec<_>>();
10092
10093    let labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
10094        lsp_adapter
10095            .labels_for_completions(&lsp_completions, language)
10096            .await
10097            .log_err()
10098            .unwrap_or_default()
10099    } else {
10100        Vec::new()
10101    };
10102
10103    for ((completion, lsp_completion), label) in new_completions
10104        .into_iter()
10105        .zip(lsp_completions)
10106        .zip(labels.into_iter().chain(iter::repeat(None)))
10107    {
10108        let documentation = if let Some(docs) = &lsp_completion.documentation {
10109            Some(prepare_completion_documentation(docs, &language_registry, language.clone()).await)
10110        } else {
10111            None
10112        };
10113
10114        completions.push(Completion {
10115            old_range: completion.old_range,
10116            new_text: completion.new_text,
10117            label: label.unwrap_or_else(|| {
10118                CodeLabel::plain(
10119                    lsp_completion.label.clone(),
10120                    lsp_completion.filter_text.as_deref(),
10121                )
10122            }),
10123            server_id: completion.server_id,
10124            documentation,
10125            lsp_completion,
10126        })
10127    }
10128}
10129
10130fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
10131    code_actions
10132        .iter()
10133        .flat_map(|(kind, enabled)| {
10134            if *enabled {
10135                Some(kind.clone().into())
10136            } else {
10137                None
10138            }
10139        })
10140        .collect()
10141}
10142
10143#[allow(clippy::too_many_arguments)]
10144async fn search_snapshots(
10145    snapshots: &Vec<LocalSnapshot>,
10146    worker_start_ix: usize,
10147    worker_end_ix: usize,
10148    query: &SearchQuery,
10149    results_tx: &Sender<SearchMatchCandidate>,
10150    opened_buffers: &HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
10151    include_root: bool,
10152    fs: &Arc<dyn Fs>,
10153) {
10154    let mut snapshot_start_ix = 0;
10155    let mut abs_path = PathBuf::new();
10156
10157    for snapshot in snapshots {
10158        let snapshot_end_ix = snapshot_start_ix
10159            + if query.include_ignored() {
10160                snapshot.file_count()
10161            } else {
10162                snapshot.visible_file_count()
10163            };
10164        if worker_end_ix <= snapshot_start_ix {
10165            break;
10166        } else if worker_start_ix > snapshot_end_ix {
10167            snapshot_start_ix = snapshot_end_ix;
10168            continue;
10169        } else {
10170            let start_in_snapshot = worker_start_ix.saturating_sub(snapshot_start_ix);
10171            let end_in_snapshot = cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
10172
10173            for entry in snapshot
10174                .files(false, start_in_snapshot)
10175                .take(end_in_snapshot - start_in_snapshot)
10176            {
10177                if results_tx.is_closed() {
10178                    break;
10179                }
10180                if opened_buffers.contains_key(&entry.path) {
10181                    continue;
10182                }
10183
10184                let matched_path = if include_root {
10185                    let mut full_path = PathBuf::from(snapshot.root_name());
10186                    full_path.push(&entry.path);
10187                    query.file_matches(Some(&full_path))
10188                } else {
10189                    query.file_matches(Some(&entry.path))
10190                };
10191
10192                let matches = if matched_path {
10193                    abs_path.clear();
10194                    abs_path.push(&snapshot.abs_path());
10195                    abs_path.push(&entry.path);
10196                    if let Some(file) = fs.open_sync(&abs_path).await.log_err() {
10197                        query.detect(file).unwrap_or(false)
10198                    } else {
10199                        false
10200                    }
10201                } else {
10202                    false
10203                };
10204
10205                if matches {
10206                    let project_path = SearchMatchCandidate::Path {
10207                        worktree_id: snapshot.id(),
10208                        path: entry.path.clone(),
10209                        is_ignored: entry.is_ignored,
10210                    };
10211                    if results_tx.send(project_path).await.is_err() {
10212                        return;
10213                    }
10214                }
10215            }
10216
10217            snapshot_start_ix = snapshot_end_ix;
10218        }
10219    }
10220}
10221
10222async fn search_ignored_entry(
10223    snapshot: &LocalSnapshot,
10224    ignored_entry: &Entry,
10225    fs: &Arc<dyn Fs>,
10226    query: &SearchQuery,
10227    counter_tx: &Sender<SearchMatchCandidate>,
10228) {
10229    let mut ignored_paths_to_process =
10230        VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
10231
10232    while let Some(ignored_abs_path) = ignored_paths_to_process.pop_front() {
10233        let metadata = fs
10234            .metadata(&ignored_abs_path)
10235            .await
10236            .with_context(|| format!("fetching fs metadata for {ignored_abs_path:?}"))
10237            .log_err()
10238            .flatten();
10239
10240        if let Some(fs_metadata) = metadata {
10241            if fs_metadata.is_dir {
10242                let files = fs
10243                    .read_dir(&ignored_abs_path)
10244                    .await
10245                    .with_context(|| format!("listing ignored path {ignored_abs_path:?}"))
10246                    .log_err();
10247
10248                if let Some(mut subfiles) = files {
10249                    while let Some(subfile) = subfiles.next().await {
10250                        if let Some(subfile) = subfile.log_err() {
10251                            ignored_paths_to_process.push_back(subfile);
10252                        }
10253                    }
10254                }
10255            } else if !fs_metadata.is_symlink {
10256                if !query.file_matches(Some(&ignored_abs_path))
10257                    || snapshot.is_path_excluded(ignored_entry.path.to_path_buf())
10258                {
10259                    continue;
10260                }
10261                let matches = if let Some(file) = fs
10262                    .open_sync(&ignored_abs_path)
10263                    .await
10264                    .with_context(|| format!("Opening ignored path {ignored_abs_path:?}"))
10265                    .log_err()
10266                {
10267                    query.detect(file).unwrap_or(false)
10268                } else {
10269                    false
10270                };
10271
10272                if matches {
10273                    let project_path = SearchMatchCandidate::Path {
10274                        worktree_id: snapshot.id(),
10275                        path: Arc::from(
10276                            ignored_abs_path
10277                                .strip_prefix(snapshot.abs_path())
10278                                .expect("scanning worktree-related files"),
10279                        ),
10280                        is_ignored: true,
10281                    };
10282                    if counter_tx.send(project_path).await.is_err() {
10283                        return;
10284                    }
10285                }
10286            }
10287        }
10288    }
10289}
10290
10291fn subscribe_for_copilot_events(
10292    copilot: &Model<Copilot>,
10293    cx: &mut ModelContext<'_, Project>,
10294) -> gpui::Subscription {
10295    cx.subscribe(
10296        copilot,
10297        |project, copilot, copilot_event, cx| match copilot_event {
10298            copilot::Event::CopilotLanguageServerStarted => {
10299                match copilot.read(cx).language_server() {
10300                    Some((name, copilot_server)) => {
10301                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
10302                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
10303                            let new_server_id = copilot_server.server_id();
10304                            let weak_project = cx.weak_model();
10305                            let copilot_log_subscription = copilot_server
10306                                .on_notification::<copilot::request::LogMessage, _>(
10307                                    move |params, mut cx| {
10308                                        weak_project.update(&mut cx, |_, cx| {
10309                                            cx.emit(Event::LanguageServerLog(
10310                                                new_server_id,
10311                                                params.message,
10312                                            ));
10313                                        }).ok();
10314                                    },
10315                                );
10316                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
10317                            project.copilot_log_subscription = Some(copilot_log_subscription);
10318                            cx.emit(Event::LanguageServerAdded(new_server_id));
10319                        }
10320                    }
10321                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
10322                }
10323            }
10324        },
10325    )
10326}
10327
10328fn glob_literal_prefix(glob: &str) -> &str {
10329    let mut literal_end = 0;
10330    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
10331        if part.contains(&['*', '?', '{', '}']) {
10332            break;
10333        } else {
10334            if i > 0 {
10335                // Account for separator prior to this part
10336                literal_end += path::MAIN_SEPARATOR.len_utf8();
10337            }
10338            literal_end += part.len();
10339        }
10340    }
10341    &glob[..literal_end]
10342}
10343
10344impl WorktreeHandle {
10345    pub fn upgrade(&self) -> Option<Model<Worktree>> {
10346        match self {
10347            WorktreeHandle::Strong(handle) => Some(handle.clone()),
10348            WorktreeHandle::Weak(handle) => handle.upgrade(),
10349        }
10350    }
10351
10352    pub fn handle_id(&self) -> usize {
10353        match self {
10354            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
10355            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
10356        }
10357    }
10358}
10359
10360impl OpenBuffer {
10361    pub fn upgrade(&self) -> Option<Model<Buffer>> {
10362        match self {
10363            OpenBuffer::Strong(handle) => Some(handle.clone()),
10364            OpenBuffer::Weak(handle) => handle.upgrade(),
10365            OpenBuffer::Operations(_) => None,
10366        }
10367    }
10368}
10369
10370pub struct PathMatchCandidateSet {
10371    pub snapshot: Snapshot,
10372    pub include_ignored: bool,
10373    pub include_root_name: bool,
10374}
10375
10376impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
10377    type Candidates = PathMatchCandidateSetIter<'a>;
10378
10379    fn id(&self) -> usize {
10380        self.snapshot.id().to_usize()
10381    }
10382
10383    fn len(&self) -> usize {
10384        if self.include_ignored {
10385            self.snapshot.file_count()
10386        } else {
10387            self.snapshot.visible_file_count()
10388        }
10389    }
10390
10391    fn prefix(&self) -> Arc<str> {
10392        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
10393            self.snapshot.root_name().into()
10394        } else if self.include_root_name {
10395            format!("{}/", self.snapshot.root_name()).into()
10396        } else {
10397            "".into()
10398        }
10399    }
10400
10401    fn candidates(&'a self, start: usize) -> Self::Candidates {
10402        PathMatchCandidateSetIter {
10403            traversal: self.snapshot.files(self.include_ignored, start),
10404        }
10405    }
10406}
10407
10408pub struct PathMatchCandidateSetIter<'a> {
10409    traversal: Traversal<'a>,
10410}
10411
10412impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
10413    type Item = fuzzy::PathMatchCandidate<'a>;
10414
10415    fn next(&mut self) -> Option<Self::Item> {
10416        self.traversal.next().map(|entry| {
10417            if let EntryKind::File(char_bag) = entry.kind {
10418                fuzzy::PathMatchCandidate {
10419                    path: &entry.path,
10420                    char_bag,
10421                }
10422            } else {
10423                unreachable!()
10424            }
10425        })
10426    }
10427}
10428
10429impl EventEmitter<Event> for Project {}
10430
10431impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
10432    fn into(self) -> SettingsLocation<'a> {
10433        SettingsLocation {
10434            worktree_id: self.worktree_id.to_usize(),
10435            path: self.path.as_ref(),
10436        }
10437    }
10438}
10439
10440impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
10441    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
10442        Self {
10443            worktree_id,
10444            path: path.as_ref().into(),
10445        }
10446    }
10447}
10448
10449struct ProjectLspAdapterDelegate {
10450    project: WeakModel<Project>,
10451    worktree: worktree::Snapshot,
10452    fs: Arc<dyn Fs>,
10453    http_client: Arc<dyn HttpClient>,
10454    language_registry: Arc<LanguageRegistry>,
10455    shell_env: Mutex<Option<HashMap<String, String>>>,
10456}
10457
10458impl ProjectLspAdapterDelegate {
10459    fn new(project: &Project, worktree: &Model<Worktree>, cx: &ModelContext<Project>) -> Arc<Self> {
10460        Arc::new(Self {
10461            project: cx.weak_model(),
10462            worktree: worktree.read(cx).snapshot(),
10463            fs: project.fs.clone(),
10464            http_client: project.client.http_client(),
10465            language_registry: project.languages.clone(),
10466            shell_env: Default::default(),
10467        })
10468    }
10469
10470    async fn load_shell_env(&self) {
10471        let worktree_abs_path = self.worktree.abs_path();
10472        let shell_env = load_shell_environment(&worktree_abs_path)
10473            .await
10474            .with_context(|| {
10475                format!("failed to determine load login shell environment in {worktree_abs_path:?}")
10476            })
10477            .log_err()
10478            .unwrap_or_default();
10479        *self.shell_env.lock() = Some(shell_env);
10480    }
10481}
10482
10483#[async_trait]
10484impl LspAdapterDelegate for ProjectLspAdapterDelegate {
10485    fn show_notification(&self, message: &str, cx: &mut AppContext) {
10486        self.project
10487            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())))
10488            .ok();
10489    }
10490
10491    fn http_client(&self) -> Arc<dyn HttpClient> {
10492        self.http_client.clone()
10493    }
10494
10495    fn worktree_id(&self) -> u64 {
10496        self.worktree.id().to_proto()
10497    }
10498
10499    fn worktree_root_path(&self) -> &Path {
10500        self.worktree.abs_path().as_ref()
10501    }
10502
10503    async fn shell_env(&self) -> HashMap<String, String> {
10504        self.load_shell_env().await;
10505        self.shell_env.lock().as_ref().cloned().unwrap_or_default()
10506    }
10507
10508    #[cfg(not(target_os = "windows"))]
10509    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10510        let worktree_abs_path = self.worktree.abs_path();
10511        self.load_shell_env().await;
10512        let shell_path = self
10513            .shell_env
10514            .lock()
10515            .as_ref()
10516            .and_then(|shell_env| shell_env.get("PATH").cloned());
10517        which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
10518    }
10519
10520    #[cfg(target_os = "windows")]
10521    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10522        // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
10523        //               there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
10524        //               SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
10525        which::which(command).ok()
10526    }
10527
10528    fn update_status(
10529        &self,
10530        server_name: LanguageServerName,
10531        status: language::LanguageServerBinaryStatus,
10532    ) {
10533        self.language_registry
10534            .update_lsp_status(server_name, status);
10535    }
10536
10537    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
10538        if self.worktree.entry_for_path(&path).is_none() {
10539            return Err(anyhow!("no such path {path:?}"));
10540        }
10541        let path = self.worktree.absolutize(path.as_ref())?;
10542        let content = self.fs.load(&path).await?;
10543        Ok(content)
10544    }
10545}
10546
10547fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
10548    proto::Symbol {
10549        language_server_name: symbol.language_server_name.0.to_string(),
10550        source_worktree_id: symbol.source_worktree_id.to_proto(),
10551        worktree_id: symbol.path.worktree_id.to_proto(),
10552        path: symbol.path.path.to_string_lossy().to_string(),
10553        name: symbol.name.clone(),
10554        kind: unsafe { mem::transmute(symbol.kind) },
10555        start: Some(proto::PointUtf16 {
10556            row: symbol.range.start.0.row,
10557            column: symbol.range.start.0.column,
10558        }),
10559        end: Some(proto::PointUtf16 {
10560            row: symbol.range.end.0.row,
10561            column: symbol.range.end.0.column,
10562        }),
10563        signature: symbol.signature.to_vec(),
10564    }
10565}
10566
10567fn relativize_path(base: &Path, path: &Path) -> PathBuf {
10568    let mut path_components = path.components();
10569    let mut base_components = base.components();
10570    let mut components: Vec<Component> = Vec::new();
10571    loop {
10572        match (path_components.next(), base_components.next()) {
10573            (None, None) => break,
10574            (Some(a), None) => {
10575                components.push(a);
10576                components.extend(path_components.by_ref());
10577                break;
10578            }
10579            (None, _) => components.push(Component::ParentDir),
10580            (Some(a), Some(b)) if components.is_empty() && a == b => (),
10581            (Some(a), Some(Component::CurDir)) => components.push(a),
10582            (Some(a), Some(_)) => {
10583                components.push(Component::ParentDir);
10584                for _ in base_components {
10585                    components.push(Component::ParentDir);
10586                }
10587                components.push(a);
10588                components.extend(path_components.by_ref());
10589                break;
10590            }
10591        }
10592    }
10593    components.iter().map(|c| c.as_os_str()).collect()
10594}
10595
10596fn resolve_path(base: &Path, path: &Path) -> PathBuf {
10597    let mut result = base.to_path_buf();
10598    for component in path.components() {
10599        match component {
10600            Component::ParentDir => {
10601                result.pop();
10602            }
10603            Component::CurDir => (),
10604            _ => result.push(component),
10605        }
10606    }
10607    result
10608}
10609
10610impl Item for Buffer {
10611    fn try_open(
10612        project: &Model<Project>,
10613        path: &ProjectPath,
10614        cx: &mut AppContext,
10615    ) -> Option<Task<Result<Model<Self>>>> {
10616        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
10617    }
10618
10619    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
10620        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
10621    }
10622
10623    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
10624        File::from_dyn(self.file()).map(|file| ProjectPath {
10625            worktree_id: file.worktree_id(cx),
10626            path: file.path().clone(),
10627        })
10628    }
10629}
10630
10631impl Completion {
10632    /// A key that can be used to sort completions when displaying
10633    /// them to the user.
10634    pub fn sort_key(&self) -> (usize, &str) {
10635        let kind_key = match self.lsp_completion.kind {
10636            Some(lsp::CompletionItemKind::KEYWORD) => 0,
10637            Some(lsp::CompletionItemKind::VARIABLE) => 1,
10638            _ => 2,
10639        };
10640        (kind_key, &self.label.text[self.label.filter_range.clone()])
10641    }
10642
10643    /// Whether this completion is a snippet.
10644    pub fn is_snippet(&self) -> bool {
10645        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
10646    }
10647}
10648
10649async fn wait_for_loading_buffer(
10650    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
10651) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
10652    loop {
10653        if let Some(result) = receiver.borrow().as_ref() {
10654            match result {
10655                Ok(buffer) => return Ok(buffer.to_owned()),
10656                Err(e) => return Err(e.to_owned()),
10657            }
10658        }
10659        receiver.next().await;
10660    }
10661}
10662
10663fn include_text(server: &lsp::LanguageServer) -> bool {
10664    server
10665        .capabilities()
10666        .text_document_sync
10667        .as_ref()
10668        .and_then(|sync| match sync {
10669            lsp::TextDocumentSyncCapability::Kind(_) => None,
10670            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
10671        })
10672        .and_then(|save_options| match save_options {
10673            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
10674            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
10675        })
10676        .unwrap_or(false)
10677}
10678
10679async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
10680    let marker = "ZED_SHELL_START";
10681    let shell = env::var("SHELL").context(
10682        "SHELL environment variable is not assigned so we can't source login environment variables",
10683    )?;
10684
10685    // What we're doing here is to spawn a shell and then `cd` into
10686    // the project directory to get the env in there as if the user
10687    // `cd`'d into it. We do that because tools like direnv, asdf, ...
10688    // hook into `cd` and only set up the env after that.
10689    //
10690    // In certain shells we need to execute additional_command in order to
10691    // trigger the behavior of direnv, etc.
10692    //
10693    //
10694    // The `exit 0` is the result of hours of debugging, trying to find out
10695    // why running this command here, without `exit 0`, would mess
10696    // up signal process for our process so that `ctrl-c` doesn't work
10697    // anymore.
10698    //
10699    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
10700    // do that, but it does, and `exit 0` helps.
10701    let additional_command = PathBuf::from(&shell)
10702        .file_name()
10703        .and_then(|f| f.to_str())
10704        .and_then(|shell| match shell {
10705            "fish" => Some("emit fish_prompt;"),
10706            _ => None,
10707        });
10708
10709    let command = format!(
10710        "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
10711        dir.display(),
10712        additional_command.unwrap_or("")
10713    );
10714
10715    let output = smol::process::Command::new(&shell)
10716        .args(["-i", "-c", &command])
10717        .output()
10718        .await
10719        .context("failed to spawn login shell to source login environment variables")?;
10720
10721    anyhow::ensure!(
10722        output.status.success(),
10723        "login shell exited with error {:?}",
10724        output.status
10725    );
10726
10727    let stdout = String::from_utf8_lossy(&output.stdout);
10728    let env_output_start = stdout.find(marker).ok_or_else(|| {
10729        anyhow!(
10730            "failed to parse output of `env` command in login shell: {}",
10731            stdout
10732        )
10733    })?;
10734
10735    let mut parsed_env = HashMap::default();
10736    let env_output = &stdout[env_output_start + marker.len()..];
10737
10738    parse_env_output(env_output, |key, value| {
10739        parsed_env.insert(key, value);
10740    });
10741
10742    Ok(parsed_env)
10743}
10744
10745fn serialize_blame_buffer_response(blame: git::blame::Blame) -> proto::BlameBufferResponse {
10746    let entries = blame
10747        .entries
10748        .into_iter()
10749        .map(|entry| proto::BlameEntry {
10750            sha: entry.sha.as_bytes().into(),
10751            start_line: entry.range.start,
10752            end_line: entry.range.end,
10753            original_line_number: entry.original_line_number,
10754            author: entry.author.clone(),
10755            author_mail: entry.author_mail.clone(),
10756            author_time: entry.author_time,
10757            author_tz: entry.author_tz.clone(),
10758            committer: entry.committer.clone(),
10759            committer_mail: entry.committer_mail.clone(),
10760            committer_time: entry.committer_time,
10761            committer_tz: entry.committer_tz.clone(),
10762            summary: entry.summary.clone(),
10763            previous: entry.previous.clone(),
10764            filename: entry.filename.clone(),
10765        })
10766        .collect::<Vec<_>>();
10767
10768    let messages = blame
10769        .messages
10770        .into_iter()
10771        .map(|(oid, message)| proto::CommitMessage {
10772            oid: oid.as_bytes().into(),
10773            message,
10774        })
10775        .collect::<Vec<_>>();
10776
10777    let permalinks = blame
10778        .permalinks
10779        .into_iter()
10780        .map(|(oid, url)| proto::CommitPermalink {
10781            oid: oid.as_bytes().into(),
10782            permalink: url.to_string(),
10783        })
10784        .collect::<Vec<_>>();
10785
10786    proto::BlameBufferResponse {
10787        entries,
10788        messages,
10789        permalinks,
10790        remote_url: blame.remote_url,
10791    }
10792}
10793
10794fn deserialize_blame_buffer_response(response: proto::BlameBufferResponse) -> git::blame::Blame {
10795    let entries = response
10796        .entries
10797        .into_iter()
10798        .filter_map(|entry| {
10799            Some(git::blame::BlameEntry {
10800                sha: git::Oid::from_bytes(&entry.sha).ok()?,
10801                range: entry.start_line..entry.end_line,
10802                original_line_number: entry.original_line_number,
10803                committer: entry.committer,
10804                committer_time: entry.committer_time,
10805                committer_tz: entry.committer_tz,
10806                committer_mail: entry.committer_mail,
10807                author: entry.author,
10808                author_mail: entry.author_mail,
10809                author_time: entry.author_time,
10810                author_tz: entry.author_tz,
10811                summary: entry.summary,
10812                previous: entry.previous,
10813                filename: entry.filename,
10814            })
10815        })
10816        .collect::<Vec<_>>();
10817
10818    let messages = response
10819        .messages
10820        .into_iter()
10821        .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
10822        .collect::<HashMap<_, _>>();
10823
10824    let permalinks = response
10825        .permalinks
10826        .into_iter()
10827        .filter_map(|permalink| {
10828            Some((
10829                git::Oid::from_bytes(&permalink.oid).ok()?,
10830                Url::from_str(&permalink.permalink).ok()?,
10831            ))
10832        })
10833        .collect::<HashMap<_, _>>();
10834
10835    Blame {
10836        entries,
10837        permalinks,
10838        messages,
10839        remote_url: response.remote_url,
10840    }
10841}
10842
10843fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
10844    hover
10845        .contents
10846        .retain(|hover_block| !hover_block.text.trim().is_empty());
10847    if hover.contents.is_empty() {
10848        None
10849    } else {
10850        Some(hover)
10851    }
10852}
10853
10854#[derive(Debug)]
10855pub struct NoRepositoryError {}
10856
10857impl std::fmt::Display for NoRepositoryError {
10858    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10859        write!(f, "no git repository for worktree found")
10860    }
10861}
10862
10863impl std::error::Error for NoRepositoryError {}