project.rs

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