project.rs

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