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