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