project.rs

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