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