project.rs

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