project.rs

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