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