project.rs

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