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