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