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
 7860                                        .repo()
 7861                                        .lock()
 7862                                        .load_index_text(&relative_path)
 7863                                };
 7864                                Some((buffer, base_text))
 7865                            }
 7866                        })
 7867                        .collect::<FuturesUnordered<_>>();
 7868
 7869                    let mut diff_bases = Vec::with_capacity(diff_base_tasks.len());
 7870                    while let Some(diff_base) = diff_base_tasks.next().await {
 7871                        if let Some(diff_base) = diff_base {
 7872                            diff_bases.push(diff_base);
 7873                        }
 7874                    }
 7875                    diff_bases
 7876                })
 7877                .await;
 7878
 7879            // Assign the new diff bases on all of the buffers.
 7880            for (buffer, diff_base) in diff_bases_by_buffer {
 7881                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
 7882                    buffer.set_diff_base(diff_base.clone(), cx);
 7883                    buffer.remote_id().into()
 7884                })?;
 7885                if let Some(project_id) = remote_id {
 7886                    client
 7887                        .send(proto::UpdateDiffBase {
 7888                            project_id,
 7889                            buffer_id,
 7890                            diff_base,
 7891                        })
 7892                        .log_err();
 7893                }
 7894            }
 7895
 7896            anyhow::Ok(())
 7897        })
 7898        .detach();
 7899    }
 7900
 7901    fn update_local_worktree_settings(
 7902        &mut self,
 7903        worktree: &Model<Worktree>,
 7904        changes: &UpdatedEntriesSet,
 7905        cx: &mut ModelContext<Self>,
 7906    ) {
 7907        if worktree.read(cx).as_local().is_none() {
 7908            return;
 7909        }
 7910        let project_id = self.remote_id();
 7911        let worktree_id = worktree.entity_id();
 7912        let remote_worktree_id = worktree.read(cx).id();
 7913
 7914        let mut settings_contents = Vec::new();
 7915        for (path, _, change) in changes.iter() {
 7916            let removed = change == &PathChange::Removed;
 7917            let abs_path = match worktree.read(cx).absolutize(path) {
 7918                Ok(abs_path) => abs_path,
 7919                Err(e) => {
 7920                    log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
 7921                    continue;
 7922                }
 7923            };
 7924
 7925            if abs_path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
 7926                let settings_dir = Arc::from(
 7927                    path.ancestors()
 7928                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
 7929                        .unwrap(),
 7930                );
 7931                let fs = self.fs.clone();
 7932                settings_contents.push(async move {
 7933                    (
 7934                        settings_dir,
 7935                        if removed {
 7936                            None
 7937                        } else {
 7938                            Some(async move { fs.load(&abs_path).await }.await)
 7939                        },
 7940                    )
 7941                });
 7942            } else if abs_path.ends_with(&*LOCAL_TASKS_RELATIVE_PATH) {
 7943                self.task_inventory().update(cx, |task_inventory, cx| {
 7944                    if removed {
 7945                        task_inventory.remove_local_static_source(&abs_path);
 7946                    } else {
 7947                        let fs = self.fs.clone();
 7948                        let task_abs_path = abs_path.clone();
 7949                        let tasks_file_rx =
 7950                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7951                        task_inventory.add_source(
 7952                            TaskSourceKind::Worktree {
 7953                                id: remote_worktree_id,
 7954                                abs_path,
 7955                                id_base: "local_tasks_for_worktree".into(),
 7956                            },
 7957                            |tx, cx| StaticSource::new(TrackedFile::new(tasks_file_rx, tx, cx)),
 7958                            cx,
 7959                        );
 7960                    }
 7961                })
 7962            } else if abs_path.ends_with(&*LOCAL_VSCODE_TASKS_RELATIVE_PATH) {
 7963                self.task_inventory().update(cx, |task_inventory, cx| {
 7964                    if removed {
 7965                        task_inventory.remove_local_static_source(&abs_path);
 7966                    } else {
 7967                        let fs = self.fs.clone();
 7968                        let task_abs_path = abs_path.clone();
 7969                        let tasks_file_rx =
 7970                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7971                        task_inventory.add_source(
 7972                            TaskSourceKind::Worktree {
 7973                                id: remote_worktree_id,
 7974                                abs_path,
 7975                                id_base: "local_vscode_tasks_for_worktree".into(),
 7976                            },
 7977                            |tx, cx| {
 7978                                StaticSource::new(TrackedFile::new_convertible::<
 7979                                    task::VsCodeTaskFile,
 7980                                >(
 7981                                    tasks_file_rx, tx, cx
 7982                                ))
 7983                            },
 7984                            cx,
 7985                        );
 7986                    }
 7987                })
 7988            }
 7989        }
 7990
 7991        if settings_contents.is_empty() {
 7992            return;
 7993        }
 7994
 7995        let client = self.client.clone();
 7996        cx.spawn(move |_, cx| async move {
 7997            let settings_contents: Vec<(Arc<Path>, _)> =
 7998                futures::future::join_all(settings_contents).await;
 7999            cx.update(|cx| {
 8000                cx.update_global::<SettingsStore, _>(|store, cx| {
 8001                    for (directory, file_content) in settings_contents {
 8002                        let file_content = file_content.and_then(|content| content.log_err());
 8003                        store
 8004                            .set_local_settings(
 8005                                worktree_id.as_u64() as usize,
 8006                                directory.clone(),
 8007                                file_content.as_deref(),
 8008                                cx,
 8009                            )
 8010                            .log_err();
 8011                        if let Some(remote_id) = project_id {
 8012                            client
 8013                                .send(proto::UpdateWorktreeSettings {
 8014                                    project_id: remote_id,
 8015                                    worktree_id: remote_worktree_id.to_proto(),
 8016                                    path: directory.to_string_lossy().into_owned(),
 8017                                    content: file_content,
 8018                                })
 8019                                .log_err();
 8020                        }
 8021                    }
 8022                });
 8023            })
 8024            .ok();
 8025        })
 8026        .detach();
 8027    }
 8028
 8029    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
 8030        let new_active_entry = entry.and_then(|project_path| {
 8031            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 8032            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
 8033            Some(entry.id)
 8034        });
 8035        if new_active_entry != self.active_entry {
 8036            self.active_entry = new_active_entry;
 8037            cx.emit(Event::ActiveEntryChanged(new_active_entry));
 8038        }
 8039    }
 8040
 8041    pub fn language_servers_running_disk_based_diagnostics(
 8042        &self,
 8043    ) -> impl Iterator<Item = LanguageServerId> + '_ {
 8044        self.language_server_statuses
 8045            .iter()
 8046            .filter_map(|(id, status)| {
 8047                if status.has_pending_diagnostic_updates {
 8048                    Some(*id)
 8049                } else {
 8050                    None
 8051                }
 8052            })
 8053    }
 8054
 8055    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
 8056        let mut summary = DiagnosticSummary::default();
 8057        for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
 8058            summary.error_count += path_summary.error_count;
 8059            summary.warning_count += path_summary.warning_count;
 8060        }
 8061        summary
 8062    }
 8063
 8064    pub fn diagnostic_summaries<'a>(
 8065        &'a self,
 8066        include_ignored: bool,
 8067        cx: &'a AppContext,
 8068    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
 8069        self.visible_worktrees(cx).flat_map(move |worktree| {
 8070            let worktree = worktree.read(cx);
 8071            let worktree_id = worktree.id();
 8072            worktree
 8073                .diagnostic_summaries()
 8074                .filter_map(move |(path, server_id, summary)| {
 8075                    if include_ignored
 8076                        || worktree
 8077                            .entry_for_path(path.as_ref())
 8078                            .map_or(false, |entry| !entry.is_ignored)
 8079                    {
 8080                        Some((ProjectPath { worktree_id, path }, server_id, summary))
 8081                    } else {
 8082                        None
 8083                    }
 8084                })
 8085        })
 8086    }
 8087
 8088    pub fn disk_based_diagnostics_started(
 8089        &mut self,
 8090        language_server_id: LanguageServerId,
 8091        cx: &mut ModelContext<Self>,
 8092    ) {
 8093        if let Some(language_server_status) =
 8094            self.language_server_statuses.get_mut(&language_server_id)
 8095        {
 8096            language_server_status.has_pending_diagnostic_updates = true;
 8097        }
 8098
 8099        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
 8100        if self.is_local() {
 8101            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 8102                language_server_id,
 8103                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
 8104                    Default::default(),
 8105                ),
 8106            })
 8107            .ok();
 8108        }
 8109    }
 8110
 8111    pub fn disk_based_diagnostics_finished(
 8112        &mut self,
 8113        language_server_id: LanguageServerId,
 8114        cx: &mut ModelContext<Self>,
 8115    ) {
 8116        if let Some(language_server_status) =
 8117            self.language_server_statuses.get_mut(&language_server_id)
 8118        {
 8119            language_server_status.has_pending_diagnostic_updates = false;
 8120        }
 8121
 8122        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
 8123
 8124        if self.is_local() {
 8125            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 8126                language_server_id,
 8127                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
 8128                    Default::default(),
 8129                ),
 8130            })
 8131            .ok();
 8132        }
 8133    }
 8134
 8135    pub fn active_entry(&self) -> Option<ProjectEntryId> {
 8136        self.active_entry
 8137    }
 8138
 8139    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
 8140        self.worktree_for_id(path.worktree_id, cx)?
 8141            .read(cx)
 8142            .entry_for_path(&path.path)
 8143            .cloned()
 8144    }
 8145
 8146    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
 8147        let worktree = self.worktree_for_entry(entry_id, cx)?;
 8148        let worktree = worktree.read(cx);
 8149        let worktree_id = worktree.id();
 8150        let path = worktree.entry_for_id(entry_id)?.path.clone();
 8151        Some(ProjectPath { worktree_id, path })
 8152    }
 8153
 8154    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
 8155        let workspace_root = self
 8156            .worktree_for_id(project_path.worktree_id, cx)?
 8157            .read(cx)
 8158            .abs_path();
 8159        let project_path = project_path.path.as_ref();
 8160
 8161        Some(if project_path == Path::new("") {
 8162            workspace_root.to_path_buf()
 8163        } else {
 8164            workspace_root.join(project_path)
 8165        })
 8166    }
 8167
 8168    pub fn project_path_for_absolute_path(
 8169        &self,
 8170        abs_path: &Path,
 8171        cx: &AppContext,
 8172    ) -> Option<ProjectPath> {
 8173        self.find_local_worktree(abs_path, cx)
 8174            .map(|(worktree, relative_path)| ProjectPath {
 8175                worktree_id: worktree.read(cx).id(),
 8176                path: relative_path.into(),
 8177            })
 8178    }
 8179
 8180    pub fn get_workspace_root(
 8181        &self,
 8182        project_path: &ProjectPath,
 8183        cx: &AppContext,
 8184    ) -> Option<PathBuf> {
 8185        Some(
 8186            self.worktree_for_id(project_path.worktree_id, cx)?
 8187                .read(cx)
 8188                .abs_path()
 8189                .to_path_buf(),
 8190        )
 8191    }
 8192
 8193    pub fn get_repo(
 8194        &self,
 8195        project_path: &ProjectPath,
 8196        cx: &AppContext,
 8197    ) -> Option<Arc<Mutex<dyn GitRepository>>> {
 8198        self.worktree_for_id(project_path.worktree_id, cx)?
 8199            .read(cx)
 8200            .as_local()?
 8201            .snapshot()
 8202            .local_git_repo(&project_path.path)
 8203    }
 8204
 8205    pub fn get_first_worktree_root_repo(
 8206        &self,
 8207        cx: &AppContext,
 8208    ) -> Option<Arc<Mutex<dyn GitRepository>>> {
 8209        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
 8210        let root_entry = worktree.root_git_entry()?;
 8211
 8212        worktree.get_local_repo(&root_entry)?.repo().clone().into()
 8213    }
 8214
 8215    pub fn blame_buffer(
 8216        &self,
 8217        buffer: &Model<Buffer>,
 8218        version: Option<clock::Global>,
 8219        cx: &AppContext,
 8220    ) -> Task<Result<Blame>> {
 8221        if self.is_local() {
 8222            let blame_params = maybe!({
 8223                let buffer = buffer.read(cx);
 8224                let buffer_project_path = buffer
 8225                    .project_path(cx)
 8226                    .context("failed to get buffer project path")?;
 8227
 8228                let worktree = self
 8229                    .worktree_for_id(buffer_project_path.worktree_id, cx)
 8230                    .context("failed to get worktree")?
 8231                    .read(cx)
 8232                    .as_local()
 8233                    .context("worktree was not local")?
 8234                    .snapshot();
 8235
 8236                let (repo_entry, local_repo_entry) =
 8237                    match worktree.repo_for_path(&buffer_project_path.path) {
 8238                        Some(repo_for_path) => repo_for_path,
 8239                        None => anyhow::bail!(NoRepositoryError {}),
 8240                    };
 8241
 8242                let relative_path = repo_entry
 8243                    .relativize(&worktree, &buffer_project_path.path)
 8244                    .context("failed to relativize buffer path")?;
 8245
 8246                let repo = local_repo_entry.repo().clone();
 8247
 8248                let content = match version {
 8249                    Some(version) => buffer.rope_for_version(&version).clone(),
 8250                    None => buffer.as_rope().clone(),
 8251                };
 8252
 8253                anyhow::Ok((repo, relative_path, content))
 8254            });
 8255
 8256            cx.background_executor().spawn(async move {
 8257                let (repo, relative_path, content) = blame_params?;
 8258                let lock = repo.lock();
 8259                lock.blame(&relative_path, content)
 8260                    .with_context(|| format!("Failed to blame {:?}", relative_path.0))
 8261            })
 8262        } else {
 8263            let project_id = self.remote_id();
 8264            let buffer_id = buffer.read(cx).remote_id();
 8265            let client = self.client.clone();
 8266            let version = buffer.read(cx).version();
 8267
 8268            cx.spawn(|_| async move {
 8269                let project_id = project_id.context("unable to get project id for buffer")?;
 8270                let response = client
 8271                    .request(proto::BlameBuffer {
 8272                        project_id,
 8273                        buffer_id: buffer_id.into(),
 8274                        version: serialize_version(&version),
 8275                    })
 8276                    .await?;
 8277
 8278                Ok(deserialize_blame_buffer_response(response))
 8279            })
 8280        }
 8281    }
 8282
 8283    // RPC message handlers
 8284
 8285    async fn handle_blame_buffer(
 8286        this: Model<Self>,
 8287        envelope: TypedEnvelope<proto::BlameBuffer>,
 8288        _: Arc<Client>,
 8289        mut cx: AsyncAppContext,
 8290    ) -> Result<proto::BlameBufferResponse> {
 8291        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8292        let version = deserialize_version(&envelope.payload.version);
 8293
 8294        let buffer = this.update(&mut cx, |this, _cx| {
 8295            this.opened_buffers
 8296                .get(&buffer_id)
 8297                .and_then(|buffer| buffer.upgrade())
 8298                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 8299        })??;
 8300
 8301        buffer
 8302            .update(&mut cx, |buffer, _| {
 8303                buffer.wait_for_version(version.clone())
 8304            })?
 8305            .await?;
 8306
 8307        let blame = this
 8308            .update(&mut cx, |this, cx| {
 8309                this.blame_buffer(&buffer, Some(version), cx)
 8310            })?
 8311            .await?;
 8312
 8313        Ok(serialize_blame_buffer_response(blame))
 8314    }
 8315
 8316    async fn handle_multi_lsp_query(
 8317        project: Model<Self>,
 8318        envelope: TypedEnvelope<proto::MultiLspQuery>,
 8319        _: Arc<Client>,
 8320        mut cx: AsyncAppContext,
 8321    ) -> Result<proto::MultiLspQueryResponse> {
 8322        let sender_id = envelope.original_sender_id()?;
 8323        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8324        let version = deserialize_version(&envelope.payload.version);
 8325        let buffer = project.update(&mut cx, |project, _cx| {
 8326            project
 8327                .opened_buffers
 8328                .get(&buffer_id)
 8329                .and_then(|buffer| buffer.upgrade())
 8330                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 8331        })??;
 8332        buffer
 8333            .update(&mut cx, |buffer, _| {
 8334                buffer.wait_for_version(version.clone())
 8335            })?
 8336            .await?;
 8337        let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
 8338        match envelope
 8339            .payload
 8340            .strategy
 8341            .context("invalid request without the strategy")?
 8342        {
 8343            proto::multi_lsp_query::Strategy::All(_) => {
 8344                // currently, there's only one multiple language servers query strategy,
 8345                // so just ensure it's specified correctly
 8346            }
 8347        }
 8348        match envelope.payload.request {
 8349            Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
 8350                let get_hover =
 8351                    GetHover::from_proto(get_hover, project.clone(), buffer.clone(), cx.clone())
 8352                        .await?;
 8353                let all_hovers = project
 8354                    .update(&mut cx, |project, cx| {
 8355                        project.request_multiple_lsp_locally(
 8356                            &buffer,
 8357                            Some(get_hover.position),
 8358                            |server_capabilities| match server_capabilities.hover_provider {
 8359                                Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 8360                                Some(lsp::HoverProviderCapability::Options(_)) => true,
 8361                                None => false,
 8362                            },
 8363                            get_hover,
 8364                            cx,
 8365                        )
 8366                    })?
 8367                    .await
 8368                    .into_iter()
 8369                    .filter_map(|hover| remove_empty_hover_blocks(hover?));
 8370                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8371                    responses: all_hovers
 8372                        .map(|hover| proto::LspResponse {
 8373                            response: Some(proto::lsp_response::Response::GetHoverResponse(
 8374                                GetHover::response_to_proto(
 8375                                    Some(hover),
 8376                                    project,
 8377                                    sender_id,
 8378                                    &buffer_version,
 8379                                    cx,
 8380                                ),
 8381                            )),
 8382                        })
 8383                        .collect(),
 8384                })
 8385            }
 8386            Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
 8387                let get_code_actions = GetCodeActions::from_proto(
 8388                    get_code_actions,
 8389                    project.clone(),
 8390                    buffer.clone(),
 8391                    cx.clone(),
 8392                )
 8393                .await?;
 8394
 8395                let all_actions = project
 8396                    .update(&mut cx, |project, cx| {
 8397                        project.request_multiple_lsp_locally(
 8398                            &buffer,
 8399                            Some(get_code_actions.range.start),
 8400                            GetCodeActions::supports_code_actions,
 8401                            get_code_actions,
 8402                            cx,
 8403                        )
 8404                    })?
 8405                    .await
 8406                    .into_iter();
 8407
 8408                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8409                    responses: all_actions
 8410                        .map(|code_actions| proto::LspResponse {
 8411                            response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
 8412                                GetCodeActions::response_to_proto(
 8413                                    code_actions,
 8414                                    project,
 8415                                    sender_id,
 8416                                    &buffer_version,
 8417                                    cx,
 8418                                ),
 8419                            )),
 8420                        })
 8421                        .collect(),
 8422                })
 8423            }
 8424            None => anyhow::bail!("empty multi lsp query request"),
 8425        }
 8426    }
 8427
 8428    async fn handle_unshare_project(
 8429        this: Model<Self>,
 8430        _: TypedEnvelope<proto::UnshareProject>,
 8431        _: Arc<Client>,
 8432        mut cx: AsyncAppContext,
 8433    ) -> Result<()> {
 8434        this.update(&mut cx, |this, cx| {
 8435            if this.is_local() {
 8436                this.unshare(cx)?;
 8437            } else {
 8438                this.disconnected_from_host(cx);
 8439            }
 8440            Ok(())
 8441        })?
 8442    }
 8443
 8444    async fn handle_add_collaborator(
 8445        this: Model<Self>,
 8446        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
 8447        _: Arc<Client>,
 8448        mut cx: AsyncAppContext,
 8449    ) -> Result<()> {
 8450        let collaborator = envelope
 8451            .payload
 8452            .collaborator
 8453            .take()
 8454            .ok_or_else(|| anyhow!("empty collaborator"))?;
 8455
 8456        let collaborator = Collaborator::from_proto(collaborator)?;
 8457        this.update(&mut cx, |this, cx| {
 8458            this.shared_buffers.remove(&collaborator.peer_id);
 8459            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
 8460            this.collaborators
 8461                .insert(collaborator.peer_id, collaborator);
 8462            cx.notify();
 8463        })?;
 8464
 8465        Ok(())
 8466    }
 8467
 8468    async fn handle_update_project_collaborator(
 8469        this: Model<Self>,
 8470        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
 8471        _: Arc<Client>,
 8472        mut cx: AsyncAppContext,
 8473    ) -> Result<()> {
 8474        let old_peer_id = envelope
 8475            .payload
 8476            .old_peer_id
 8477            .ok_or_else(|| anyhow!("missing old peer id"))?;
 8478        let new_peer_id = envelope
 8479            .payload
 8480            .new_peer_id
 8481            .ok_or_else(|| anyhow!("missing new peer id"))?;
 8482        this.update(&mut cx, |this, cx| {
 8483            let collaborator = this
 8484                .collaborators
 8485                .remove(&old_peer_id)
 8486                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
 8487            let is_host = collaborator.replica_id == 0;
 8488            this.collaborators.insert(new_peer_id, collaborator);
 8489
 8490            let buffers = this.shared_buffers.remove(&old_peer_id);
 8491            log::info!(
 8492                "peer {} became {}. moving buffers {:?}",
 8493                old_peer_id,
 8494                new_peer_id,
 8495                &buffers
 8496            );
 8497            if let Some(buffers) = buffers {
 8498                this.shared_buffers.insert(new_peer_id, buffers);
 8499            }
 8500
 8501            if is_host {
 8502                this.opened_buffers
 8503                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
 8504                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 8505                    .unwrap();
 8506            }
 8507
 8508            cx.emit(Event::CollaboratorUpdated {
 8509                old_peer_id,
 8510                new_peer_id,
 8511            });
 8512            cx.notify();
 8513            Ok(())
 8514        })?
 8515    }
 8516
 8517    async fn handle_remove_collaborator(
 8518        this: Model<Self>,
 8519        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
 8520        _: Arc<Client>,
 8521        mut cx: AsyncAppContext,
 8522    ) -> Result<()> {
 8523        this.update(&mut cx, |this, cx| {
 8524            let peer_id = envelope
 8525                .payload
 8526                .peer_id
 8527                .ok_or_else(|| anyhow!("invalid peer id"))?;
 8528            let replica_id = this
 8529                .collaborators
 8530                .remove(&peer_id)
 8531                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
 8532                .replica_id;
 8533            for buffer in this.opened_buffers.values() {
 8534                if let Some(buffer) = buffer.upgrade() {
 8535                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
 8536                }
 8537            }
 8538            this.shared_buffers.remove(&peer_id);
 8539
 8540            cx.emit(Event::CollaboratorLeft(peer_id));
 8541            cx.notify();
 8542            Ok(())
 8543        })?
 8544    }
 8545
 8546    async fn handle_update_project(
 8547        this: Model<Self>,
 8548        envelope: TypedEnvelope<proto::UpdateProject>,
 8549        _: Arc<Client>,
 8550        mut cx: AsyncAppContext,
 8551    ) -> Result<()> {
 8552        this.update(&mut cx, |this, cx| {
 8553            // Don't handle messages that were sent before the response to us joining the project
 8554            if envelope.message_id > this.join_project_response_message_id {
 8555                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
 8556            }
 8557            Ok(())
 8558        })?
 8559    }
 8560
 8561    async fn handle_update_worktree(
 8562        this: Model<Self>,
 8563        envelope: TypedEnvelope<proto::UpdateWorktree>,
 8564        _: Arc<Client>,
 8565        mut cx: AsyncAppContext,
 8566    ) -> Result<()> {
 8567        this.update(&mut cx, |this, cx| {
 8568            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8569            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8570                worktree.update(cx, |worktree, _| {
 8571                    let worktree = worktree.as_remote_mut().unwrap();
 8572                    worktree.update_from_remote(envelope.payload);
 8573                });
 8574            }
 8575            Ok(())
 8576        })?
 8577    }
 8578
 8579    async fn handle_update_worktree_settings(
 8580        this: Model<Self>,
 8581        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
 8582        _: Arc<Client>,
 8583        mut cx: AsyncAppContext,
 8584    ) -> Result<()> {
 8585        this.update(&mut cx, |this, cx| {
 8586            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8587            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8588                cx.update_global::<SettingsStore, _>(|store, cx| {
 8589                    store
 8590                        .set_local_settings(
 8591                            worktree.entity_id().as_u64() as usize,
 8592                            PathBuf::from(&envelope.payload.path).into(),
 8593                            envelope.payload.content.as_deref(),
 8594                            cx,
 8595                        )
 8596                        .log_err();
 8597                });
 8598            }
 8599            Ok(())
 8600        })?
 8601    }
 8602
 8603    async fn handle_create_project_entry(
 8604        this: Model<Self>,
 8605        envelope: TypedEnvelope<proto::CreateProjectEntry>,
 8606        _: Arc<Client>,
 8607        mut cx: AsyncAppContext,
 8608    ) -> Result<proto::ProjectEntryResponse> {
 8609        let worktree = this.update(&mut cx, |this, cx| {
 8610            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8611            this.worktree_for_id(worktree_id, cx)
 8612                .ok_or_else(|| anyhow!("worktree not found"))
 8613        })??;
 8614        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8615        let entry = worktree
 8616            .update(&mut cx, |worktree, cx| {
 8617                let worktree = worktree.as_local_mut().unwrap();
 8618                let path = PathBuf::from(envelope.payload.path);
 8619                worktree.create_entry(path, envelope.payload.is_directory, cx)
 8620            })?
 8621            .await?;
 8622        Ok(proto::ProjectEntryResponse {
 8623            entry: entry.as_ref().map(|e| e.into()),
 8624            worktree_scan_id: worktree_scan_id as u64,
 8625        })
 8626    }
 8627
 8628    async fn handle_rename_project_entry(
 8629        this: Model<Self>,
 8630        envelope: TypedEnvelope<proto::RenameProjectEntry>,
 8631        _: Arc<Client>,
 8632        mut cx: AsyncAppContext,
 8633    ) -> Result<proto::ProjectEntryResponse> {
 8634        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8635        let worktree = this.update(&mut cx, |this, cx| {
 8636            this.worktree_for_entry(entry_id, cx)
 8637                .ok_or_else(|| anyhow!("worktree not found"))
 8638        })??;
 8639        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8640        let entry = worktree
 8641            .update(&mut cx, |worktree, cx| {
 8642                let new_path = PathBuf::from(envelope.payload.new_path);
 8643                worktree
 8644                    .as_local_mut()
 8645                    .unwrap()
 8646                    .rename_entry(entry_id, new_path, cx)
 8647            })?
 8648            .await?;
 8649        Ok(proto::ProjectEntryResponse {
 8650            entry: entry.as_ref().map(|e| e.into()),
 8651            worktree_scan_id: worktree_scan_id as u64,
 8652        })
 8653    }
 8654
 8655    async fn handle_copy_project_entry(
 8656        this: Model<Self>,
 8657        envelope: TypedEnvelope<proto::CopyProjectEntry>,
 8658        _: Arc<Client>,
 8659        mut cx: AsyncAppContext,
 8660    ) -> Result<proto::ProjectEntryResponse> {
 8661        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8662        let worktree = this.update(&mut cx, |this, cx| {
 8663            this.worktree_for_entry(entry_id, cx)
 8664                .ok_or_else(|| anyhow!("worktree not found"))
 8665        })??;
 8666        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8667        let entry = worktree
 8668            .update(&mut cx, |worktree, cx| {
 8669                let new_path = PathBuf::from(envelope.payload.new_path);
 8670                worktree
 8671                    .as_local_mut()
 8672                    .unwrap()
 8673                    .copy_entry(entry_id, new_path, cx)
 8674            })?
 8675            .await?;
 8676        Ok(proto::ProjectEntryResponse {
 8677            entry: entry.as_ref().map(|e| e.into()),
 8678            worktree_scan_id: worktree_scan_id as u64,
 8679        })
 8680    }
 8681
 8682    async fn handle_delete_project_entry(
 8683        this: Model<Self>,
 8684        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
 8685        _: Arc<Client>,
 8686        mut cx: AsyncAppContext,
 8687    ) -> Result<proto::ProjectEntryResponse> {
 8688        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8689        let trash = envelope.payload.use_trash;
 8690
 8691        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
 8692
 8693        let worktree = this.update(&mut cx, |this, cx| {
 8694            this.worktree_for_entry(entry_id, cx)
 8695                .ok_or_else(|| anyhow!("worktree not found"))
 8696        })??;
 8697        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8698        worktree
 8699            .update(&mut cx, |worktree, cx| {
 8700                worktree
 8701                    .as_local_mut()
 8702                    .unwrap()
 8703                    .delete_entry(entry_id, trash, cx)
 8704                    .ok_or_else(|| anyhow!("invalid entry"))
 8705            })??
 8706            .await?;
 8707        Ok(proto::ProjectEntryResponse {
 8708            entry: None,
 8709            worktree_scan_id: worktree_scan_id as u64,
 8710        })
 8711    }
 8712
 8713    async fn handle_expand_project_entry(
 8714        this: Model<Self>,
 8715        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
 8716        _: Arc<Client>,
 8717        mut cx: AsyncAppContext,
 8718    ) -> Result<proto::ExpandProjectEntryResponse> {
 8719        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8720        let worktree = this
 8721            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
 8722            .ok_or_else(|| anyhow!("invalid request"))?;
 8723        worktree
 8724            .update(&mut cx, |worktree, cx| {
 8725                worktree
 8726                    .as_local_mut()
 8727                    .unwrap()
 8728                    .expand_entry(entry_id, cx)
 8729                    .ok_or_else(|| anyhow!("invalid entry"))
 8730            })??
 8731            .await?;
 8732        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
 8733        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
 8734    }
 8735
 8736    async fn handle_update_diagnostic_summary(
 8737        this: Model<Self>,
 8738        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 8739        _: Arc<Client>,
 8740        mut cx: AsyncAppContext,
 8741    ) -> Result<()> {
 8742        this.update(&mut cx, |this, cx| {
 8743            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8744            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8745                if let Some(summary) = envelope.payload.summary {
 8746                    let project_path = ProjectPath {
 8747                        worktree_id,
 8748                        path: Path::new(&summary.path).into(),
 8749                    };
 8750                    worktree.update(cx, |worktree, _| {
 8751                        worktree
 8752                            .as_remote_mut()
 8753                            .unwrap()
 8754                            .update_diagnostic_summary(project_path.path.clone(), &summary);
 8755                    });
 8756                    cx.emit(Event::DiagnosticsUpdated {
 8757                        language_server_id: LanguageServerId(summary.language_server_id as usize),
 8758                        path: project_path,
 8759                    });
 8760                }
 8761            }
 8762            Ok(())
 8763        })?
 8764    }
 8765
 8766    async fn handle_start_language_server(
 8767        this: Model<Self>,
 8768        envelope: TypedEnvelope<proto::StartLanguageServer>,
 8769        _: Arc<Client>,
 8770        mut cx: AsyncAppContext,
 8771    ) -> Result<()> {
 8772        let server = envelope
 8773            .payload
 8774            .server
 8775            .ok_or_else(|| anyhow!("invalid server"))?;
 8776        this.update(&mut cx, |this, cx| {
 8777            this.language_server_statuses.insert(
 8778                LanguageServerId(server.id as usize),
 8779                LanguageServerStatus {
 8780                    name: server.name,
 8781                    pending_work: Default::default(),
 8782                    has_pending_diagnostic_updates: false,
 8783                    progress_tokens: Default::default(),
 8784                },
 8785            );
 8786            cx.notify();
 8787        })?;
 8788        Ok(())
 8789    }
 8790
 8791    async fn handle_update_language_server(
 8792        this: Model<Self>,
 8793        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
 8794        _: Arc<Client>,
 8795        mut cx: AsyncAppContext,
 8796    ) -> Result<()> {
 8797        this.update(&mut cx, |this, cx| {
 8798            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8799
 8800            match envelope
 8801                .payload
 8802                .variant
 8803                .ok_or_else(|| anyhow!("invalid variant"))?
 8804            {
 8805                proto::update_language_server::Variant::WorkStart(payload) => {
 8806                    this.on_lsp_work_start(
 8807                        language_server_id,
 8808                        payload.token,
 8809                        LanguageServerProgress {
 8810                            message: payload.message,
 8811                            percentage: payload.percentage.map(|p| p as usize),
 8812                            last_update_at: Instant::now(),
 8813                        },
 8814                        cx,
 8815                    );
 8816                }
 8817
 8818                proto::update_language_server::Variant::WorkProgress(payload) => {
 8819                    this.on_lsp_work_progress(
 8820                        language_server_id,
 8821                        payload.token,
 8822                        LanguageServerProgress {
 8823                            message: payload.message,
 8824                            percentage: payload.percentage.map(|p| p as usize),
 8825                            last_update_at: Instant::now(),
 8826                        },
 8827                        cx,
 8828                    );
 8829                }
 8830
 8831                proto::update_language_server::Variant::WorkEnd(payload) => {
 8832                    this.on_lsp_work_end(language_server_id, payload.token, cx);
 8833                }
 8834
 8835                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
 8836                    this.disk_based_diagnostics_started(language_server_id, cx);
 8837                }
 8838
 8839                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
 8840                    this.disk_based_diagnostics_finished(language_server_id, cx)
 8841                }
 8842            }
 8843
 8844            Ok(())
 8845        })?
 8846    }
 8847
 8848    async fn handle_update_buffer(
 8849        this: Model<Self>,
 8850        envelope: TypedEnvelope<proto::UpdateBuffer>,
 8851        _: Arc<Client>,
 8852        mut cx: AsyncAppContext,
 8853    ) -> Result<proto::Ack> {
 8854        this.update(&mut cx, |this, cx| {
 8855            let payload = envelope.payload.clone();
 8856            let buffer_id = BufferId::new(payload.buffer_id)?;
 8857            let ops = payload
 8858                .operations
 8859                .into_iter()
 8860                .map(language::proto::deserialize_operation)
 8861                .collect::<Result<Vec<_>, _>>()?;
 8862            let is_remote = this.is_remote();
 8863            match this.opened_buffers.entry(buffer_id) {
 8864                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
 8865                    OpenBuffer::Strong(buffer) => {
 8866                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
 8867                    }
 8868                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
 8869                    OpenBuffer::Weak(_) => {}
 8870                },
 8871                hash_map::Entry::Vacant(e) => {
 8872                    if !is_remote {
 8873                        debug_panic!(
 8874                            "received buffer update from {:?}",
 8875                            envelope.original_sender_id
 8876                        );
 8877                        return Err(anyhow!("received buffer update for non-remote project"));
 8878                    }
 8879                    e.insert(OpenBuffer::Operations(ops));
 8880                }
 8881            }
 8882            Ok(proto::Ack {})
 8883        })?
 8884    }
 8885
 8886    async fn handle_create_buffer_for_peer(
 8887        this: Model<Self>,
 8888        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 8889        _: Arc<Client>,
 8890        mut cx: AsyncAppContext,
 8891    ) -> Result<()> {
 8892        this.update(&mut cx, |this, cx| {
 8893            match envelope
 8894                .payload
 8895                .variant
 8896                .ok_or_else(|| anyhow!("missing variant"))?
 8897            {
 8898                proto::create_buffer_for_peer::Variant::State(mut state) => {
 8899                    let buffer_id = BufferId::new(state.id)?;
 8900
 8901                    let buffer_result = maybe!({
 8902                        let mut buffer_file = None;
 8903                        if let Some(file) = state.file.take() {
 8904                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
 8905                            let worktree =
 8906                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
 8907                                    anyhow!("no worktree found for id {}", file.worktree_id)
 8908                                })?;
 8909                            buffer_file =
 8910                                Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
 8911                                    as Arc<dyn language::File>);
 8912                        }
 8913                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
 8914                    });
 8915
 8916                    match buffer_result {
 8917                        Ok(buffer) => {
 8918                            let buffer = cx.new_model(|_| buffer);
 8919                            this.incomplete_remote_buffers.insert(buffer_id, buffer);
 8920                        }
 8921                        Err(error) => {
 8922                            if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 8923                                for listener in listeners {
 8924                                    listener.send(Err(anyhow!(error.cloned()))).ok();
 8925                                }
 8926                            }
 8927                        }
 8928                    };
 8929                }
 8930                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
 8931                    let buffer_id = BufferId::new(chunk.buffer_id)?;
 8932                    let buffer = this
 8933                        .incomplete_remote_buffers
 8934                        .get(&buffer_id)
 8935                        .cloned()
 8936                        .ok_or_else(|| {
 8937                            anyhow!(
 8938                                "received chunk for buffer {} without initial state",
 8939                                chunk.buffer_id
 8940                            )
 8941                        })?;
 8942
 8943                    let result = maybe!({
 8944                        let operations = chunk
 8945                            .operations
 8946                            .into_iter()
 8947                            .map(language::proto::deserialize_operation)
 8948                            .collect::<Result<Vec<_>>>()?;
 8949                        buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))
 8950                    });
 8951
 8952                    if let Err(error) = result {
 8953                        this.incomplete_remote_buffers.remove(&buffer_id);
 8954                        if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 8955                            for listener in listeners {
 8956                                listener.send(Err(error.cloned())).ok();
 8957                            }
 8958                        }
 8959                    } else {
 8960                        if chunk.is_last {
 8961                            this.incomplete_remote_buffers.remove(&buffer_id);
 8962                            this.register_buffer(&buffer, cx)?;
 8963                        }
 8964                    }
 8965                }
 8966            }
 8967
 8968            Ok(())
 8969        })?
 8970    }
 8971
 8972    async fn handle_update_diff_base(
 8973        this: Model<Self>,
 8974        envelope: TypedEnvelope<proto::UpdateDiffBase>,
 8975        _: Arc<Client>,
 8976        mut cx: AsyncAppContext,
 8977    ) -> Result<()> {
 8978        this.update(&mut cx, |this, cx| {
 8979            let buffer_id = envelope.payload.buffer_id;
 8980            let buffer_id = BufferId::new(buffer_id)?;
 8981            if let Some(buffer) = this
 8982                .opened_buffers
 8983                .get_mut(&buffer_id)
 8984                .and_then(|b| b.upgrade())
 8985                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 8986            {
 8987                buffer.update(cx, |buffer, cx| {
 8988                    buffer.set_diff_base(envelope.payload.diff_base, cx)
 8989                });
 8990            }
 8991            Ok(())
 8992        })?
 8993    }
 8994
 8995    async fn handle_update_buffer_file(
 8996        this: Model<Self>,
 8997        envelope: TypedEnvelope<proto::UpdateBufferFile>,
 8998        _: Arc<Client>,
 8999        mut cx: AsyncAppContext,
 9000    ) -> Result<()> {
 9001        let buffer_id = envelope.payload.buffer_id;
 9002        let buffer_id = BufferId::new(buffer_id)?;
 9003
 9004        this.update(&mut cx, |this, cx| {
 9005            let payload = envelope.payload.clone();
 9006            if let Some(buffer) = this
 9007                .opened_buffers
 9008                .get(&buffer_id)
 9009                .and_then(|b| b.upgrade())
 9010                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 9011            {
 9012                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
 9013                let worktree = this
 9014                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
 9015                    .ok_or_else(|| anyhow!("no such worktree"))?;
 9016                let file = File::from_proto(file, worktree, cx)?;
 9017                buffer.update(cx, |buffer, cx| {
 9018                    buffer.file_updated(Arc::new(file), cx);
 9019                });
 9020                this.detect_language_for_buffer(&buffer, cx);
 9021            }
 9022            Ok(())
 9023        })?
 9024    }
 9025
 9026    async fn handle_save_buffer(
 9027        this: Model<Self>,
 9028        envelope: TypedEnvelope<proto::SaveBuffer>,
 9029        _: Arc<Client>,
 9030        mut cx: AsyncAppContext,
 9031    ) -> Result<proto::BufferSaved> {
 9032        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9033        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
 9034            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
 9035            let buffer = this
 9036                .opened_buffers
 9037                .get(&buffer_id)
 9038                .and_then(|buffer| buffer.upgrade())
 9039                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9040            anyhow::Ok((project_id, buffer))
 9041        })??;
 9042        buffer
 9043            .update(&mut cx, |buffer, _| {
 9044                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 9045            })?
 9046            .await?;
 9047        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
 9048
 9049        if let Some(new_path) = envelope.payload.new_path {
 9050            let new_path = ProjectPath::from_proto(new_path);
 9051            this.update(&mut cx, |this, cx| {
 9052                this.save_buffer_as(buffer.clone(), new_path, cx)
 9053            })?
 9054            .await?;
 9055        } else {
 9056            this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
 9057                .await?;
 9058        }
 9059
 9060        buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
 9061            project_id,
 9062            buffer_id: buffer_id.into(),
 9063            version: serialize_version(buffer.saved_version()),
 9064            mtime: buffer.saved_mtime().map(|time| time.into()),
 9065        })
 9066    }
 9067
 9068    async fn handle_reload_buffers(
 9069        this: Model<Self>,
 9070        envelope: TypedEnvelope<proto::ReloadBuffers>,
 9071        _: Arc<Client>,
 9072        mut cx: AsyncAppContext,
 9073    ) -> Result<proto::ReloadBuffersResponse> {
 9074        let sender_id = envelope.original_sender_id()?;
 9075        let reload = this.update(&mut cx, |this, cx| {
 9076            let mut buffers = HashSet::default();
 9077            for buffer_id in &envelope.payload.buffer_ids {
 9078                let buffer_id = BufferId::new(*buffer_id)?;
 9079                buffers.insert(
 9080                    this.opened_buffers
 9081                        .get(&buffer_id)
 9082                        .and_then(|buffer| buffer.upgrade())
 9083                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 9084                );
 9085            }
 9086            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
 9087        })??;
 9088
 9089        let project_transaction = reload.await?;
 9090        let project_transaction = this.update(&mut cx, |this, cx| {
 9091            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9092        })?;
 9093        Ok(proto::ReloadBuffersResponse {
 9094            transaction: Some(project_transaction),
 9095        })
 9096    }
 9097
 9098    async fn handle_synchronize_buffers(
 9099        this: Model<Self>,
 9100        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
 9101        _: Arc<Client>,
 9102        mut cx: AsyncAppContext,
 9103    ) -> Result<proto::SynchronizeBuffersResponse> {
 9104        let project_id = envelope.payload.project_id;
 9105        let mut response = proto::SynchronizeBuffersResponse {
 9106            buffers: Default::default(),
 9107        };
 9108
 9109        this.update(&mut cx, |this, cx| {
 9110            let Some(guest_id) = envelope.original_sender_id else {
 9111                error!("missing original_sender_id on SynchronizeBuffers request");
 9112                bail!("missing original_sender_id on SynchronizeBuffers request");
 9113            };
 9114
 9115            this.shared_buffers.entry(guest_id).or_default().clear();
 9116            for buffer in envelope.payload.buffers {
 9117                let buffer_id = BufferId::new(buffer.id)?;
 9118                let remote_version = language::proto::deserialize_version(&buffer.version);
 9119                if let Some(buffer) = this.buffer_for_id(buffer_id) {
 9120                    this.shared_buffers
 9121                        .entry(guest_id)
 9122                        .or_default()
 9123                        .insert(buffer_id);
 9124
 9125                    let buffer = buffer.read(cx);
 9126                    response.buffers.push(proto::BufferVersion {
 9127                        id: buffer_id.into(),
 9128                        version: language::proto::serialize_version(&buffer.version),
 9129                    });
 9130
 9131                    let operations = buffer.serialize_ops(Some(remote_version), cx);
 9132                    let client = this.client.clone();
 9133                    if let Some(file) = buffer.file() {
 9134                        client
 9135                            .send(proto::UpdateBufferFile {
 9136                                project_id,
 9137                                buffer_id: buffer_id.into(),
 9138                                file: Some(file.to_proto()),
 9139                            })
 9140                            .log_err();
 9141                    }
 9142
 9143                    client
 9144                        .send(proto::UpdateDiffBase {
 9145                            project_id,
 9146                            buffer_id: buffer_id.into(),
 9147                            diff_base: buffer.diff_base().map(ToString::to_string),
 9148                        })
 9149                        .log_err();
 9150
 9151                    client
 9152                        .send(proto::BufferReloaded {
 9153                            project_id,
 9154                            buffer_id: buffer_id.into(),
 9155                            version: language::proto::serialize_version(buffer.saved_version()),
 9156                            mtime: buffer.saved_mtime().map(|time| time.into()),
 9157                            line_ending: language::proto::serialize_line_ending(
 9158                                buffer.line_ending(),
 9159                            ) as i32,
 9160                        })
 9161                        .log_err();
 9162
 9163                    cx.background_executor()
 9164                        .spawn(
 9165                            async move {
 9166                                let operations = operations.await;
 9167                                for chunk in split_operations(operations) {
 9168                                    client
 9169                                        .request(proto::UpdateBuffer {
 9170                                            project_id,
 9171                                            buffer_id: buffer_id.into(),
 9172                                            operations: chunk,
 9173                                        })
 9174                                        .await?;
 9175                                }
 9176                                anyhow::Ok(())
 9177                            }
 9178                            .log_err(),
 9179                        )
 9180                        .detach();
 9181                }
 9182            }
 9183            Ok(())
 9184        })??;
 9185
 9186        Ok(response)
 9187    }
 9188
 9189    async fn handle_format_buffers(
 9190        this: Model<Self>,
 9191        envelope: TypedEnvelope<proto::FormatBuffers>,
 9192        _: Arc<Client>,
 9193        mut cx: AsyncAppContext,
 9194    ) -> Result<proto::FormatBuffersResponse> {
 9195        let sender_id = envelope.original_sender_id()?;
 9196        let format = this.update(&mut cx, |this, cx| {
 9197            let mut buffers = HashSet::default();
 9198            for buffer_id in &envelope.payload.buffer_ids {
 9199                let buffer_id = BufferId::new(*buffer_id)?;
 9200                buffers.insert(
 9201                    this.opened_buffers
 9202                        .get(&buffer_id)
 9203                        .and_then(|buffer| buffer.upgrade())
 9204                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 9205                );
 9206            }
 9207            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
 9208            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
 9209        })??;
 9210
 9211        let project_transaction = format.await?;
 9212        let project_transaction = this.update(&mut cx, |this, cx| {
 9213            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9214        })?;
 9215        Ok(proto::FormatBuffersResponse {
 9216            transaction: Some(project_transaction),
 9217        })
 9218    }
 9219
 9220    async fn handle_apply_additional_edits_for_completion(
 9221        this: Model<Self>,
 9222        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 9223        _: Arc<Client>,
 9224        mut cx: AsyncAppContext,
 9225    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
 9226        let (buffer, completion) = this.update(&mut cx, |this, _| {
 9227            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9228            let buffer = this
 9229                .opened_buffers
 9230                .get(&buffer_id)
 9231                .and_then(|buffer| buffer.upgrade())
 9232                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9233            let completion = Self::deserialize_completion(
 9234                envelope
 9235                    .payload
 9236                    .completion
 9237                    .ok_or_else(|| anyhow!("invalid completion"))?,
 9238            )?;
 9239            anyhow::Ok((buffer, completion))
 9240        })??;
 9241
 9242        let apply_additional_edits = this.update(&mut cx, |this, cx| {
 9243            this.apply_additional_edits_for_completion(
 9244                buffer,
 9245                Completion {
 9246                    old_range: completion.old_range,
 9247                    new_text: completion.new_text,
 9248                    lsp_completion: completion.lsp_completion,
 9249                    server_id: completion.server_id,
 9250                    documentation: None,
 9251                    label: CodeLabel {
 9252                        text: Default::default(),
 9253                        runs: Default::default(),
 9254                        filter_range: Default::default(),
 9255                    },
 9256                    confirm: None,
 9257                    show_new_completions_on_confirm: false,
 9258                },
 9259                false,
 9260                cx,
 9261            )
 9262        })?;
 9263
 9264        Ok(proto::ApplyCompletionAdditionalEditsResponse {
 9265            transaction: apply_additional_edits
 9266                .await?
 9267                .as_ref()
 9268                .map(language::proto::serialize_transaction),
 9269        })
 9270    }
 9271
 9272    async fn handle_resolve_completion_documentation(
 9273        this: Model<Self>,
 9274        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
 9275        _: Arc<Client>,
 9276        mut cx: AsyncAppContext,
 9277    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
 9278        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
 9279
 9280        let completion = this
 9281            .read_with(&mut cx, |this, _| {
 9282                let id = LanguageServerId(envelope.payload.language_server_id as usize);
 9283                let Some(server) = this.language_server_for_id(id) else {
 9284                    return Err(anyhow!("No language server {id}"));
 9285                };
 9286
 9287                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
 9288            })??
 9289            .await?;
 9290
 9291        let mut documentation_is_markdown = false;
 9292        let documentation = match completion.documentation {
 9293            Some(lsp::Documentation::String(text)) => text,
 9294
 9295            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
 9296                documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
 9297                value
 9298            }
 9299
 9300            _ => String::new(),
 9301        };
 9302
 9303        // If we have a new buffer_id, that means we're talking to a new client
 9304        // and want to check for new text_edits in the completion too.
 9305        let mut old_start = None;
 9306        let mut old_end = None;
 9307        let mut new_text = String::default();
 9308        if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
 9309            let buffer_snapshot = this.update(&mut cx, |this, cx| {
 9310                let buffer = this
 9311                    .opened_buffers
 9312                    .get(&buffer_id)
 9313                    .and_then(|buffer| buffer.upgrade())
 9314                    .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9315                anyhow::Ok(buffer.read(cx).snapshot())
 9316            })??;
 9317
 9318            if let Some(text_edit) = completion.text_edit.as_ref() {
 9319                let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
 9320
 9321                if let Some((old_range, mut text_edit_new_text)) = edit {
 9322                    LineEnding::normalize(&mut text_edit_new_text);
 9323
 9324                    new_text = text_edit_new_text;
 9325                    old_start = Some(serialize_anchor(&old_range.start));
 9326                    old_end = Some(serialize_anchor(&old_range.end));
 9327                }
 9328            }
 9329        }
 9330
 9331        Ok(proto::ResolveCompletionDocumentationResponse {
 9332            documentation,
 9333            documentation_is_markdown,
 9334            old_start,
 9335            old_end,
 9336            new_text,
 9337        })
 9338    }
 9339
 9340    async fn handle_apply_code_action(
 9341        this: Model<Self>,
 9342        envelope: TypedEnvelope<proto::ApplyCodeAction>,
 9343        _: Arc<Client>,
 9344        mut cx: AsyncAppContext,
 9345    ) -> Result<proto::ApplyCodeActionResponse> {
 9346        let sender_id = envelope.original_sender_id()?;
 9347        let action = Self::deserialize_code_action(
 9348            envelope
 9349                .payload
 9350                .action
 9351                .ok_or_else(|| anyhow!("invalid action"))?,
 9352        )?;
 9353        let apply_code_action = this.update(&mut cx, |this, cx| {
 9354            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9355            let buffer = this
 9356                .opened_buffers
 9357                .get(&buffer_id)
 9358                .and_then(|buffer| buffer.upgrade())
 9359                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
 9360            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
 9361        })??;
 9362
 9363        let project_transaction = apply_code_action.await?;
 9364        let project_transaction = this.update(&mut cx, |this, cx| {
 9365            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9366        })?;
 9367        Ok(proto::ApplyCodeActionResponse {
 9368            transaction: Some(project_transaction),
 9369        })
 9370    }
 9371
 9372    async fn handle_on_type_formatting(
 9373        this: Model<Self>,
 9374        envelope: TypedEnvelope<proto::OnTypeFormatting>,
 9375        _: Arc<Client>,
 9376        mut cx: AsyncAppContext,
 9377    ) -> Result<proto::OnTypeFormattingResponse> {
 9378        let on_type_formatting = this.update(&mut cx, |this, cx| {
 9379            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9380            let buffer = this
 9381                .opened_buffers
 9382                .get(&buffer_id)
 9383                .and_then(|buffer| buffer.upgrade())
 9384                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9385            let position = envelope
 9386                .payload
 9387                .position
 9388                .and_then(deserialize_anchor)
 9389                .ok_or_else(|| anyhow!("invalid position"))?;
 9390            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
 9391                buffer,
 9392                position,
 9393                envelope.payload.trigger.clone(),
 9394                cx,
 9395            ))
 9396        })??;
 9397
 9398        let transaction = on_type_formatting
 9399            .await?
 9400            .as_ref()
 9401            .map(language::proto::serialize_transaction);
 9402        Ok(proto::OnTypeFormattingResponse { transaction })
 9403    }
 9404
 9405    async fn handle_inlay_hints(
 9406        this: Model<Self>,
 9407        envelope: TypedEnvelope<proto::InlayHints>,
 9408        _: Arc<Client>,
 9409        mut cx: AsyncAppContext,
 9410    ) -> Result<proto::InlayHintsResponse> {
 9411        let sender_id = envelope.original_sender_id()?;
 9412        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9413        let buffer = this.update(&mut cx, |this, _| {
 9414            this.opened_buffers
 9415                .get(&buffer_id)
 9416                .and_then(|buffer| buffer.upgrade())
 9417                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
 9418        })??;
 9419        buffer
 9420            .update(&mut cx, |buffer, _| {
 9421                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 9422            })?
 9423            .await
 9424            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
 9425
 9426        let start = envelope
 9427            .payload
 9428            .start
 9429            .and_then(deserialize_anchor)
 9430            .context("missing range start")?;
 9431        let end = envelope
 9432            .payload
 9433            .end
 9434            .and_then(deserialize_anchor)
 9435            .context("missing range end")?;
 9436        let buffer_hints = this
 9437            .update(&mut cx, |project, cx| {
 9438                project.inlay_hints(buffer.clone(), start..end, cx)
 9439            })?
 9440            .await
 9441            .context("inlay hints fetch")?;
 9442
 9443        this.update(&mut cx, |project, cx| {
 9444            InlayHints::response_to_proto(
 9445                buffer_hints,
 9446                project,
 9447                sender_id,
 9448                &buffer.read(cx).version(),
 9449                cx,
 9450            )
 9451        })
 9452    }
 9453
 9454    async fn handle_resolve_inlay_hint(
 9455        this: Model<Self>,
 9456        envelope: TypedEnvelope<proto::ResolveInlayHint>,
 9457        _: Arc<Client>,
 9458        mut cx: AsyncAppContext,
 9459    ) -> Result<proto::ResolveInlayHintResponse> {
 9460        let proto_hint = envelope
 9461            .payload
 9462            .hint
 9463            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
 9464        let hint = InlayHints::proto_to_project_hint(proto_hint)
 9465            .context("resolved proto inlay hint conversion")?;
 9466        let buffer = this.update(&mut cx, |this, _cx| {
 9467            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9468            this.opened_buffers
 9469                .get(&buffer_id)
 9470                .and_then(|buffer| buffer.upgrade())
 9471                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 9472        })??;
 9473        let response_hint = this
 9474            .update(&mut cx, |project, cx| {
 9475                project.resolve_inlay_hint(
 9476                    hint,
 9477                    buffer,
 9478                    LanguageServerId(envelope.payload.language_server_id as usize),
 9479                    cx,
 9480                )
 9481            })?
 9482            .await
 9483            .context("inlay hints fetch")?;
 9484        Ok(proto::ResolveInlayHintResponse {
 9485            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
 9486        })
 9487    }
 9488
 9489    async fn handle_task_context_for_location(
 9490        project: Model<Self>,
 9491        envelope: TypedEnvelope<proto::TaskContextForLocation>,
 9492        _: Arc<Client>,
 9493        mut cx: AsyncAppContext,
 9494    ) -> Result<proto::TaskContext> {
 9495        let location = envelope
 9496            .payload
 9497            .location
 9498            .context("no location given for task context handling")?;
 9499        let location = cx
 9500            .update(|cx| deserialize_location(&project, location, cx))?
 9501            .await?;
 9502        let context_task = project.update(&mut cx, |project, cx| {
 9503            let captured_variables = {
 9504                let mut variables = TaskVariables::default();
 9505                for range in location
 9506                    .buffer
 9507                    .read(cx)
 9508                    .snapshot()
 9509                    .runnable_ranges(location.range.clone())
 9510                {
 9511                    for (capture_name, value) in range.extra_captures {
 9512                        variables.insert(VariableName::Custom(capture_name.into()), value);
 9513                    }
 9514                }
 9515                variables
 9516            };
 9517            project.task_context_for_location(captured_variables, location, cx)
 9518        })?;
 9519        let task_context = context_task.await.unwrap_or_default();
 9520        Ok(proto::TaskContext {
 9521            cwd: task_context
 9522                .cwd
 9523                .map(|cwd| cwd.to_string_lossy().to_string()),
 9524            task_variables: task_context
 9525                .task_variables
 9526                .into_iter()
 9527                .map(|(variable_name, variable_value)| (variable_name.to_string(), variable_value))
 9528                .collect(),
 9529        })
 9530    }
 9531
 9532    async fn handle_task_templates(
 9533        project: Model<Self>,
 9534        envelope: TypedEnvelope<proto::TaskTemplates>,
 9535        _: Arc<Client>,
 9536        mut cx: AsyncAppContext,
 9537    ) -> Result<proto::TaskTemplatesResponse> {
 9538        let worktree = envelope.payload.worktree_id.map(WorktreeId::from_proto);
 9539        let location = match envelope.payload.location {
 9540            Some(location) => Some(
 9541                cx.update(|cx| deserialize_location(&project, location, cx))?
 9542                    .await
 9543                    .context("task templates request location deserializing")?,
 9544            ),
 9545            None => None,
 9546        };
 9547
 9548        let templates = project
 9549            .update(&mut cx, |project, cx| {
 9550                project.task_templates(worktree, location, cx)
 9551            })?
 9552            .await
 9553            .context("receiving task templates")?
 9554            .into_iter()
 9555            .map(|(kind, template)| {
 9556                let kind = Some(match kind {
 9557                    TaskSourceKind::UserInput => proto::task_source_kind::Kind::UserInput(
 9558                        proto::task_source_kind::UserInput {},
 9559                    ),
 9560                    TaskSourceKind::Worktree {
 9561                        id,
 9562                        abs_path,
 9563                        id_base,
 9564                    } => {
 9565                        proto::task_source_kind::Kind::Worktree(proto::task_source_kind::Worktree {
 9566                            id: id.to_proto(),
 9567                            abs_path: abs_path.to_string_lossy().to_string(),
 9568                            id_base: id_base.to_string(),
 9569                        })
 9570                    }
 9571                    TaskSourceKind::AbsPath { id_base, abs_path } => {
 9572                        proto::task_source_kind::Kind::AbsPath(proto::task_source_kind::AbsPath {
 9573                            abs_path: abs_path.to_string_lossy().to_string(),
 9574                            id_base: id_base.to_string(),
 9575                        })
 9576                    }
 9577                    TaskSourceKind::Language { name } => {
 9578                        proto::task_source_kind::Kind::Language(proto::task_source_kind::Language {
 9579                            name: name.to_string(),
 9580                        })
 9581                    }
 9582                });
 9583                let kind = Some(proto::TaskSourceKind { kind });
 9584                let template = Some(proto::TaskTemplate {
 9585                    label: template.label,
 9586                    command: template.command,
 9587                    args: template.args,
 9588                    env: template.env.into_iter().collect(),
 9589                    cwd: template.cwd,
 9590                    use_new_terminal: template.use_new_terminal,
 9591                    allow_concurrent_runs: template.allow_concurrent_runs,
 9592                    reveal: match template.reveal {
 9593                        RevealStrategy::Always => proto::RevealStrategy::Always as i32,
 9594                        RevealStrategy::Never => proto::RevealStrategy::Never as i32,
 9595                    },
 9596                    tags: template.tags,
 9597                });
 9598                proto::TemplatePair { kind, template }
 9599            })
 9600            .collect();
 9601
 9602        Ok(proto::TaskTemplatesResponse { templates })
 9603    }
 9604
 9605    async fn try_resolve_code_action(
 9606        lang_server: &LanguageServer,
 9607        action: &mut CodeAction,
 9608    ) -> anyhow::Result<()> {
 9609        if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
 9610            if action.lsp_action.data.is_some()
 9611                && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
 9612            {
 9613                action.lsp_action = lang_server
 9614                    .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
 9615                    .await?;
 9616            }
 9617        }
 9618
 9619        anyhow::Ok(())
 9620    }
 9621
 9622    async fn execute_code_actions_on_servers(
 9623        project: &WeakModel<Project>,
 9624        adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
 9625        code_actions: Vec<lsp::CodeActionKind>,
 9626        buffer: &Model<Buffer>,
 9627        push_to_history: bool,
 9628        project_transaction: &mut ProjectTransaction,
 9629        cx: &mut AsyncAppContext,
 9630    ) -> Result<(), anyhow::Error> {
 9631        for (lsp_adapter, language_server) in adapters_and_servers.iter() {
 9632            let code_actions = code_actions.clone();
 9633
 9634            let actions = project
 9635                .update(cx, move |this, cx| {
 9636                    let request = GetCodeActions {
 9637                        range: text::Anchor::MIN..text::Anchor::MAX,
 9638                        kinds: Some(code_actions),
 9639                    };
 9640                    let server = LanguageServerToQuery::Other(language_server.server_id());
 9641                    this.request_lsp(buffer.clone(), server, request, cx)
 9642                })?
 9643                .await?;
 9644
 9645            for mut action in actions {
 9646                Self::try_resolve_code_action(&language_server, &mut action)
 9647                    .await
 9648                    .context("resolving a formatting code action")?;
 9649
 9650                if let Some(edit) = action.lsp_action.edit {
 9651                    if edit.changes.is_none() && edit.document_changes.is_none() {
 9652                        continue;
 9653                    }
 9654
 9655                    let new = Self::deserialize_workspace_edit(
 9656                        project
 9657                            .upgrade()
 9658                            .ok_or_else(|| anyhow!("project dropped"))?,
 9659                        edit,
 9660                        push_to_history,
 9661                        lsp_adapter.clone(),
 9662                        language_server.clone(),
 9663                        cx,
 9664                    )
 9665                    .await?;
 9666                    project_transaction.0.extend(new.0);
 9667                }
 9668
 9669                if let Some(command) = action.lsp_action.command {
 9670                    project.update(cx, |this, _| {
 9671                        this.last_workspace_edits_by_language_server
 9672                            .remove(&language_server.server_id());
 9673                    })?;
 9674
 9675                    language_server
 9676                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 9677                            command: command.command,
 9678                            arguments: command.arguments.unwrap_or_default(),
 9679                            ..Default::default()
 9680                        })
 9681                        .await?;
 9682
 9683                    project.update(cx, |this, _| {
 9684                        project_transaction.0.extend(
 9685                            this.last_workspace_edits_by_language_server
 9686                                .remove(&language_server.server_id())
 9687                                .unwrap_or_default()
 9688                                .0,
 9689                        )
 9690                    })?;
 9691                }
 9692            }
 9693        }
 9694
 9695        Ok(())
 9696    }
 9697
 9698    async fn handle_refresh_inlay_hints(
 9699        this: Model<Self>,
 9700        _: TypedEnvelope<proto::RefreshInlayHints>,
 9701        _: Arc<Client>,
 9702        mut cx: AsyncAppContext,
 9703    ) -> Result<proto::Ack> {
 9704        this.update(&mut cx, |_, cx| {
 9705            cx.emit(Event::RefreshInlayHints);
 9706        })?;
 9707        Ok(proto::Ack {})
 9708    }
 9709
 9710    async fn handle_lsp_command<T: LspCommand>(
 9711        this: Model<Self>,
 9712        envelope: TypedEnvelope<T::ProtoRequest>,
 9713        _: Arc<Client>,
 9714        mut cx: AsyncAppContext,
 9715    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
 9716    where
 9717        <T::LspRequest as lsp::request::Request>::Params: Send,
 9718        <T::LspRequest as lsp::request::Request>::Result: Send,
 9719    {
 9720        let sender_id = envelope.original_sender_id()?;
 9721        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
 9722        let buffer_handle = this.update(&mut cx, |this, _cx| {
 9723            this.opened_buffers
 9724                .get(&buffer_id)
 9725                .and_then(|buffer| buffer.upgrade())
 9726                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 9727        })??;
 9728        let request = T::from_proto(
 9729            envelope.payload,
 9730            this.clone(),
 9731            buffer_handle.clone(),
 9732            cx.clone(),
 9733        )
 9734        .await?;
 9735        let response = this
 9736            .update(&mut cx, |this, cx| {
 9737                this.request_lsp(
 9738                    buffer_handle.clone(),
 9739                    LanguageServerToQuery::Primary,
 9740                    request,
 9741                    cx,
 9742                )
 9743            })?
 9744            .await?;
 9745        this.update(&mut cx, |this, cx| {
 9746            Ok(T::response_to_proto(
 9747                response,
 9748                this,
 9749                sender_id,
 9750                &buffer_handle.read(cx).version(),
 9751                cx,
 9752            ))
 9753        })?
 9754    }
 9755
 9756    async fn handle_get_project_symbols(
 9757        this: Model<Self>,
 9758        envelope: TypedEnvelope<proto::GetProjectSymbols>,
 9759        _: Arc<Client>,
 9760        mut cx: AsyncAppContext,
 9761    ) -> Result<proto::GetProjectSymbolsResponse> {
 9762        let symbols = this
 9763            .update(&mut cx, |this, cx| {
 9764                this.symbols(&envelope.payload.query, cx)
 9765            })?
 9766            .await?;
 9767
 9768        Ok(proto::GetProjectSymbolsResponse {
 9769            symbols: symbols.iter().map(serialize_symbol).collect(),
 9770        })
 9771    }
 9772
 9773    async fn handle_search_project(
 9774        this: Model<Self>,
 9775        envelope: TypedEnvelope<proto::SearchProject>,
 9776        _: Arc<Client>,
 9777        mut cx: AsyncAppContext,
 9778    ) -> Result<proto::SearchProjectResponse> {
 9779        let peer_id = envelope.original_sender_id()?;
 9780        let query = SearchQuery::from_proto(envelope.payload)?;
 9781        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
 9782
 9783        cx.spawn(move |mut cx| async move {
 9784            let mut locations = Vec::new();
 9785            let mut limit_reached = false;
 9786            while let Some(result) = result.next().await {
 9787                match result {
 9788                    SearchResult::Buffer { buffer, ranges } => {
 9789                        for range in ranges {
 9790                            let start = serialize_anchor(&range.start);
 9791                            let end = serialize_anchor(&range.end);
 9792                            let buffer_id = this.update(&mut cx, |this, cx| {
 9793                                this.create_buffer_for_peer(&buffer, peer_id, cx).into()
 9794                            })?;
 9795                            locations.push(proto::Location {
 9796                                buffer_id,
 9797                                start: Some(start),
 9798                                end: Some(end),
 9799                            });
 9800                        }
 9801                    }
 9802                    SearchResult::LimitReached => limit_reached = true,
 9803                }
 9804            }
 9805            Ok(proto::SearchProjectResponse {
 9806                locations,
 9807                limit_reached,
 9808            })
 9809        })
 9810        .await
 9811    }
 9812
 9813    async fn handle_open_buffer_for_symbol(
 9814        this: Model<Self>,
 9815        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
 9816        _: Arc<Client>,
 9817        mut cx: AsyncAppContext,
 9818    ) -> Result<proto::OpenBufferForSymbolResponse> {
 9819        let peer_id = envelope.original_sender_id()?;
 9820        let symbol = envelope
 9821            .payload
 9822            .symbol
 9823            .ok_or_else(|| anyhow!("invalid symbol"))?;
 9824        let symbol = Self::deserialize_symbol(symbol)?;
 9825        let symbol = this.update(&mut cx, |this, _| {
 9826            let signature = this.symbol_signature(&symbol.path);
 9827            if signature == symbol.signature {
 9828                Ok(symbol)
 9829            } else {
 9830                Err(anyhow!("invalid symbol signature"))
 9831            }
 9832        })??;
 9833        let buffer = this
 9834            .update(&mut cx, |this, cx| {
 9835                this.open_buffer_for_symbol(
 9836                    &Symbol {
 9837                        language_server_name: symbol.language_server_name,
 9838                        source_worktree_id: symbol.source_worktree_id,
 9839                        path: symbol.path,
 9840                        name: symbol.name,
 9841                        kind: symbol.kind,
 9842                        range: symbol.range,
 9843                        signature: symbol.signature,
 9844                        label: CodeLabel {
 9845                            text: Default::default(),
 9846                            runs: Default::default(),
 9847                            filter_range: Default::default(),
 9848                        },
 9849                    },
 9850                    cx,
 9851                )
 9852            })?
 9853            .await?;
 9854
 9855        this.update(&mut cx, |this, cx| {
 9856            let is_private = buffer
 9857                .read(cx)
 9858                .file()
 9859                .map(|f| f.is_private())
 9860                .unwrap_or_default();
 9861            if is_private {
 9862                Err(anyhow!(ErrorCode::UnsharedItem))
 9863            } else {
 9864                Ok(proto::OpenBufferForSymbolResponse {
 9865                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9866                })
 9867            }
 9868        })?
 9869    }
 9870
 9871    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
 9872        let mut hasher = Sha256::new();
 9873        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
 9874        hasher.update(project_path.path.to_string_lossy().as_bytes());
 9875        hasher.update(self.nonce.to_be_bytes());
 9876        hasher.finalize().as_slice().try_into().unwrap()
 9877    }
 9878
 9879    async fn handle_open_buffer_by_id(
 9880        this: Model<Self>,
 9881        envelope: TypedEnvelope<proto::OpenBufferById>,
 9882        _: Arc<Client>,
 9883        mut cx: AsyncAppContext,
 9884    ) -> Result<proto::OpenBufferResponse> {
 9885        let peer_id = envelope.original_sender_id()?;
 9886        let buffer_id = BufferId::new(envelope.payload.id)?;
 9887        let buffer = this
 9888            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
 9889            .await?;
 9890        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9891    }
 9892
 9893    async fn handle_open_buffer_by_path(
 9894        this: Model<Self>,
 9895        envelope: TypedEnvelope<proto::OpenBufferByPath>,
 9896        _: Arc<Client>,
 9897        mut cx: AsyncAppContext,
 9898    ) -> Result<proto::OpenBufferResponse> {
 9899        let peer_id = envelope.original_sender_id()?;
 9900        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 9901        let open_buffer = this.update(&mut cx, |this, cx| {
 9902            this.open_buffer(
 9903                ProjectPath {
 9904                    worktree_id,
 9905                    path: PathBuf::from(envelope.payload.path).into(),
 9906                },
 9907                cx,
 9908            )
 9909        })?;
 9910
 9911        let buffer = open_buffer.await?;
 9912        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9913    }
 9914
 9915    async fn handle_open_new_buffer(
 9916        this: Model<Self>,
 9917        envelope: TypedEnvelope<proto::OpenNewBuffer>,
 9918        _: Arc<Client>,
 9919        mut cx: AsyncAppContext,
 9920    ) -> Result<proto::OpenBufferResponse> {
 9921        let buffer = this.update(&mut cx, |this, cx| this.create_local_buffer("", None, cx))?;
 9922        let peer_id = envelope.original_sender_id()?;
 9923
 9924        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9925    }
 9926
 9927    fn respond_to_open_buffer_request(
 9928        this: Model<Self>,
 9929        buffer: Model<Buffer>,
 9930        peer_id: proto::PeerId,
 9931        cx: &mut AsyncAppContext,
 9932    ) -> Result<proto::OpenBufferResponse> {
 9933        this.update(cx, |this, cx| {
 9934            let is_private = buffer
 9935                .read(cx)
 9936                .file()
 9937                .map(|f| f.is_private())
 9938                .unwrap_or_default();
 9939            if is_private {
 9940                Err(anyhow!(ErrorCode::UnsharedItem))
 9941            } else {
 9942                Ok(proto::OpenBufferResponse {
 9943                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9944                })
 9945            }
 9946        })?
 9947    }
 9948
 9949    fn serialize_project_transaction_for_peer(
 9950        &mut self,
 9951        project_transaction: ProjectTransaction,
 9952        peer_id: proto::PeerId,
 9953        cx: &mut AppContext,
 9954    ) -> proto::ProjectTransaction {
 9955        let mut serialized_transaction = proto::ProjectTransaction {
 9956            buffer_ids: Default::default(),
 9957            transactions: Default::default(),
 9958        };
 9959        for (buffer, transaction) in project_transaction.0 {
 9960            serialized_transaction
 9961                .buffer_ids
 9962                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
 9963            serialized_transaction
 9964                .transactions
 9965                .push(language::proto::serialize_transaction(&transaction));
 9966        }
 9967        serialized_transaction
 9968    }
 9969
 9970    fn deserialize_project_transaction(
 9971        &mut self,
 9972        message: proto::ProjectTransaction,
 9973        push_to_history: bool,
 9974        cx: &mut ModelContext<Self>,
 9975    ) -> Task<Result<ProjectTransaction>> {
 9976        cx.spawn(move |this, mut cx| async move {
 9977            let mut project_transaction = ProjectTransaction::default();
 9978            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
 9979            {
 9980                let buffer_id = BufferId::new(buffer_id)?;
 9981                let buffer = this
 9982                    .update(&mut cx, |this, cx| {
 9983                        this.wait_for_remote_buffer(buffer_id, cx)
 9984                    })?
 9985                    .await?;
 9986                let transaction = language::proto::deserialize_transaction(transaction)?;
 9987                project_transaction.0.insert(buffer, transaction);
 9988            }
 9989
 9990            for (buffer, transaction) in &project_transaction.0 {
 9991                buffer
 9992                    .update(&mut cx, |buffer, _| {
 9993                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 9994                    })?
 9995                    .await?;
 9996
 9997                if push_to_history {
 9998                    buffer.update(&mut cx, |buffer, _| {
 9999                        buffer.push_transaction(transaction.clone(), Instant::now());
10000                    })?;
10001                }
10002            }
10003
10004            Ok(project_transaction)
10005        })
10006    }
10007
10008    fn create_buffer_for_peer(
10009        &mut self,
10010        buffer: &Model<Buffer>,
10011        peer_id: proto::PeerId,
10012        cx: &mut AppContext,
10013    ) -> BufferId {
10014        let buffer_id = buffer.read(cx).remote_id();
10015        if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
10016            updates_tx
10017                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
10018                .ok();
10019        }
10020        buffer_id
10021    }
10022
10023    fn wait_for_remote_buffer(
10024        &mut self,
10025        id: BufferId,
10026        cx: &mut ModelContext<Self>,
10027    ) -> Task<Result<Model<Buffer>>> {
10028        let buffer = self
10029            .opened_buffers
10030            .get(&id)
10031            .and_then(|buffer| buffer.upgrade());
10032
10033        if let Some(buffer) = buffer {
10034            return Task::ready(Ok(buffer));
10035        }
10036
10037        let (tx, rx) = oneshot::channel();
10038        self.loading_buffers.entry(id).or_default().push(tx);
10039
10040        cx.background_executor().spawn(async move { rx.await? })
10041    }
10042
10043    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
10044        let project_id = match self.client_state {
10045            ProjectClientState::Remote {
10046                sharing_has_stopped,
10047                remote_id,
10048                ..
10049            } => {
10050                if sharing_has_stopped {
10051                    return Task::ready(Err(anyhow!(
10052                        "can't synchronize remote buffers on a readonly project"
10053                    )));
10054                } else {
10055                    remote_id
10056                }
10057            }
10058            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
10059                return Task::ready(Err(anyhow!(
10060                    "can't synchronize remote buffers on a local project"
10061                )))
10062            }
10063        };
10064
10065        let client = self.client.clone();
10066        cx.spawn(move |this, mut cx| async move {
10067            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
10068                let buffers = this
10069                    .opened_buffers
10070                    .iter()
10071                    .filter_map(|(id, buffer)| {
10072                        let buffer = buffer.upgrade()?;
10073                        Some(proto::BufferVersion {
10074                            id: (*id).into(),
10075                            version: language::proto::serialize_version(&buffer.read(cx).version),
10076                        })
10077                    })
10078                    .collect();
10079                let incomplete_buffer_ids = this
10080                    .incomplete_remote_buffers
10081                    .keys()
10082                    .copied()
10083                    .collect::<Vec<_>>();
10084
10085                (buffers, incomplete_buffer_ids)
10086            })?;
10087            let response = client
10088                .request(proto::SynchronizeBuffers {
10089                    project_id,
10090                    buffers,
10091                })
10092                .await?;
10093
10094            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
10095                response
10096                    .buffers
10097                    .into_iter()
10098                    .map(|buffer| {
10099                        let client = client.clone();
10100                        let buffer_id = match BufferId::new(buffer.id) {
10101                            Ok(id) => id,
10102                            Err(e) => {
10103                                return Task::ready(Err(e));
10104                            }
10105                        };
10106                        let remote_version = language::proto::deserialize_version(&buffer.version);
10107                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
10108                            let operations =
10109                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
10110                            cx.background_executor().spawn(async move {
10111                                let operations = operations.await;
10112                                for chunk in split_operations(operations) {
10113                                    client
10114                                        .request(proto::UpdateBuffer {
10115                                            project_id,
10116                                            buffer_id: buffer_id.into(),
10117                                            operations: chunk,
10118                                        })
10119                                        .await?;
10120                                }
10121                                anyhow::Ok(())
10122                            })
10123                        } else {
10124                            Task::ready(Ok(()))
10125                        }
10126                    })
10127                    .collect::<Vec<_>>()
10128            })?;
10129
10130            // Any incomplete buffers have open requests waiting. Request that the host sends
10131            // creates these buffers for us again to unblock any waiting futures.
10132            for id in incomplete_buffer_ids {
10133                cx.background_executor()
10134                    .spawn(client.request(proto::OpenBufferById {
10135                        project_id,
10136                        id: id.into(),
10137                    }))
10138                    .detach();
10139            }
10140
10141            futures::future::join_all(send_updates_for_buffers)
10142                .await
10143                .into_iter()
10144                .collect()
10145        })
10146    }
10147
10148    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
10149        self.worktrees()
10150            .map(|worktree| {
10151                let worktree = worktree.read(cx);
10152                proto::WorktreeMetadata {
10153                    id: worktree.id().to_proto(),
10154                    root_name: worktree.root_name().into(),
10155                    visible: worktree.is_visible(),
10156                    abs_path: worktree.abs_path().to_string_lossy().into(),
10157                }
10158            })
10159            .collect()
10160    }
10161
10162    fn set_worktrees_from_proto(
10163        &mut self,
10164        worktrees: Vec<proto::WorktreeMetadata>,
10165        cx: &mut ModelContext<Project>,
10166    ) -> Result<()> {
10167        let replica_id = self.replica_id();
10168        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
10169
10170        let mut old_worktrees_by_id = self
10171            .worktrees
10172            .drain(..)
10173            .filter_map(|worktree| {
10174                let worktree = worktree.upgrade()?;
10175                Some((worktree.read(cx).id(), worktree))
10176            })
10177            .collect::<HashMap<_, _>>();
10178
10179        for worktree in worktrees {
10180            if let Some(old_worktree) =
10181                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
10182            {
10183                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
10184            } else {
10185                let worktree =
10186                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
10187                let _ = self.add_worktree(&worktree, cx);
10188            }
10189        }
10190
10191        self.metadata_changed(cx);
10192        for id in old_worktrees_by_id.keys() {
10193            cx.emit(Event::WorktreeRemoved(*id));
10194        }
10195
10196        Ok(())
10197    }
10198
10199    fn set_collaborators_from_proto(
10200        &mut self,
10201        messages: Vec<proto::Collaborator>,
10202        cx: &mut ModelContext<Self>,
10203    ) -> Result<()> {
10204        let mut collaborators = HashMap::default();
10205        for message in messages {
10206            let collaborator = Collaborator::from_proto(message)?;
10207            collaborators.insert(collaborator.peer_id, collaborator);
10208        }
10209        for old_peer_id in self.collaborators.keys() {
10210            if !collaborators.contains_key(old_peer_id) {
10211                cx.emit(Event::CollaboratorLeft(*old_peer_id));
10212            }
10213        }
10214        self.collaborators = collaborators;
10215        Ok(())
10216    }
10217
10218    fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
10219        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
10220        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
10221        let kind = unsafe { mem::transmute(serialized_symbol.kind) };
10222        let path = ProjectPath {
10223            worktree_id,
10224            path: PathBuf::from(serialized_symbol.path).into(),
10225        };
10226
10227        let start = serialized_symbol
10228            .start
10229            .ok_or_else(|| anyhow!("invalid start"))?;
10230        let end = serialized_symbol
10231            .end
10232            .ok_or_else(|| anyhow!("invalid end"))?;
10233        Ok(CoreSymbol {
10234            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
10235            source_worktree_id,
10236            path,
10237            name: serialized_symbol.name,
10238            range: Unclipped(PointUtf16::new(start.row, start.column))
10239                ..Unclipped(PointUtf16::new(end.row, end.column)),
10240            kind,
10241            signature: serialized_symbol
10242                .signature
10243                .try_into()
10244                .map_err(|_| anyhow!("invalid signature"))?,
10245        })
10246    }
10247
10248    fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
10249        proto::Completion {
10250            old_start: Some(serialize_anchor(&completion.old_range.start)),
10251            old_end: Some(serialize_anchor(&completion.old_range.end)),
10252            new_text: completion.new_text.clone(),
10253            server_id: completion.server_id.0 as u64,
10254            lsp_completion: serde_json::to_vec(&completion.lsp_completion).unwrap(),
10255        }
10256    }
10257
10258    fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
10259        let old_start = completion
10260            .old_start
10261            .and_then(deserialize_anchor)
10262            .ok_or_else(|| anyhow!("invalid old start"))?;
10263        let old_end = completion
10264            .old_end
10265            .and_then(deserialize_anchor)
10266            .ok_or_else(|| anyhow!("invalid old end"))?;
10267        let lsp_completion = serde_json::from_slice(&completion.lsp_completion)?;
10268
10269        Ok(CoreCompletion {
10270            old_range: old_start..old_end,
10271            new_text: completion.new_text,
10272            server_id: LanguageServerId(completion.server_id as usize),
10273            lsp_completion,
10274        })
10275    }
10276
10277    fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
10278        proto::CodeAction {
10279            server_id: action.server_id.0 as u64,
10280            start: Some(serialize_anchor(&action.range.start)),
10281            end: Some(serialize_anchor(&action.range.end)),
10282            lsp_action: serde_json::to_vec(&action.lsp_action).unwrap(),
10283        }
10284    }
10285
10286    fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
10287        let start = action
10288            .start
10289            .and_then(deserialize_anchor)
10290            .ok_or_else(|| anyhow!("invalid start"))?;
10291        let end = action
10292            .end
10293            .and_then(deserialize_anchor)
10294            .ok_or_else(|| anyhow!("invalid end"))?;
10295        let lsp_action = serde_json::from_slice(&action.lsp_action)?;
10296        Ok(CodeAction {
10297            server_id: LanguageServerId(action.server_id as usize),
10298            range: start..end,
10299            lsp_action,
10300        })
10301    }
10302
10303    async fn handle_buffer_saved(
10304        this: Model<Self>,
10305        envelope: TypedEnvelope<proto::BufferSaved>,
10306        _: Arc<Client>,
10307        mut cx: AsyncAppContext,
10308    ) -> Result<()> {
10309        let version = deserialize_version(&envelope.payload.version);
10310        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
10311        let mtime = envelope.payload.mtime.map(|time| time.into());
10312
10313        this.update(&mut cx, |this, cx| {
10314            let buffer = this
10315                .opened_buffers
10316                .get(&buffer_id)
10317                .and_then(|buffer| buffer.upgrade())
10318                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
10319            if let Some(buffer) = buffer {
10320                buffer.update(cx, |buffer, cx| {
10321                    buffer.did_save(version, mtime, cx);
10322                });
10323            }
10324            Ok(())
10325        })?
10326    }
10327
10328    async fn handle_buffer_reloaded(
10329        this: Model<Self>,
10330        envelope: TypedEnvelope<proto::BufferReloaded>,
10331        _: Arc<Client>,
10332        mut cx: AsyncAppContext,
10333    ) -> Result<()> {
10334        let payload = envelope.payload;
10335        let version = deserialize_version(&payload.version);
10336        let line_ending = deserialize_line_ending(
10337            proto::LineEnding::from_i32(payload.line_ending)
10338                .ok_or_else(|| anyhow!("missing line ending"))?,
10339        );
10340        let mtime = payload.mtime.map(|time| time.into());
10341        let buffer_id = BufferId::new(payload.buffer_id)?;
10342        this.update(&mut cx, |this, cx| {
10343            let buffer = this
10344                .opened_buffers
10345                .get(&buffer_id)
10346                .and_then(|buffer| buffer.upgrade())
10347                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
10348            if let Some(buffer) = buffer {
10349                buffer.update(cx, |buffer, cx| {
10350                    buffer.did_reload(version, line_ending, mtime, cx);
10351                });
10352            }
10353            Ok(())
10354        })?
10355    }
10356
10357    #[allow(clippy::type_complexity)]
10358    fn edits_from_lsp(
10359        &mut self,
10360        buffer: &Model<Buffer>,
10361        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
10362        server_id: LanguageServerId,
10363        version: Option<i32>,
10364        cx: &mut ModelContext<Self>,
10365    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
10366        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
10367        cx.background_executor().spawn(async move {
10368            let snapshot = snapshot?;
10369            let mut lsp_edits = lsp_edits
10370                .into_iter()
10371                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
10372                .collect::<Vec<_>>();
10373            lsp_edits.sort_by_key(|(range, _)| range.start);
10374
10375            let mut lsp_edits = lsp_edits.into_iter().peekable();
10376            let mut edits = Vec::new();
10377            while let Some((range, mut new_text)) = lsp_edits.next() {
10378                // Clip invalid ranges provided by the language server.
10379                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
10380                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
10381
10382                // Combine any LSP edits that are adjacent.
10383                //
10384                // Also, combine LSP edits that are separated from each other by only
10385                // a newline. This is important because for some code actions,
10386                // Rust-analyzer rewrites the entire buffer via a series of edits that
10387                // are separated by unchanged newline characters.
10388                //
10389                // In order for the diffing logic below to work properly, any edits that
10390                // cancel each other out must be combined into one.
10391                while let Some((next_range, next_text)) = lsp_edits.peek() {
10392                    if next_range.start.0 > range.end {
10393                        if next_range.start.0.row > range.end.row + 1
10394                            || next_range.start.0.column > 0
10395                            || snapshot.clip_point_utf16(
10396                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
10397                                Bias::Left,
10398                            ) > range.end
10399                        {
10400                            break;
10401                        }
10402                        new_text.push('\n');
10403                    }
10404                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
10405                    new_text.push_str(next_text);
10406                    lsp_edits.next();
10407                }
10408
10409                // For multiline edits, perform a diff of the old and new text so that
10410                // we can identify the changes more precisely, preserving the locations
10411                // of any anchors positioned in the unchanged regions.
10412                if range.end.row > range.start.row {
10413                    let mut offset = range.start.to_offset(&snapshot);
10414                    let old_text = snapshot.text_for_range(range).collect::<String>();
10415
10416                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
10417                    let mut moved_since_edit = true;
10418                    for change in diff.iter_all_changes() {
10419                        let tag = change.tag();
10420                        let value = change.value();
10421                        match tag {
10422                            ChangeTag::Equal => {
10423                                offset += value.len();
10424                                moved_since_edit = true;
10425                            }
10426                            ChangeTag::Delete => {
10427                                let start = snapshot.anchor_after(offset);
10428                                let end = snapshot.anchor_before(offset + value.len());
10429                                if moved_since_edit {
10430                                    edits.push((start..end, String::new()));
10431                                } else {
10432                                    edits.last_mut().unwrap().0.end = end;
10433                                }
10434                                offset += value.len();
10435                                moved_since_edit = false;
10436                            }
10437                            ChangeTag::Insert => {
10438                                if moved_since_edit {
10439                                    let anchor = snapshot.anchor_after(offset);
10440                                    edits.push((anchor..anchor, value.to_string()));
10441                                } else {
10442                                    edits.last_mut().unwrap().1.push_str(value);
10443                                }
10444                                moved_since_edit = false;
10445                            }
10446                        }
10447                    }
10448                } else if range.end == range.start {
10449                    let anchor = snapshot.anchor_after(range.start);
10450                    edits.push((anchor..anchor, new_text));
10451                } else {
10452                    let edit_start = snapshot.anchor_after(range.start);
10453                    let edit_end = snapshot.anchor_before(range.end);
10454                    edits.push((edit_start..edit_end, new_text));
10455                }
10456            }
10457
10458            Ok(edits)
10459        })
10460    }
10461
10462    fn buffer_snapshot_for_lsp_version(
10463        &mut self,
10464        buffer: &Model<Buffer>,
10465        server_id: LanguageServerId,
10466        version: Option<i32>,
10467        cx: &AppContext,
10468    ) -> Result<TextBufferSnapshot> {
10469        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
10470
10471        if let Some(version) = version {
10472            let buffer_id = buffer.read(cx).remote_id();
10473            let snapshots = self
10474                .buffer_snapshots
10475                .get_mut(&buffer_id)
10476                .and_then(|m| m.get_mut(&server_id))
10477                .ok_or_else(|| {
10478                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
10479                })?;
10480
10481            let found_snapshot = snapshots
10482                .binary_search_by_key(&version, |e| e.version)
10483                .map(|ix| snapshots[ix].snapshot.clone())
10484                .map_err(|_| {
10485                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
10486                })?;
10487
10488            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
10489            Ok(found_snapshot)
10490        } else {
10491            Ok((buffer.read(cx)).text_snapshot())
10492        }
10493    }
10494
10495    pub fn language_servers(
10496        &self,
10497    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
10498        self.language_server_ids
10499            .iter()
10500            .map(|((worktree_id, server_name), server_id)| {
10501                (*server_id, server_name.clone(), *worktree_id)
10502            })
10503    }
10504
10505    pub fn supplementary_language_servers(
10506        &self,
10507    ) -> impl '_
10508           + Iterator<
10509        Item = (
10510            &LanguageServerId,
10511            &(LanguageServerName, Arc<LanguageServer>),
10512        ),
10513    > {
10514        self.supplementary_language_servers.iter()
10515    }
10516
10517    pub fn language_server_adapter_for_id(
10518        &self,
10519        id: LanguageServerId,
10520    ) -> Option<Arc<CachedLspAdapter>> {
10521        if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
10522            Some(adapter.clone())
10523        } else {
10524            None
10525        }
10526    }
10527
10528    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
10529        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
10530            Some(server.clone())
10531        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
10532            Some(Arc::clone(server))
10533        } else {
10534            None
10535        }
10536    }
10537
10538    pub fn language_servers_for_buffer(
10539        &self,
10540        buffer: &Buffer,
10541        cx: &AppContext,
10542    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10543        self.language_server_ids_for_buffer(buffer, cx)
10544            .into_iter()
10545            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
10546                LanguageServerState::Running {
10547                    adapter, server, ..
10548                } => Some((adapter, server)),
10549                _ => None,
10550            })
10551    }
10552
10553    fn primary_language_server_for_buffer(
10554        &self,
10555        buffer: &Buffer,
10556        cx: &AppContext,
10557    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10558        self.language_servers_for_buffer(buffer, cx)
10559            .find(|s| s.0.is_primary)
10560    }
10561
10562    pub fn language_server_for_buffer(
10563        &self,
10564        buffer: &Buffer,
10565        server_id: LanguageServerId,
10566        cx: &AppContext,
10567    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10568        self.language_servers_for_buffer(buffer, cx)
10569            .find(|(_, s)| s.server_id() == server_id)
10570    }
10571
10572    fn language_server_ids_for_buffer(
10573        &self,
10574        buffer: &Buffer,
10575        cx: &AppContext,
10576    ) -> Vec<LanguageServerId> {
10577        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
10578            let worktree_id = file.worktree_id(cx);
10579            self.languages
10580                .lsp_adapters(&language)
10581                .iter()
10582                .flat_map(|adapter| {
10583                    let key = (worktree_id, adapter.name.clone());
10584                    self.language_server_ids.get(&key).copied()
10585                })
10586                .collect()
10587        } else {
10588            Vec::new()
10589        }
10590    }
10591
10592    pub fn task_context_for_location(
10593        &self,
10594        captured_variables: TaskVariables,
10595        location: Location,
10596        cx: &mut ModelContext<'_, Project>,
10597    ) -> Task<Option<TaskContext>> {
10598        if self.is_local() {
10599            let cwd = self.task_cwd(cx).log_err().flatten();
10600
10601            cx.spawn(|project, cx| async move {
10602                let mut task_variables = cx
10603                    .update(|cx| {
10604                        combine_task_variables(
10605                            captured_variables,
10606                            location,
10607                            BasicContextProvider::new(project.upgrade()?),
10608                            cx,
10609                        )
10610                        .log_err()
10611                    })
10612                    .ok()
10613                    .flatten()?;
10614                // Remove all custom entries starting with _, as they're not intended for use by the end user.
10615                task_variables.sweep();
10616                Some(TaskContext {
10617                    cwd,
10618                    task_variables,
10619                })
10620            })
10621        } else if let Some(project_id) = self
10622            .remote_id()
10623            .filter(|_| self.ssh_connection_string(cx).is_some())
10624        {
10625            let task_context = self.client().request(proto::TaskContextForLocation {
10626                project_id,
10627                location: Some(proto::Location {
10628                    buffer_id: location.buffer.read(cx).remote_id().into(),
10629                    start: Some(serialize_anchor(&location.range.start)),
10630                    end: Some(serialize_anchor(&location.range.end)),
10631                }),
10632            });
10633            cx.background_executor().spawn(async move {
10634                let task_context = task_context.await.log_err()?;
10635                Some(TaskContext {
10636                    cwd: task_context.cwd.map(PathBuf::from),
10637                    task_variables: task_context
10638                        .task_variables
10639                        .into_iter()
10640                        .filter_map(
10641                            |(variable_name, variable_value)| match variable_name.parse() {
10642                                Ok(variable_name) => Some((variable_name, variable_value)),
10643                                Err(()) => {
10644                                    log::error!("Unknown variable name: {variable_name}");
10645                                    None
10646                                }
10647                            },
10648                        )
10649                        .collect(),
10650                })
10651            })
10652        } else {
10653            Task::ready(None)
10654        }
10655    }
10656
10657    pub fn task_templates(
10658        &self,
10659        worktree: Option<WorktreeId>,
10660        location: Option<Location>,
10661        cx: &mut ModelContext<Self>,
10662    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
10663        if self.is_local() {
10664            let language = location
10665                .and_then(|location| location.buffer.read(cx).language_at(location.range.start));
10666            Task::ready(Ok(self
10667                .task_inventory()
10668                .read(cx)
10669                .list_tasks(language, worktree)))
10670        } else if let Some(project_id) = self
10671            .remote_id()
10672            .filter(|_| self.ssh_connection_string(cx).is_some())
10673        {
10674            let remote_templates =
10675                self.query_remote_task_templates(project_id, worktree, location.as_ref(), cx);
10676            cx.background_executor().spawn(remote_templates)
10677        } else {
10678            Task::ready(Ok(Vec::new()))
10679        }
10680    }
10681
10682    pub fn query_remote_task_templates(
10683        &self,
10684        project_id: u64,
10685        worktree: Option<WorktreeId>,
10686        location: Option<&Location>,
10687        cx: &AppContext,
10688    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
10689        let client = self.client();
10690        let location = location.map(|location| serialize_location(location, cx));
10691        cx.spawn(|_| async move {
10692            let response = client
10693                .request(proto::TaskTemplates {
10694                    project_id,
10695                    worktree_id: worktree.map(|id| id.to_proto()),
10696                    location,
10697                })
10698                .await?;
10699
10700            Ok(response
10701                .templates
10702                .into_iter()
10703                .filter_map(|template_pair| {
10704                    let task_source_kind = match template_pair.kind?.kind? {
10705                        proto::task_source_kind::Kind::UserInput(_) => TaskSourceKind::UserInput,
10706                        proto::task_source_kind::Kind::Worktree(worktree) => {
10707                            TaskSourceKind::Worktree {
10708                                id: WorktreeId::from_proto(worktree.id),
10709                                abs_path: PathBuf::from(worktree.abs_path),
10710                                id_base: Cow::Owned(worktree.id_base),
10711                            }
10712                        }
10713                        proto::task_source_kind::Kind::AbsPath(abs_path) => {
10714                            TaskSourceKind::AbsPath {
10715                                id_base: Cow::Owned(abs_path.id_base),
10716                                abs_path: PathBuf::from(abs_path.abs_path),
10717                            }
10718                        }
10719                        proto::task_source_kind::Kind::Language(language) => {
10720                            TaskSourceKind::Language {
10721                                name: language.name.into(),
10722                            }
10723                        }
10724                    };
10725
10726                    let proto_template = template_pair.template?;
10727                    let reveal = match proto::RevealStrategy::from_i32(proto_template.reveal)
10728                        .unwrap_or(proto::RevealStrategy::Always)
10729                    {
10730                        proto::RevealStrategy::Always => RevealStrategy::Always,
10731                        proto::RevealStrategy::Never => RevealStrategy::Never,
10732                    };
10733                    let task_template = TaskTemplate {
10734                        label: proto_template.label,
10735                        command: proto_template.command,
10736                        args: proto_template.args,
10737                        env: proto_template.env.into_iter().collect(),
10738                        cwd: proto_template.cwd,
10739                        use_new_terminal: proto_template.use_new_terminal,
10740                        allow_concurrent_runs: proto_template.allow_concurrent_runs,
10741                        reveal,
10742                        tags: proto_template.tags,
10743                    };
10744                    Some((task_source_kind, task_template))
10745                })
10746                .collect())
10747        })
10748    }
10749
10750    fn task_cwd(&self, cx: &AppContext) -> anyhow::Result<Option<PathBuf>> {
10751        let available_worktrees = self
10752            .worktrees()
10753            .filter(|worktree| {
10754                let worktree = worktree.read(cx);
10755                worktree.is_visible()
10756                    && worktree.is_local()
10757                    && worktree.root_entry().map_or(false, |e| e.is_dir())
10758            })
10759            .collect::<Vec<_>>();
10760        let cwd = match available_worktrees.len() {
10761            0 => None,
10762            1 => Some(available_worktrees[0].read(cx).abs_path()),
10763            _ => {
10764                let cwd_for_active_entry = self.active_entry().and_then(|entry_id| {
10765                    available_worktrees.into_iter().find_map(|worktree| {
10766                        let worktree = worktree.read(cx);
10767                        if worktree.contains_entry(entry_id) {
10768                            Some(worktree.abs_path())
10769                        } else {
10770                            None
10771                        }
10772                    })
10773                });
10774                anyhow::ensure!(
10775                    cwd_for_active_entry.is_some(),
10776                    "Cannot determine task cwd for multiple worktrees"
10777                );
10778                cwd_for_active_entry
10779            }
10780        };
10781        Ok(cwd.map(|path| path.to_path_buf()))
10782    }
10783}
10784
10785fn combine_task_variables(
10786    mut captured_variables: TaskVariables,
10787    location: Location,
10788    baseline: BasicContextProvider,
10789    cx: &mut AppContext,
10790) -> anyhow::Result<TaskVariables> {
10791    let language_context_provider = location
10792        .buffer
10793        .read(cx)
10794        .language()
10795        .and_then(|language| language.context_provider());
10796    let baseline = baseline
10797        .build_context(&captured_variables, &location, cx)
10798        .context("building basic default context")?;
10799    captured_variables.extend(baseline);
10800    if let Some(provider) = language_context_provider {
10801        captured_variables.extend(
10802            provider
10803                .build_context(&captured_variables, &location, cx)
10804                .context("building provider context")?,
10805        );
10806    }
10807    Ok(captured_variables)
10808}
10809
10810async fn populate_labels_for_symbols(
10811    symbols: Vec<CoreSymbol>,
10812    language_registry: &Arc<LanguageRegistry>,
10813    default_language: Option<Arc<Language>>,
10814    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10815    output: &mut Vec<Symbol>,
10816) {
10817    let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
10818
10819    let mut unknown_path = None;
10820    for symbol in symbols {
10821        let language = language_registry
10822            .language_for_file_path(&symbol.path.path)
10823            .await
10824            .ok()
10825            .or_else(|| {
10826                unknown_path.get_or_insert(symbol.path.path.clone());
10827                default_language.clone()
10828            });
10829        symbols_by_language
10830            .entry(language)
10831            .or_default()
10832            .push(symbol);
10833    }
10834
10835    if let Some(unknown_path) = unknown_path {
10836        log::info!(
10837            "no language found for symbol path {}",
10838            unknown_path.display()
10839        );
10840    }
10841
10842    let mut label_params = Vec::new();
10843    for (language, mut symbols) in symbols_by_language {
10844        label_params.clear();
10845        label_params.extend(
10846            symbols
10847                .iter_mut()
10848                .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
10849        );
10850
10851        let mut labels = Vec::new();
10852        if let Some(language) = language {
10853            let lsp_adapter = lsp_adapter
10854                .clone()
10855                .or_else(|| language_registry.lsp_adapters(&language).first().cloned());
10856            if let Some(lsp_adapter) = lsp_adapter {
10857                labels = lsp_adapter
10858                    .labels_for_symbols(&label_params, &language)
10859                    .await
10860                    .log_err()
10861                    .unwrap_or_default();
10862            }
10863        }
10864
10865        for ((symbol, (name, _)), label) in symbols
10866            .into_iter()
10867            .zip(label_params.drain(..))
10868            .zip(labels.into_iter().chain(iter::repeat(None)))
10869        {
10870            output.push(Symbol {
10871                language_server_name: symbol.language_server_name,
10872                source_worktree_id: symbol.source_worktree_id,
10873                path: symbol.path,
10874                label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
10875                name,
10876                kind: symbol.kind,
10877                range: symbol.range,
10878                signature: symbol.signature,
10879            });
10880        }
10881    }
10882}
10883
10884async fn populate_labels_for_completions(
10885    mut new_completions: Vec<CoreCompletion>,
10886    language_registry: &Arc<LanguageRegistry>,
10887    language: Option<Arc<Language>>,
10888    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10889    completions: &mut Vec<Completion>,
10890) {
10891    let lsp_completions = new_completions
10892        .iter_mut()
10893        .map(|completion| mem::take(&mut completion.lsp_completion))
10894        .collect::<Vec<_>>();
10895
10896    let labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
10897        lsp_adapter
10898            .labels_for_completions(&lsp_completions, language)
10899            .await
10900            .log_err()
10901            .unwrap_or_default()
10902    } else {
10903        Vec::new()
10904    };
10905
10906    for ((completion, lsp_completion), label) in new_completions
10907        .into_iter()
10908        .zip(lsp_completions)
10909        .zip(labels.into_iter().chain(iter::repeat(None)))
10910    {
10911        let documentation = if let Some(docs) = &lsp_completion.documentation {
10912            Some(prepare_completion_documentation(docs, &language_registry, language.clone()).await)
10913        } else {
10914            None
10915        };
10916
10917        completions.push(Completion {
10918            old_range: completion.old_range,
10919            new_text: completion.new_text,
10920            label: label.unwrap_or_else(|| {
10921                CodeLabel::plain(
10922                    lsp_completion.label.clone(),
10923                    lsp_completion.filter_text.as_deref(),
10924                )
10925            }),
10926            server_id: completion.server_id,
10927            documentation,
10928            lsp_completion,
10929            confirm: None,
10930            show_new_completions_on_confirm: false,
10931        })
10932    }
10933}
10934
10935fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
10936    code_actions
10937        .iter()
10938        .flat_map(|(kind, enabled)| {
10939            if *enabled {
10940                Some(kind.clone().into())
10941            } else {
10942                None
10943            }
10944        })
10945        .collect()
10946}
10947
10948#[allow(clippy::too_many_arguments)]
10949async fn search_snapshots(
10950    snapshots: &Vec<LocalSnapshot>,
10951    worker_start_ix: usize,
10952    worker_end_ix: usize,
10953    query: &SearchQuery,
10954    results_tx: &Sender<SearchMatchCandidate>,
10955    opened_buffers: &HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
10956    include_root: bool,
10957    fs: &Arc<dyn Fs>,
10958) {
10959    let mut snapshot_start_ix = 0;
10960    let mut abs_path = PathBuf::new();
10961
10962    for snapshot in snapshots {
10963        let snapshot_end_ix = snapshot_start_ix
10964            + if query.include_ignored() {
10965                snapshot.file_count()
10966            } else {
10967                snapshot.visible_file_count()
10968            };
10969        if worker_end_ix <= snapshot_start_ix {
10970            break;
10971        } else if worker_start_ix > snapshot_end_ix {
10972            snapshot_start_ix = snapshot_end_ix;
10973            continue;
10974        } else {
10975            let start_in_snapshot = worker_start_ix.saturating_sub(snapshot_start_ix);
10976            let end_in_snapshot = cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
10977
10978            for entry in snapshot
10979                .files(false, start_in_snapshot)
10980                .take(end_in_snapshot - start_in_snapshot)
10981            {
10982                if results_tx.is_closed() {
10983                    break;
10984                }
10985                if opened_buffers.contains_key(&entry.path) {
10986                    continue;
10987                }
10988
10989                let matched_path = if include_root {
10990                    let mut full_path = PathBuf::from(snapshot.root_name());
10991                    full_path.push(&entry.path);
10992                    query.file_matches(Some(&full_path))
10993                } else {
10994                    query.file_matches(Some(&entry.path))
10995                };
10996
10997                let matches = if matched_path {
10998                    abs_path.clear();
10999                    abs_path.push(&snapshot.abs_path());
11000                    abs_path.push(&entry.path);
11001                    if let Some(file) = fs.open_sync(&abs_path).await.log_err() {
11002                        query.detect(file).unwrap_or(false)
11003                    } else {
11004                        false
11005                    }
11006                } else {
11007                    false
11008                };
11009
11010                if matches {
11011                    let project_path = SearchMatchCandidate::Path {
11012                        worktree_id: snapshot.id(),
11013                        path: entry.path.clone(),
11014                        is_ignored: entry.is_ignored,
11015                    };
11016                    if results_tx.send(project_path).await.is_err() {
11017                        return;
11018                    }
11019                }
11020            }
11021
11022            snapshot_start_ix = snapshot_end_ix;
11023        }
11024    }
11025}
11026
11027async fn search_ignored_entry(
11028    snapshot: &LocalSnapshot,
11029    ignored_entry: &Entry,
11030    fs: &Arc<dyn Fs>,
11031    query: &SearchQuery,
11032    counter_tx: &Sender<SearchMatchCandidate>,
11033) {
11034    let mut ignored_paths_to_process =
11035        VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
11036
11037    while let Some(ignored_abs_path) = ignored_paths_to_process.pop_front() {
11038        let metadata = fs
11039            .metadata(&ignored_abs_path)
11040            .await
11041            .with_context(|| format!("fetching fs metadata for {ignored_abs_path:?}"))
11042            .log_err()
11043            .flatten();
11044
11045        if let Some(fs_metadata) = metadata {
11046            if fs_metadata.is_dir {
11047                let files = fs
11048                    .read_dir(&ignored_abs_path)
11049                    .await
11050                    .with_context(|| format!("listing ignored path {ignored_abs_path:?}"))
11051                    .log_err();
11052
11053                if let Some(mut subfiles) = files {
11054                    while let Some(subfile) = subfiles.next().await {
11055                        if let Some(subfile) = subfile.log_err() {
11056                            ignored_paths_to_process.push_back(subfile);
11057                        }
11058                    }
11059                }
11060            } else if !fs_metadata.is_symlink {
11061                if !query.file_matches(Some(&ignored_abs_path))
11062                    || snapshot.is_path_excluded(&ignored_entry.path)
11063                {
11064                    continue;
11065                }
11066                let matches = if let Some(file) = fs
11067                    .open_sync(&ignored_abs_path)
11068                    .await
11069                    .with_context(|| format!("Opening ignored path {ignored_abs_path:?}"))
11070                    .log_err()
11071                {
11072                    query.detect(file).unwrap_or(false)
11073                } else {
11074                    false
11075                };
11076
11077                if matches {
11078                    let project_path = SearchMatchCandidate::Path {
11079                        worktree_id: snapshot.id(),
11080                        path: Arc::from(
11081                            ignored_abs_path
11082                                .strip_prefix(snapshot.abs_path())
11083                                .expect("scanning worktree-related files"),
11084                        ),
11085                        is_ignored: true,
11086                    };
11087                    if counter_tx.send(project_path).await.is_err() {
11088                        return;
11089                    }
11090                }
11091            }
11092        }
11093    }
11094}
11095
11096fn glob_literal_prefix(glob: &str) -> &str {
11097    let mut literal_end = 0;
11098    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
11099        if part.contains(&['*', '?', '{', '}']) {
11100            break;
11101        } else {
11102            if i > 0 {
11103                // Account for separator prior to this part
11104                literal_end += path::MAIN_SEPARATOR.len_utf8();
11105            }
11106            literal_end += part.len();
11107        }
11108    }
11109    &glob[..literal_end]
11110}
11111
11112impl WorktreeHandle {
11113    pub fn upgrade(&self) -> Option<Model<Worktree>> {
11114        match self {
11115            WorktreeHandle::Strong(handle) => Some(handle.clone()),
11116            WorktreeHandle::Weak(handle) => handle.upgrade(),
11117        }
11118    }
11119
11120    pub fn handle_id(&self) -> usize {
11121        match self {
11122            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
11123            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
11124        }
11125    }
11126}
11127
11128impl OpenBuffer {
11129    pub fn upgrade(&self) -> Option<Model<Buffer>> {
11130        match self {
11131            OpenBuffer::Strong(handle) => Some(handle.clone()),
11132            OpenBuffer::Weak(handle) => handle.upgrade(),
11133            OpenBuffer::Operations(_) => None,
11134        }
11135    }
11136}
11137
11138pub struct PathMatchCandidateSet {
11139    pub snapshot: Snapshot,
11140    pub include_ignored: bool,
11141    pub include_root_name: bool,
11142    pub directories_only: bool,
11143}
11144
11145impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
11146    type Candidates = PathMatchCandidateSetIter<'a>;
11147
11148    fn id(&self) -> usize {
11149        self.snapshot.id().to_usize()
11150    }
11151
11152    fn len(&self) -> usize {
11153        if self.include_ignored {
11154            self.snapshot.file_count()
11155        } else {
11156            self.snapshot.visible_file_count()
11157        }
11158    }
11159
11160    fn prefix(&self) -> Arc<str> {
11161        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
11162            self.snapshot.root_name().into()
11163        } else if self.include_root_name {
11164            format!("{}/", self.snapshot.root_name()).into()
11165        } else {
11166            "".into()
11167        }
11168    }
11169
11170    fn candidates(&'a self, start: usize) -> Self::Candidates {
11171        PathMatchCandidateSetIter {
11172            traversal: if self.directories_only {
11173                self.snapshot.directories(self.include_ignored, start)
11174            } else {
11175                self.snapshot.files(self.include_ignored, start)
11176            },
11177        }
11178    }
11179}
11180
11181pub struct PathMatchCandidateSetIter<'a> {
11182    traversal: Traversal<'a>,
11183}
11184
11185impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
11186    type Item = fuzzy::PathMatchCandidate<'a>;
11187
11188    fn next(&mut self) -> Option<Self::Item> {
11189        self.traversal.next().map(|entry| match entry.kind {
11190            EntryKind::Dir => fuzzy::PathMatchCandidate {
11191                path: &entry.path,
11192                char_bag: CharBag::from_iter(entry.path.to_string_lossy().to_lowercase().chars()),
11193            },
11194            EntryKind::File(char_bag) => fuzzy::PathMatchCandidate {
11195                path: &entry.path,
11196                char_bag,
11197            },
11198            EntryKind::UnloadedDir | EntryKind::PendingDir => unreachable!(),
11199        })
11200    }
11201}
11202
11203impl EventEmitter<Event> for Project {}
11204
11205impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
11206    fn into(self) -> SettingsLocation<'a> {
11207        SettingsLocation {
11208            worktree_id: self.worktree_id.to_usize(),
11209            path: self.path.as_ref(),
11210        }
11211    }
11212}
11213
11214impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
11215    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
11216        Self {
11217            worktree_id,
11218            path: path.as_ref().into(),
11219        }
11220    }
11221}
11222
11223pub struct ProjectLspAdapterDelegate {
11224    project: WeakModel<Project>,
11225    worktree: worktree::Snapshot,
11226    fs: Arc<dyn Fs>,
11227    http_client: Arc<dyn HttpClient>,
11228    language_registry: Arc<LanguageRegistry>,
11229    shell_env: Mutex<Option<HashMap<String, String>>>,
11230}
11231
11232impl ProjectLspAdapterDelegate {
11233    pub fn new(
11234        project: &Project,
11235        worktree: &Model<Worktree>,
11236        cx: &ModelContext<Project>,
11237    ) -> Arc<Self> {
11238        Arc::new(Self {
11239            project: cx.weak_model(),
11240            worktree: worktree.read(cx).snapshot(),
11241            fs: project.fs.clone(),
11242            http_client: project.client.http_client(),
11243            language_registry: project.languages.clone(),
11244            shell_env: Default::default(),
11245        })
11246    }
11247
11248    async fn load_shell_env(&self) {
11249        let worktree_abs_path = self.worktree.abs_path();
11250        let shell_env = load_shell_environment(&worktree_abs_path)
11251            .await
11252            .with_context(|| {
11253                format!("failed to determine load login shell environment in {worktree_abs_path:?}")
11254            })
11255            .log_err()
11256            .unwrap_or_default();
11257        *self.shell_env.lock() = Some(shell_env);
11258    }
11259}
11260
11261#[async_trait]
11262impl LspAdapterDelegate for ProjectLspAdapterDelegate {
11263    fn show_notification(&self, message: &str, cx: &mut AppContext) {
11264        self.project
11265            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())))
11266            .ok();
11267    }
11268
11269    fn http_client(&self) -> Arc<dyn HttpClient> {
11270        self.http_client.clone()
11271    }
11272
11273    fn worktree_id(&self) -> u64 {
11274        self.worktree.id().to_proto()
11275    }
11276
11277    fn worktree_root_path(&self) -> &Path {
11278        self.worktree.abs_path().as_ref()
11279    }
11280
11281    async fn shell_env(&self) -> HashMap<String, String> {
11282        self.load_shell_env().await;
11283        self.shell_env.lock().as_ref().cloned().unwrap_or_default()
11284    }
11285
11286    #[cfg(not(target_os = "windows"))]
11287    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11288        let worktree_abs_path = self.worktree.abs_path();
11289        self.load_shell_env().await;
11290        let shell_path = self
11291            .shell_env
11292            .lock()
11293            .as_ref()
11294            .and_then(|shell_env| shell_env.get("PATH").cloned());
11295        which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
11296    }
11297
11298    #[cfg(target_os = "windows")]
11299    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11300        // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
11301        //               there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
11302        //               SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
11303        which::which(command).ok()
11304    }
11305
11306    fn update_status(
11307        &self,
11308        server_name: LanguageServerName,
11309        status: language::LanguageServerBinaryStatus,
11310    ) {
11311        self.language_registry
11312            .update_lsp_status(server_name, status);
11313    }
11314
11315    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
11316        if self.worktree.entry_for_path(&path).is_none() {
11317            return Err(anyhow!("no such path {path:?}"));
11318        }
11319        let path = self.worktree.absolutize(path.as_ref())?;
11320        let content = self.fs.load(&path).await?;
11321        Ok(content)
11322    }
11323}
11324
11325fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
11326    proto::Symbol {
11327        language_server_name: symbol.language_server_name.0.to_string(),
11328        source_worktree_id: symbol.source_worktree_id.to_proto(),
11329        worktree_id: symbol.path.worktree_id.to_proto(),
11330        path: symbol.path.path.to_string_lossy().to_string(),
11331        name: symbol.name.clone(),
11332        kind: unsafe { mem::transmute(symbol.kind) },
11333        start: Some(proto::PointUtf16 {
11334            row: symbol.range.start.0.row,
11335            column: symbol.range.start.0.column,
11336        }),
11337        end: Some(proto::PointUtf16 {
11338            row: symbol.range.end.0.row,
11339            column: symbol.range.end.0.column,
11340        }),
11341        signature: symbol.signature.to_vec(),
11342    }
11343}
11344
11345fn relativize_path(base: &Path, path: &Path) -> PathBuf {
11346    let mut path_components = path.components();
11347    let mut base_components = base.components();
11348    let mut components: Vec<Component> = Vec::new();
11349    loop {
11350        match (path_components.next(), base_components.next()) {
11351            (None, None) => break,
11352            (Some(a), None) => {
11353                components.push(a);
11354                components.extend(path_components.by_ref());
11355                break;
11356            }
11357            (None, _) => components.push(Component::ParentDir),
11358            (Some(a), Some(b)) if components.is_empty() && a == b => (),
11359            (Some(a), Some(Component::CurDir)) => components.push(a),
11360            (Some(a), Some(_)) => {
11361                components.push(Component::ParentDir);
11362                for _ in base_components {
11363                    components.push(Component::ParentDir);
11364                }
11365                components.push(a);
11366                components.extend(path_components.by_ref());
11367                break;
11368            }
11369        }
11370    }
11371    components.iter().map(|c| c.as_os_str()).collect()
11372}
11373
11374fn resolve_path(base: &Path, path: &Path) -> PathBuf {
11375    let mut result = base.to_path_buf();
11376    for component in path.components() {
11377        match component {
11378            Component::ParentDir => {
11379                result.pop();
11380            }
11381            Component::CurDir => (),
11382            _ => result.push(component),
11383        }
11384    }
11385    result
11386}
11387
11388impl Item for Buffer {
11389    fn try_open(
11390        project: &Model<Project>,
11391        path: &ProjectPath,
11392        cx: &mut AppContext,
11393    ) -> Option<Task<Result<Model<Self>>>> {
11394        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
11395    }
11396
11397    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
11398        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
11399    }
11400
11401    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
11402        File::from_dyn(self.file()).map(|file| ProjectPath {
11403            worktree_id: file.worktree_id(cx),
11404            path: file.path().clone(),
11405        })
11406    }
11407}
11408
11409impl Completion {
11410    /// A key that can be used to sort completions when displaying
11411    /// them to the user.
11412    pub fn sort_key(&self) -> (usize, &str) {
11413        let kind_key = match self.lsp_completion.kind {
11414            Some(lsp::CompletionItemKind::KEYWORD) => 0,
11415            Some(lsp::CompletionItemKind::VARIABLE) => 1,
11416            _ => 2,
11417        };
11418        (kind_key, &self.label.text[self.label.filter_range.clone()])
11419    }
11420
11421    /// Whether this completion is a snippet.
11422    pub fn is_snippet(&self) -> bool {
11423        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
11424    }
11425}
11426
11427async fn wait_for_loading_buffer(
11428    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
11429) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
11430    loop {
11431        if let Some(result) = receiver.borrow().as_ref() {
11432            match result {
11433                Ok(buffer) => return Ok(buffer.to_owned()),
11434                Err(e) => return Err(e.to_owned()),
11435            }
11436        }
11437        receiver.next().await;
11438    }
11439}
11440
11441fn include_text(server: &lsp::LanguageServer) -> bool {
11442    server
11443        .capabilities()
11444        .text_document_sync
11445        .as_ref()
11446        .and_then(|sync| match sync {
11447            lsp::TextDocumentSyncCapability::Kind(_) => None,
11448            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
11449        })
11450        .and_then(|save_options| match save_options {
11451            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
11452            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
11453        })
11454        .unwrap_or(false)
11455}
11456
11457async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
11458    let marker = "ZED_SHELL_START";
11459    let shell = env::var("SHELL").context(
11460        "SHELL environment variable is not assigned so we can't source login environment variables",
11461    )?;
11462
11463    // What we're doing here is to spawn a shell and then `cd` into
11464    // the project directory to get the env in there as if the user
11465    // `cd`'d into it. We do that because tools like direnv, asdf, ...
11466    // hook into `cd` and only set up the env after that.
11467    //
11468    // In certain shells we need to execute additional_command in order to
11469    // trigger the behavior of direnv, etc.
11470    //
11471    //
11472    // The `exit 0` is the result of hours of debugging, trying to find out
11473    // why running this command here, without `exit 0`, would mess
11474    // up signal process for our process so that `ctrl-c` doesn't work
11475    // anymore.
11476    //
11477    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
11478    // do that, but it does, and `exit 0` helps.
11479    let additional_command = PathBuf::from(&shell)
11480        .file_name()
11481        .and_then(|f| f.to_str())
11482        .and_then(|shell| match shell {
11483            "fish" => Some("emit fish_prompt;"),
11484            _ => None,
11485        });
11486
11487    let command = format!(
11488        "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
11489        dir.display(),
11490        additional_command.unwrap_or("")
11491    );
11492
11493    let output = smol::process::Command::new(&shell)
11494        .args(["-i", "-c", &command])
11495        .output()
11496        .await
11497        .context("failed to spawn login shell to source login environment variables")?;
11498
11499    anyhow::ensure!(
11500        output.status.success(),
11501        "login shell exited with error {:?}",
11502        output.status
11503    );
11504
11505    let stdout = String::from_utf8_lossy(&output.stdout);
11506    let env_output_start = stdout.find(marker).ok_or_else(|| {
11507        anyhow!(
11508            "failed to parse output of `env` command in login shell: {}",
11509            stdout
11510        )
11511    })?;
11512
11513    let mut parsed_env = HashMap::default();
11514    let env_output = &stdout[env_output_start + marker.len()..];
11515
11516    parse_env_output(env_output, |key, value| {
11517        parsed_env.insert(key, value);
11518    });
11519
11520    Ok(parsed_env)
11521}
11522
11523fn serialize_blame_buffer_response(blame: git::blame::Blame) -> proto::BlameBufferResponse {
11524    let entries = blame
11525        .entries
11526        .into_iter()
11527        .map(|entry| proto::BlameEntry {
11528            sha: entry.sha.as_bytes().into(),
11529            start_line: entry.range.start,
11530            end_line: entry.range.end,
11531            original_line_number: entry.original_line_number,
11532            author: entry.author.clone(),
11533            author_mail: entry.author_mail.clone(),
11534            author_time: entry.author_time,
11535            author_tz: entry.author_tz.clone(),
11536            committer: entry.committer.clone(),
11537            committer_mail: entry.committer_mail.clone(),
11538            committer_time: entry.committer_time,
11539            committer_tz: entry.committer_tz.clone(),
11540            summary: entry.summary.clone(),
11541            previous: entry.previous.clone(),
11542            filename: entry.filename.clone(),
11543        })
11544        .collect::<Vec<_>>();
11545
11546    let messages = blame
11547        .messages
11548        .into_iter()
11549        .map(|(oid, message)| proto::CommitMessage {
11550            oid: oid.as_bytes().into(),
11551            message,
11552        })
11553        .collect::<Vec<_>>();
11554
11555    let permalinks = blame
11556        .permalinks
11557        .into_iter()
11558        .map(|(oid, url)| proto::CommitPermalink {
11559            oid: oid.as_bytes().into(),
11560            permalink: url.to_string(),
11561        })
11562        .collect::<Vec<_>>();
11563
11564    proto::BlameBufferResponse {
11565        entries,
11566        messages,
11567        permalinks,
11568        remote_url: blame.remote_url,
11569    }
11570}
11571
11572fn deserialize_blame_buffer_response(response: proto::BlameBufferResponse) -> git::blame::Blame {
11573    let entries = response
11574        .entries
11575        .into_iter()
11576        .filter_map(|entry| {
11577            Some(git::blame::BlameEntry {
11578                sha: git::Oid::from_bytes(&entry.sha).ok()?,
11579                range: entry.start_line..entry.end_line,
11580                original_line_number: entry.original_line_number,
11581                committer: entry.committer,
11582                committer_time: entry.committer_time,
11583                committer_tz: entry.committer_tz,
11584                committer_mail: entry.committer_mail,
11585                author: entry.author,
11586                author_mail: entry.author_mail,
11587                author_time: entry.author_time,
11588                author_tz: entry.author_tz,
11589                summary: entry.summary,
11590                previous: entry.previous,
11591                filename: entry.filename,
11592            })
11593        })
11594        .collect::<Vec<_>>();
11595
11596    let messages = response
11597        .messages
11598        .into_iter()
11599        .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
11600        .collect::<HashMap<_, _>>();
11601
11602    let permalinks = response
11603        .permalinks
11604        .into_iter()
11605        .filter_map(|permalink| {
11606            Some((
11607                git::Oid::from_bytes(&permalink.oid).ok()?,
11608                Url::from_str(&permalink.permalink).ok()?,
11609            ))
11610        })
11611        .collect::<HashMap<_, _>>();
11612
11613    Blame {
11614        entries,
11615        permalinks,
11616        messages,
11617        remote_url: response.remote_url,
11618    }
11619}
11620
11621fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
11622    hover
11623        .contents
11624        .retain(|hover_block| !hover_block.text.trim().is_empty());
11625    if hover.contents.is_empty() {
11626        None
11627    } else {
11628        Some(hover)
11629    }
11630}
11631
11632#[derive(Debug)]
11633pub struct NoRepositoryError {}
11634
11635impl std::fmt::Display for NoRepositoryError {
11636    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11637        write!(f, "no git repository for worktree found")
11638    }
11639}
11640
11641impl std::error::Error for NoRepositoryError {}
11642
11643fn serialize_location(location: &Location, cx: &AppContext) -> proto::Location {
11644    proto::Location {
11645        buffer_id: location.buffer.read(cx).remote_id().into(),
11646        start: Some(serialize_anchor(&location.range.start)),
11647        end: Some(serialize_anchor(&location.range.end)),
11648    }
11649}
11650
11651fn deserialize_location(
11652    project: &Model<Project>,
11653    location: proto::Location,
11654    cx: &mut AppContext,
11655) -> Task<Result<Location>> {
11656    let buffer_id = match BufferId::new(location.buffer_id) {
11657        Ok(id) => id,
11658        Err(e) => return Task::ready(Err(e)),
11659    };
11660    let buffer_task = project.update(cx, |project, cx| {
11661        project.wait_for_remote_buffer(buffer_id, cx)
11662    });
11663    cx.spawn(|_| async move {
11664        let buffer = buffer_task.await?;
11665        let start = location
11666            .start
11667            .and_then(deserialize_anchor)
11668            .context("missing task context location start")?;
11669        let end = location
11670            .end
11671            .and_then(deserialize_anchor)
11672            .context("missing task context location end")?;
11673        Ok(Location {
11674            buffer,
11675            range: start..end,
11676        })
11677    })
11678}