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