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