Skip to content

Visual Studio Code, rebuilt in Rust

Rust
57.4 KB
Raw Blame
//! contentHoverController.ts, contentHoverWidgetWrapper.ts and hoverOperation.ts: the hover over the editor's
//! text, from the problem markers and unicode highlights under the mouse and the extensions' hover providers.

use std::cell::Cell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

use futures::channel::oneshot;
use config::configuration::Overrides;
use gpui::{Bounds, Context, FocusHandle, Modifiers, MouseMoveEvent, Pixels, Point, ScrollHandle, Task, Window, px};
use serde_json::{Value, json};

use super::Workbench;
use crate::editor::unicode_highlighter::{CodePointHighlighter, HighlightReason, not_ambiguous_in_locales};
use crate::editor::{OpenEditor, Position, utf16_column, column_x};
use crate::language_features::Candidate;
use crate::markers::{ERROR, INFO, Marker, WARNING};
use crate::workbench::editor_options::MULTI_CURSOR_MODIFIER;

#[derive(Default)]
pub(super) struct ContentHover {
    /// `HoverOperation` with the computer's anchor; it stays after it completes, until the hover hides.
    operation: Option<Operation>,
    /// `_currentResult`: what the widget shows.
    pub(super) shown: Option<Shown>,
    /// `_reactToEditorMouseMoveRunner` and the `_mouseMoveEvent` it reacts to.
    reschedule: Option<Task<()>>,
    last_move: Option<MouseMove>,
    /// The model line and visible column under the mouse, set by the line's row before the text area reacts.
    pub(super) row_target: Option<(usize, f32)>,
    /// The hover's editor drew it since the last render began; set on a new result, which it draws next.
    pub(super) drawn: Cell<bool>,
    /// The widget's window bounds, once painted.
    pub(super) widget_bounds: Rc<Cell<Option<Bounds<f32>>>>,
    /// The rows' height before `max_height` clips them, which `_findPositionPreference` compares to the space.
    pub(super) content_height: Rc<Cell<f32>>,
    /// The widget's padding box width before contentHoverWidget.ts `handleContentsChanged` sets it, per shown result.
    pub(super) natural_width: Rc<Cell<Option<f32>>>,
    serial: usize,
    /// Counts the shows from hidden, which replay the `fade-in` animation.
    pub(super) shows: usize,
    /// ResizableContentWidget: the border box size a sash drag gave the widget, until the next result lays it out.
    pub(super) size: Option<(f32, f32)>,
    /// contentHoverWidget.ts `_lastDimensions`: the last dragged size, a floor of the max size of later hovers.
    pub(super) last_size: (f32, f32),
    pub(super) resize: Option<super::content_hover_view::HoverResize>,
    /// The sash the pointer rests on past `workbench.sash.hoverDelay`.
    pub(super) hovered_sash: Option<usize>,
    pub(super) sash_hover: Option<Task<()>>,
    /// markdownHoverParticipant.ts `_ongoingHoverOperations`: per provider handle, the verbosity delta asked for and
    /// its request; dropping the task cancels the call.
    verbosity_requests: HashMap<u64, (i64, Task<()>)>,
    /// Per rendered part with verbosity actions: how far the row reaches below the hover's visible part.
    pub(super) verbosity_overflow: Rc<std::cell::RefCell<HashMap<usize, f32>>>,
    /// contentHoverWidget.ts `showAt` with `shouldFocus`: the widget takes the focus when it next renders.
    focus_on_show: bool,
    /// contentHoverRendered.ts `_createListenersForPart`: per rendered part (the status bar last), its `tabIndex = 0`.
    pub(super) part_focus: Vec<FocusHandle>,
    /// The `tabIndex = 0` element inside the part at that index that has the focus the part's handle holds.
    focused_stop: Option<(usize, PartStop)>,
    /// The scrollable element of the hover's contents.
    pub(super) scroll: ScrollHandle,
}

/// A `tabIndex = 0` element inside a rendered part: a verbosity action of its delta, the nth markdown link (`<a>`),
/// the marker's code link and nth related information link, the copy button, the status bar's actions.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum PartStop {
    Verbosity(i64),
    Link(usize),
    MarkerCode,
    MarkerRelated(usize),
    Copy,
    ViewProblem,
    QuickFix,
}

/// `HoverRangeAnchor` on one model line: the chars `start..end`, or the empty range at a position.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Anchor {
    pub model_id: u32,
    pub line: usize,
    pub start: usize,
    pub end: usize,
}

#[derive(Clone, Copy)]
pub(super) enum MouseTarget {
    /// The text, or the empty content of a line, at a visible column.
    Text { line: usize, visible: f32 },
    Widget,
    Other,
}

#[derive(Clone, Copy)]
struct MouseMove {
    target: MouseTarget,
    position: Point<f32>,
    modifiers: Modifiers,
}

#[derive(Clone, Copy, PartialEq)]
enum Mode {
    Delayed,
    Immediate,
}

#[derive(Clone, Copy, PartialEq)]
enum State {
    FirstWait,
    SecondWait,
    WaitingForAsync,
    WaitingForAsyncShowingLoading,
    Idle,
}

/// `HoverStartSource`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum HoverSource {
    Mouse,
    Click,
    Keyboard,
}

struct Operation {
    anchor: Anchor,
    source: HoverSource,
    insist: bool,
    /// `shouldFocus`.
    focus: bool,
    initial_mouse: Option<Point<f32>>,
    state: State,
    pending_providers: usize,
    parts: Vec<Part>,
    serial: usize,
    _tasks: Vec<Task<()>>,
}

/// The participants in `hoverOrdinal` order: the widget renders their parts in it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Participant {
    Marker,
    ColorPicker,
    Markdown,
    InlineCompletions,
    Unicode,
}

#[derive(Clone, Debug)]
pub(super) struct Part {
    pub participant: Participant,
    pub ordinal: usize,
    pub start: Position,
    pub end: Position,
    pub content: PartContent,
    pub source: Option<ProviderHover>,
}

/// markdownHoverParticipant.ts `HoverSource`: a provider's hover, which a verbosity request sends back by its id.
#[derive(Clone, Debug)]
pub(super) struct ProviderHover {
    pub handle: u64,
    pub position: Value,
    pub hover: Value,
}

impl ProviderHover {
    /// `supportsVerbosityAction`: `delta` 1 increases, -1 decreases.
    pub(super) fn supports(&self, delta: i64) -> bool {
        let key = if delta > 0 { "canIncreaseVerbosity" } else { "canDecreaseVerbosity" };
        self.hover[key] == true
    }
}

#[derive(Clone, Debug)]
pub(super) enum PartContent {
    Marker(Arc<Marker>),
    /// The `IMarkdownString`s of one hover.
    Markdown(Vec<Value>),
    /// The color picker of `ColorDetector.picker`.
    ColorPicker,
    /// hintsWidget/hoverParticipant.ts: the inline suggestion's toolbar.
    InlineCompletions,
}

/// `ContentHoverResult` as shown, with the widget's `_visibleData` for `isMouseGettingCloser`.
pub(super) struct Shown {
    pub anchor: Anchor,
    pub parts: Vec<Part>,
    complete: bool,
    keyboard: bool,
    initial_mouse: Option<Point<f32>>,
    closest_distance: Option<f32>,
    /// The editor's scroll when shown: `_onEditorScrollChanged` hides on a change.
    scroll: (f32, f32),
}

/// `editor.hover` of the model's language.
pub(super) struct HoverSettings {
    pub(super) enabled: String,
    pub(super) delay: u64,
    pub(super) sticky: bool,
    hiding_delay: u64,
    pub above: bool,
}

/// markdownHoverParticipant.ts `createLoadingMessage`.
const LOADING_ORDINAL: usize = 2000;

/// contentHoverWidget.ts `HORIZONTAL_SCROLLING_BY`.
const HORIZONTAL_SCROLLING_BY: f32 = 30.;

/// The scroll position (`scrollLeft`, `scrollTop`) a hover scroll action asks for, from the current one, the
/// visible height and the largest position.
type HoverScrollTo = fn(Point<f32>, f32, Point<f32>) -> Point<f32>;

impl Workbench {
    pub(super) fn hover_settings(&self, editor: &OpenEditor) -> HoverSettings {
        let settings = self.settings.lock().unwrap();
        let (resource, language) = (editor.document().path.clone(), editor.document().language_id.clone());
        let overrides = Overrides { resource: Some(&resource), override_identifier: Some(&language) };
        let value = |key: &str| settings.get_value(Some(&format!("editor.hover.{key}")), &overrides).unwrap_or(Value::Null);
        HoverSettings {
            // debugEditorContribution.ts `preventDefaultEditorHover` turns the hover off while the debug hover may show.
            enabled: if self.debug_hover.lockout { "off".to_owned() } else { value("enabled").as_str().unwrap_or("on").to_owned() },
            delay: value("delay").as_u64().unwrap_or(300),
            sticky: value("sticky").as_bool().unwrap_or(true),
            hiding_delay: value("hidingDelay").as_u64().unwrap_or(300),
            above: value("above").as_bool().unwrap_or(true),
        }
    }

    /// `editorHoverVisible`.
    pub(super) fn content_hover_visible(&self) -> bool {
        self.content_hover.shown.is_some()
    }

    /// `_onEditorMouseMove`: a move over the text area or the widget.
    pub(super) fn content_hover_mouse_moved(&mut self, target: MouseTarget, position: Point<Pixels>, modifiers: Modifiers, pressed: bool, window: &Window, cx: &mut Context<Self>) {
        let Some(editor) = self.editors.active() else { return };
        let settings = self.hover_settings(editor);
        let on_widget = matches!(target, MouseTarget::Widget);
        let resizing = self.content_hover.resize.is_some();
        let focused = self.content_hover_focused(window);
        // A drag that selects text hides the hover and computes none.
        if pressed && !on_widget && !resizing {
            self.content_hover.reschedule = None;
            self.hide_content_hover(cx);
            return;
        }
        let mouse = MouseMove { target, position: position.map(f32::from), modifiers };
        self.content_hover.last_move = Some(mouse);
        let visible_from_keyboard = self.content_hover.shown.as_ref().is_some_and(|shown| shown.keyboard);
        if resizing || focused || self.hover_accessible_view_shown() || settings.sticky && (on_widget || visible_from_keyboard) {
            self.content_hover.reschedule = None;
            return;
        }
        // `_shouldRescheduleHoverComputation`: a grace period before a visible sticky hover reacts.
        if self.content_hover.shown.is_some() && settings.sticky && settings.hiding_delay > 0 {
            if self.content_hover.reschedule.is_none() {
                let delay = Duration::from_millis(settings.hiding_delay);
                self.content_hover.reschedule = Some(cx.spawn(async move |workbench, cx| {
                    cx.background_executor().timer(delay).await;
                    let _ = workbench.update(cx, |workbench, cx| {
                        workbench.content_hover.reschedule = None;
                        if let Some(mouse) = workbench.content_hover.last_move {
                            workbench.react_to_mouse_move(mouse, cx);
                        }
                    });
                }));
            }
            return;
        }
        self.react_to_mouse_move(mouse, cx);
    }

    /// `_reactToEditorMouseMove`: `shouldShowHover` for `editor.hover.enabled`, then `showsOrWillShow`.
    fn react_to_mouse_move(&mut self, mouse: MouseMove, cx: &mut Context<Self>) {
        let Some(editor) = self.editors.active() else { return };
        let settings = self.hover_settings(editor);
        let show = match settings.enabled.as_str() {
            "on" => true,
            "off" => false,
            // isTriggerModifierPressed: the modifier `editor.multiCursorModifier` leaves free.
            _ => match self.editor_option(editor, &MULTI_CURSOR_MODIFIER) == "alt" {
                true => mouse.modifiers.platform,
                false => mouse.modifiers.alt,
            },
        };
        if show {
            let anchor = match mouse.target {
                MouseTarget::Text { line, visible } => anchor_at(editor, line, visible).or_else(|| self.inline_completions_empty_area_anchor(editor, line)),
                MouseTarget::Widget | MouseTarget::Other => None,
            };
            if self.start_showing_or_update_hover(anchor, Mode::Delayed, HoverSource::Mouse, false, Some(mouse.position), cx) {
                return;
            }
        }
        self.hide_content_hover(cx);
    }

    /// `_onKeyDown` with `editor.hover.enabled` at `onKeyboardModifier`: pressing the trigger modifier shows the
    /// hover for the last mouse move.
    pub(super) fn content_hover_modifiers_changed(&mut self, modifiers: Modifiers, cx: &mut Context<Self>) {
        let Some(editor) = self.editors.active() else { return };
        if self.hover_settings(editor).enabled != "onKeyboardModifier" || self.content_hover.shown.is_some() {
            return;
        }
        if let Some(mouse) = self.content_hover.last_move {
            self.react_to_mouse_move(MouseMove { modifiers, ..mouse }, cx);
        }
    }

    /// A move over unfocused code editor `model_id` with its text area at `origin`, or off it (`None`):
    /// that editor's own `_onEditorMouseMove` and `_onEditorMouseLeave`.
    pub(super) fn code_editor_mouse_moved(&mut self, model_id: u32, origin: Option<Point<Pixels>>, event: &MouseMoveEvent, window: &mut Window, cx: &mut Context<Self>) {
        let Some(origin) = origin else {
            let anchored = |anchor: Option<Anchor>| anchor.is_some_and(|anchor| anchor.model_id == model_id);
            if anchored(self.content_hover.shown.as_ref().map(|shown| shown.anchor)) || anchored(self.content_hover.operation.as_ref().map(|operation| operation.anchor)) {
                self.content_hover_mouse_left(event.position, window, cx);
            }
            return;
        };
        self.with_code_editor(model_id, |workbench| {
            let target = match workbench.active_editor_text_at(origin, event.position, window) {
                (line, visible, true) => MouseTarget::Text { line, visible },
                (_, _, false) => MouseTarget::Other,
            };
            workbench.content_hover_mouse_moved(target, event.position, event.modifiers, false, window, cx);
        });
    }

    /// `_onEditorMouseLeave`: leaving the text area for anywhere but the widget hides it.
    pub(super) fn content_hover_mouse_left(&mut self, mouse: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {
        if self.hover_accessible_view_shown() {
            return;
        }
        self.content_hover.reschedule = None;
        self.content_hover.last_move = None;
        let mouse = mouse.map(f32::from);
        let on_widget = self.content_hover.widget_bounds.get().is_some_and(|bounds| self.content_hover.shown.is_some() && bounds.contains(&mouse));
        if on_widget || self.content_hover.resize.is_some() || self.content_hover_focused(window) {
            return;
        }
        self.hide_content_hover(cx);
    }

    /// `_onKeyDown`: a key hides the hover unless it starts a chord or shows the hover.
    pub(super) fn content_hover_key_down(&mut self, resolution: &crate::keybindings::Resolution, cx: &mut Context<Self>) {
        let potential_shortcut = match resolution {
            crate::keybindings::Resolution::MoreChordsNeeded => true,
            crate::keybindings::Resolution::KbFound { command, .. } => command == "editor.action.showHover" && self.content_hover.shown.is_some(),
            _ => false,
        };
        if !potential_shortcut {
            self.hide_content_hover(cx);
        }
    }

    /// `hideContentHover`: the operation stops and the widget goes.
    pub(super) fn hide_content_hover(&mut self, cx: &mut Context<Self>) {
        self.content_hover.operation = None;
        self.set_content_hover_result(None, cx);
    }

    /// The listeners of the hover's code editor, run on every render: `onDidChangeModel` (it did not draw last frame)
    /// and `_onEditorScrollChanged` hide the hover. The widget takes the focus `showAt` gives it, and `hide` gives
    /// the focus the widget held back to the editor.
    pub(super) fn follow_content_hover_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(shown) = &self.content_hover.shown {
            let drawn = self.content_hover.drawn.replace(false);
            if !drawn || self.editor_scroll(shown.anchor.model_id) != shown.scroll {
                self.content_hover.operation = None;
                self.content_hover.reschedule = None;
                self.content_hover.shown = None;
                self.content_hover.widget_bounds.set(None);
                self.content_hover.resize = None;
            }
        }
        let focus_on_show = std::mem::take(&mut self.content_hover.focus_on_show);
        let Some(shown) = &self.content_hover.shown else {
            if self.content_hover_focused(window) {
                window.focus(&self.editor_focus, cx);
            }
            return;
        };
        let count = hover_parts_count(shown);
        while self.content_hover.part_focus.len() < count {
            self.content_hover.part_focus.push(cx.focus_handle());
        }
        if focus_on_show {
            window.focus(&self.content_hover_focus, cx);
        }
    }

    fn editor_scroll(&self, model_id: u32) -> (f32, f32) {
        self.hover_editor(model_id).map_or((0., 0.), |editor| (editor.scroll.top, editor.scroll.left))
    }

    /// The hover's code editor, in whichever group it is.
    fn hover_editor(&self, model_id: u32) -> Option<&OpenEditor> {
        let mut in_other_groups = self.editors.other_groups.iter().flat_map(|group| &group.editors);
        self.editors.editor_by_id(model_id).or_else(|| in_other_groups.find(|editor| editor.model_id == model_id))
    }

    pub(super) fn register_content_hover_commands(&mut self) {
        // hoverActions.ts ShowOrFocusHoverAction: `focus` is noAutoFocus, focusIfVisible (the default),
        // autoFocusImmediately, or `true` for autoFocusImmediately.
        self.commands.register("editor.action.showHover", |workbench, args, window, cx| {
            let focus = match args.first().map(|args| &args["focus"]) {
                Some(Value::String(focus)) if matches!(focus.as_str(), "noAutoFocus" | "autoFocusImmediately") => focus.clone(),
                Some(Value::Bool(true)) => "autoFocusImmediately".to_owned(),
                _ => "focusIfVisible".to_owned(),
            };
            let accessibility_support = workbench.is_screen_reader_optimized();
            match workbench.content_hover.shown.is_some() {
                true if focus != "noAutoFocus" => workbench.focus_content_hover(window, cx),
                true => workbench.show_content_hover_at_cursor(accessibility_support, cx),
                false => workbench.show_content_hover_at_cursor(accessibility_support || focus == "autoFocusImmediately", cx),
            }
            crate::commands::Outcome::done()
        });
        // hoverActions.ts ScrollUpHoverAction to GoToBottomHoverAction, with the `hoverFocused` precondition, and
        // contentHoverWidget.ts's scrolling by the editor's line height, 30px across, the visible height, or to an end.
        let scrolls: [(&str, HoverScrollTo); 8] = [
            ("editor.action.scrollUpHover", |scroll, _, _| Point::new(scroll.x, scroll.y - crate::editor::LINE_HEIGHT)),
            ("editor.action.scrollDownHover", |scroll, _, _| Point::new(scroll.x, scroll.y + crate::editor::LINE_HEIGHT)),
            ("editor.action.scrollLeftHover", |scroll, _, _| Point::new(scroll.x - HORIZONTAL_SCROLLING_BY, scroll.y)),
            ("editor.action.scrollRightHover", |scroll, _, _| Point::new(scroll.x + HORIZONTAL_SCROLLING_BY, scroll.y)),
            ("editor.action.pageUpHover", |scroll, height, _| Point::new(scroll.x, scroll.y - height)),
            ("editor.action.pageDownHover", |scroll, height, _| Point::new(scroll.x, scroll.y + height)),
            ("editor.action.goToTopHover", |scroll, _, _| Point::new(scroll.x, 0.)),
            ("editor.action.goToBottomHover", |scroll, _, max| Point::new(scroll.x, max.y)),
        ];
        for (command, scroll_to) in scrolls {
            self.commands.register(command, move |workbench, _, window, cx| {
                if workbench.content_hover_focused(window) {
                    workbench.scroll_content_hover(scroll_to, cx);
                }
                crate::commands::Outcome::done()
            });
        }
        self.commands.register("editor.action.hideHover", |workbench, _, _, cx| {
            workbench.hide_content_hover(cx);
            crate::commands::Outcome::done()
        });
        // hoverActions.ts IncreaseHoverVerbosityLevel and DecreaseHoverVerbosityLevel: the part at `index`, else the
        // focused one; -1 or no focused part is every markdown part.
        for (command, delta) in [("editor.action.increaseHoverVerbosityLevel", 1), ("editor.action.decreaseHoverVerbosityLevel", -1)] {
            self.commands.register(command, move |workbench, args, window, cx| {
                let args = args.first();
                let index = match args.and_then(|args| args["index"].as_i64()) {
                    Some(index) => usize::try_from(index).ok(),
                    None => workbench.focused_hover_part_index(window),
                };
                let focus = args.is_some_and(|args| args["focus"] == true);
                workbench.update_hover_verbosity_level(delta, index, focus, window, cx);
                crate::commands::Outcome::done()
            });
        }
    }

    /// scrollableElement.ts `setScrollPosition`. GPUI offsets are negative, and its layout clamps them.
    fn scroll_content_hover(&self, scroll_to: HoverScrollTo, cx: &mut Context<Self>) {
        let scroll = &self.content_hover.scroll;
        let (offset, max) = (scroll.offset().map(f32::from), scroll.max_offset().map(f32::from));
        let target = scroll_to(Point::new(-offset.x, -offset.y), f32::from(scroll.bounds().size.height), max);
        scroll.set_offset(Point::new(px(-target.x), px(-target.y)));
        cx.notify();
    }

    /// contentHoverRendered.ts `doesHoverAtIndexSupportVerbosityAction`: the provider's hover rendered at `index`.
    pub(super) fn hover_part_supports_verbosity(&self, index: usize, delta: i64) -> bool {
        let Some(shown) = &self.content_hover.shown else { return false };
        let mut parts: Vec<&Part> = shown.parts.iter().collect();
        parts.sort_by_key(|part| (part.participant, part.ordinal));
        parts.get(index).and_then(|part| part.source.as_ref()).is_some_and(|source| source.supports(delta))
    }

    /// contentHoverRendered.ts `focusedHoverPartIndex`.
    pub(super) fn focused_hover_part_index(&self, window: &Window) -> Option<usize> {
        self.content_hover.part_focus.iter().position(|focus| focus.is_focused(window))
    }

    /// contentHoverWidget.ts `_hoverFocusedKey`: the focus is in the widget, on its container or one of its parts.
    pub(super) fn content_hover_focused(&self, window: &Window) -> bool {
        self.content_hover_focus.is_focused(window) || self.focused_hover_part_index(window).is_some()
    }

    /// contentHoverWidgetWrapper.ts `focus`: a hover of one rendered part focuses that part, else the container.
    pub(super) fn focus_content_hover(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.content_hover.focused_stop = None;
        match self.content_hover.shown.as_ref().map(hover_parts_count) {
            Some(1) => window.focus(&self.content_hover.part_focus[0], cx),
            _ => window.focus(&self.content_hover_focus, cx),
        }
    }

    /// Tab in the hover, in DOM order: the container, then each rendered part (its `tabIndex = 0`) followed by the
    /// focusable elements inside it. From outside, Shift+Tab enters at the last element
    /// (a Tab in the editor's text hides the hover, contentHoverController.ts `_onKeyDown`).
    /// False at the hover's ends, where the focus leaves it (`move_tab_focus`).
    pub(super) fn tab_in_content_hover(&mut self, backwards: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
        let Some(shown) = &self.content_hover.shown else { return false };
        let count = hover_parts_count(shown);
        let mut order = vec![None];
        for index in 0..count {
            order.push(Some((index, None)));
            for stop in self.hover_part_stops(index) {
                order.push(Some((index, Some(stop))));
            }
        }
        let current = self.focused_hover_part_index(window).map(|index| (index, self.focused_hover_stop(window).map(|(_, stop)| stop)));
        let position = order.iter().position(|element| *element == current).filter(|_| self.content_hover_focused(window));
        let next = match (position, backwards) {
            (None, false) => None,
            (None, true) => Some(order.len() - 1),
            (Some(position), true) => position.checked_sub(1),
            (Some(position), false) => Some(position + 1).filter(|&next| next < order.len()),
        };
        let Some(next) = next else { return false };
        match order[next] {
            Some((index, stop)) => {
                self.content_hover.focused_stop = stop.map(|stop| (index, stop));
                window.focus(&self.content_hover.part_focus[index], cx);
            }
            None => window.focus(&self.content_hover_focus, cx),
        }
        cx.notify();
        true
    }

    /// The part holding the focus and the element inside it that has it.
    pub(super) fn focused_hover_stop(&self, window: &Window) -> Option<(usize, PartStop)> {
        let (index, stop) = self.content_hover.focused_stop?;
        (self.focused_hover_part_index(window) == Some(index) && self.hover_part_stops(index).contains(&stop)).then_some((index, stop))
    }

    /// The focusable elements inside the rendered part at `index`, in DOM order: a markdown part's verbosity actions
    /// (prepended), its links, a marker's code and related information links, then the copy button
    /// (`HoverCopyButton`, appended); the status bar's actions.
    pub(super) fn hover_part_stops(&self, index: usize) -> Vec<PartStop> {
        let Some(shown) = &self.content_hover.shown else { return Vec::new() };
        let mut parts: Vec<&Part> = shown.parts.iter().collect();
        parts.sort_by_key(|part| (part.participant, part.ordinal));
        let mut stops = Vec::new();
        let Some(part) = parts.get(index) else {
            // The status bar, of the first marker.
            let Some(marker) = parts.iter().find_map(|part| part_marker(&part.content)) else { return stops };
            if matches!(marker.severity, ERROR | WARNING | INFO) {
                stops.push(PartStop::ViewProblem);
            }
            if self.active_editor_readonly().is_none() && matches!(self.marker_quick_fix_status(marker), super::code_actions::QuickFixStatus::QuickFix) {
                stops.push(PartStop::QuickFix);
            }
            return stops;
        };
        match &part.content {
            PartContent::Markdown(contents) => {
                if part.source.as_ref().is_some_and(|source| source.supports(1) || source.supports(-1)) {
                    stops.extend([PartStop::Verbosity(1), PartStop::Verbosity(-1)]);
                }
                stops.extend((0..markdown_link_targets(contents).len()).map(PartStop::Link));
            }
            PartContent::Marker(marker) => {
                if marker.code.is_object() {
                    stops.push(PartStop::MarkerCode);
                }
                stops.extend((0..marker.related_information.as_array().map_or(0, Vec::len)).map(PartStop::MarkerRelated));
            }
            PartContent::ColorPicker | PartContent::InlineCompletions => return stops,
        }
        stops.push(PartStop::Copy);
        stops
    }

    /// Enter or Space on the focused element inside a part: `KeyDownAction` of an enabled verbosity action and a
    /// status bar action, the markdown renderer's link activation, `SimpleButton`'s trigger of the copy button.
    /// True when handled.
    pub(super) fn content_hover_stop_key_down(&mut self, keystroke: &gpui::Keystroke, window: &mut Window, cx: &mut Context<Self>) -> bool {
        if !matches!(keystroke.key.as_str(), "enter" | "space") || keystroke.modifiers.modified() {
            return false;
        }
        let Some((index, stop)) = self.focused_hover_stop(window) else { return false };
        let Some(shown) = &self.content_hover.shown else { return false };
        let mut parts: Vec<&Part> = shown.parts.iter().collect();
        parts.sort_by_key(|part| (part.participant, part.ordinal));
        let content = parts.get(index).map(|part| part.content.clone());
        let marker = parts.iter().find_map(|part| part_marker(&part.content).cloned());
        match (stop, content) {
            (PartStop::Verbosity(delta), _) => {
                if !parts[index].source.as_ref().is_some_and(|source| source.supports(delta)) {
                    return false;
                }
                self.update_hover_verbosity_level(delta, Some(index), true, window, cx);
            }
            (PartStop::Link(link), Some(PartContent::Markdown(contents))) => {
                let target = markdown_link_targets(&contents).swap_remove(link);
                self.open_markdown_link(&target, window, cx);
            }
            (PartStop::MarkerCode, Some(PartContent::Marker(marker))) => self.open_marker_code(&marker.code["target"], window, cx),
            (PartStop::MarkerRelated(related), Some(PartContent::Marker(marker))) => {
                self.hide_content_hover(cx);
                self.open_marker_related(&marker.related_information[related], window, cx);
            }
            (PartStop::Copy, _) => {
                let text = self.hover_accessible_content(Some(index), window);
                self.copy_hover_part(text, cx);
            }
            (PartStop::ViewProblem, _) => self.view_problem_from_hover(&marker.expect("the status bar's marker"), window, cx),
            (PartStop::QuickFix, _) => self.show_marker_quick_fixes(cx),
            _ => return false,
        }
        true
    }

    /// hoverCopyButton.ts `_copyContent`.
    pub(super) fn copy_hover_part(&mut self, text: String, cx: &mut Context<Self>) {
        if text.is_empty() {
            return;
        }
        cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
        self.aria_status("Copied to clipboard");
        cx.notify();
    }

    /// contentHoverRendered.ts `updateHoverVerbosityLevel`: asks each provider part at `index` (in the order the
    /// widget renders them) or every one again with the verbosity changed by `delta`; `focus` then focuses that
    /// part, or the hover.
    pub(super) fn update_hover_verbosity_level(&mut self, delta: i64, index: Option<usize>, focus: bool, window: &mut Window, cx: &mut Context<Self>) {
        let Some(shown) = &self.content_hover.shown else { return };
        let Some(editor) = self.hover_editor(shown.anchor.model_id) else { return };
        let uri = editor.document().uri();
        let mut order: Vec<usize> = (0..shown.parts.len()).collect();
        order.sort_by_key(|&position| (shown.parts[position].participant, shown.parts[position].ordinal));
        if let Some(index) = index {
            order = order.get(index).copied().into_iter().collect();
        }
        let sources: Vec<ProviderHover> = order.iter().filter_map(|&position| shown.parts[position].source.clone()).filter(|source| source.supports(delta)).collect();
        for source in sources {
            self.fetch_verbose_hover(source, delta, uri.clone(), cx);
        }
        if !focus {
            return;
        }
        self.content_hover.focused_stop = None;
        match index {
            Some(index) if index < self.content_hover.part_focus.len() => window.focus(&self.content_hover.part_focus[index], cx),
            Some(_) => {}
            None => self.focus_content_hover(window, cx),
        }
    }

    /// markdownHoverParticipant.ts `_fetchHover`: a request still out for the provider is cancelled and its delta
    /// added to this one.
    fn fetch_verbose_hover(&mut self, source: ProviderHover, delta: i64, uri: Value, cx: &mut Context<Self>) {
        let mut delta = delta;
        if let Some((ongoing, _)) = self.content_hover.verbosity_requests.remove(&source.handle) {
            delta += ongoing;
        }
        let context = json!({ "verbosityRequest": { "verbosityDelta": delta, "previousHover": { "id": source.hover["id"] } } });
        let args = vec![json!(source.handle), uri, source.position.clone(), context];
        let call = self.host.call_cancellable("ExtHostLanguageFeatures", "$provideHover", args);
        let handle = source.handle;
        let task = cx.spawn(async move |workbench, cx| {
            let answer = call.await;
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.content_hover.verbosity_requests.remove(&handle);
                if let Ok(Ok(hover)) = answer
                    && !hover.is_null()
                {
                    workbench.replace_verbose_hover(ProviderHover { hover, ..source }, cx);
                }
            });
        });
        self.content_hover.verbosity_requests.insert(handle, (delta, task));
    }

    /// `updateMarkdownHoverPartVerbosityLevel`: the provider's part keeps its range and ordinal, takes the new
    /// contents, and the widget lays itself out again (`onContentsChanged`).
    fn replace_verbose_hover(&mut self, source: ProviderHover, cx: &mut Context<Self>) {
        let Some(shown) = self.content_hover.shown.as_mut() else { return };
        let Some(part) = shown.parts.iter_mut().find(|part| part.source.as_ref().is_some_and(|old| old.handle == source.handle)) else { return };
        part.content = PartContent::Markdown(source.hover["contents"].as_array().cloned().unwrap_or_default());
        part.source = Some(source);
        self.content_hover.size = None;
        self.content_hover.natural_width.set(None);
        cx.notify();
    }

    /// `showContentHover` at the primary cursor, `Immediate` from the keyboard; `focus` focuses the widget it shows.
    pub(super) fn show_content_hover_at_cursor(&mut self, focus: bool, cx: &mut Context<Self>) {
        let Some(editor) = self.editors.active() else { return };
        let head = editor.selection().head;
        let anchor = Anchor { model_id: editor.model_id, line: head.line, start: head.column, end: head.column };
        self.start_showing_or_update_hover(Some(anchor), Mode::Immediate, HoverSource::Keyboard, focus, None, cx);
    }

    /// `showContentHover` at `position` with `Immediate` mode (hoverColorPickerContribution.ts on a click, the debug
    /// hover's fallback).
    pub(super) fn show_content_hover_at(&mut self, position: Position, source: HoverSource, focus: bool, cx: &mut Context<Self>) {
        let Some(editor) = self.editors.active() else { return };
        let anchor = Anchor { model_id: editor.model_id, line: position.line, start: position.column, end: position.column };
        self.start_showing_or_update_hover(Some(anchor), Mode::Immediate, source, focus, None, cx);
    }

    /// `_startShowingOrUpdateHover`: whether the hover shows or will show for `anchor`.
    fn start_showing_or_update_hover(&mut self, anchor: Option<Anchor>, mode: Mode, source: HoverSource, focus: bool, mouse: Option<Point<f32>>, cx: &mut Context<Self>) -> bool {
        if self.content_hover.shown.is_none() {
            let Some(anchor) = anchor else { return false };
            self.start_hover_operation(anchor, mode, source, focus, false, mouse, cx);
            return true;
        }
        let sticky = self.editors.active().is_some_and(|editor| self.hover_settings(editor).sticky);
        if sticky && mouse.is_some_and(|mouse| self.mouse_getting_closer(mouse)) {
            if let Some(anchor) = anchor {
                self.start_hover_operation(anchor, mode, source, focus, true, mouse, cx);
            }
            return true;
        }
        let Some(anchor) = anchor else {
            self.set_content_hover_result(None, cx);
            return false;
        };
        let shown = self.content_hover.shown.as_ref().expect("checked above");
        if shown.anchor == anchor {
            return true;
        }
        // HoverRangeAnchor.canAdoptVisibleHover: the parts still covering the anchor on the same line stay.
        if shown.anchor.model_id != anchor.model_id || shown.anchor.line != anchor.line {
            self.set_content_hover_result(None, cx);
            self.start_hover_operation(anchor, mode, source, focus, false, mouse, cx);
            return true;
        }
        let parts = shown.parts.iter().filter(|part| part.start.column <= anchor.start && part.end.column >= anchor.end).cloned().collect();
        let complete = shown.complete;
        let scroll = self.editor_scroll(anchor.model_id);
        self.set_content_hover_result(Some(Shown { anchor, parts, complete, keyboard: source == HoverSource::Keyboard, initial_mouse: mouse, closest_distance: None, scroll }), cx);
        self.start_hover_operation(anchor, mode, source, focus, false, mouse, cx);
        true
    }

    /// contentHoverWidget.ts `isMouseGettingCloser`: the first move sets where the mouse started, later ones may
    /// stray 4px from the closest the mouse got to the widget.
    fn mouse_getting_closer(&mut self, mouse: Point<f32>) -> bool {
        let bounds = self.content_hover.widget_bounds.get();
        let Some(shown) = self.content_hover.shown.as_mut() else { return false };
        let Some(initial) = shown.initial_mouse else {
            shown.initial_mouse = Some(mouse);
            return false;
        };
        let Some(bounds) = bounds else { return false };
        let closest = *shown.closest_distance.get_or_insert_with(|| distance_to_rectangle(initial, bounds));
        let distance = distance_to_rectangle(mouse, bounds);
        if distance > closest + 4. {
            return false;
        }
        shown.closest_distance = Some(closest.min(distance));
        true
    }

    /// `_startHoverOperationIfNecessary` and `HoverOperation.start`.
    fn start_hover_operation(&mut self, anchor: Anchor, mode: Mode, source: HoverSource, focus: bool, insist: bool, mouse: Option<Point<f32>>, cx: &mut Context<Self>) {
        if self.content_hover.operation.as_ref().is_some_and(|operation| operation.anchor == anchor && operation.source == source) {
            return;
        }
        let Some(editor) = self.editors.active() else { return };
        let delay = self.hover_settings(editor).delay;
        self.content_hover.serial += 1;
        let serial = self.content_hover.serial;
        let state = if mode == Mode::Delayed { State::FirstWait } else { State::WaitingForAsync };
        self.content_hover.operation = Some(Operation { anchor, source, insist, focus, initial_mouse: mouse, state, pending_providers: 0, parts: Vec::new(), serial, _tasks: Vec::new() });
        if mode == Mode::Immediate {
            self.trigger_async_hover(serial, cx);
            self.trigger_sync_hover(serial, cx);
            return;
        }
        // hoverOperation.ts: providers start after half the delay, the sync parts come at the delay, and
        // "Loading..." shows at three times the delay.
        let first_wait = Duration::from_millis(delay / 2);
        let second_wait = Duration::from_millis(delay - delay / 2);
        let loading_wait = Duration::from_millis(3 * delay).saturating_sub(first_wait + second_wait);
        let task = cx.spawn(async move |workbench, cx| {
            cx.background_executor().timer(first_wait).await;
            let _ = workbench.update(cx, |workbench, cx| workbench.trigger_async_hover(serial, cx));
            cx.background_executor().timer(second_wait).await;
            let _ = workbench.update(cx, |workbench, cx| workbench.trigger_sync_hover(serial, cx));
            cx.background_executor().timer(loading_wait).await;
            let _ = workbench.update(cx, |workbench, cx| workbench.trigger_hover_loading(serial, cx));
        });
        if let Some(operation) = self.content_hover.operation.as_mut() {
            operation._tasks.push(task);
        }
    }

    fn operation(&mut self, serial: usize) -> Option<&mut Operation> {
        self.content_hover.operation.as_mut().filter(|operation| operation.serial == serial)
    }

    /// `_triggerAsyncComputation`: markdownHoverParticipant.ts `computeAsync`, each provider's `$provideHover` in
    /// `ordered` order; a dropped operation cancels the calls still out.
    fn trigger_async_hover(&mut self, serial: usize, cx: &mut Context<Self>) {
        let Some((anchor, source)) = self.operation(serial).map(|operation| (operation.anchor, operation.source)) else { return };
        let mut calls = Vec::new();
        let mut color_hover = None;
        if let Some(editor) = self.hover_editor(anchor.model_id) {
            let uri = editor.document().uri();
            let language = editor.document().language_id.clone();
            let candidate = Candidate { uri: &uri, language: &language };
            let column = utf16_column(&editor.document().lines[anchor.line], anchor.start);
            let position = json!({ "lineNumber": anchor.line + 1, "column": column + 1 });
            for (ordinal, registration) in self.language_features.ordered("$registerHoverProvider", &candidate).into_iter().enumerate() {
                let args = vec![json!(registration.handle), uri.clone(), position.clone(), json!({})];
                let source = ProviderHover { handle: registration.handle, position: position.clone(), hover: Value::Null };
                calls.push((ordinal, source, self.host.call_cancellable("ExtHostLanguageFeatures", "$provideHover", args)));
            }
            // hoverColorPickerParticipant.ts `computeAsync`: the color decoration at the anchor.
            let position = Position::new(anchor.line, anchor.start);
            if self.color_hover_allowed(editor, source)
                && let Some(data) = self.color_data_at(editor, position).cloned()
            {
                color_hover = Some((data.start, data.end, self.create_color_hover(editor, &data, cx)));
            }
        }
        let mut tasks = Vec::new();
        for (ordinal, source, call) in calls {
            tasks.push(cx.spawn(async move |workbench, cx| {
                let answer = call.await;
                let _ = workbench.update(cx, |workbench, cx| workbench.hover_provider_answered(serial, ordinal, source, answer, cx));
            }));
        }
        if let Some((start, end, pending)) = color_hover {
            tasks.push(cx.spawn(async move |workbench, cx| {
                let picker = pending.await.ok();
                let _ = workbench.update(cx, |workbench, cx| workbench.color_hover_answered(serial, picker.map(|picker| (start, end, picker)), cx));
            }));
        }
        let Some(operation) = self.operation(serial) else { return };
        operation.pending_providers = tasks.len();
        operation._tasks.extend(tasks);
        if operation.state == State::FirstWait {
            operation.state = State::SecondWait;
        }
    }

    /// One provider's hover: getHover.ts `isValid` keeps only one with a range and contents.
    fn hover_provider_answered(&mut self, serial: usize, ordinal: usize, source: ProviderHover, answer: Result<Result<Value, Value>, oneshot::Canceled>, cx: &mut Context<Self>) {
        let Some(anchor) = self.operation(serial).map(|operation| operation.anchor) else { return };
        let part = match (answer, self.hover_editor(anchor.model_id)) {
            (Ok(Ok(hover)), Some(editor)) if hover["range"].is_object() && !crate::markdown::is_empty(&hover["contents"]) => {
                let (start, end) = super::host_requests::range(editor, &hover["range"]);
                let contents = hover["contents"].as_array().cloned().unwrap_or_default();
                let source = Some(ProviderHover { hover, ..source });
                Some(Part { participant: Participant::Markdown, ordinal, start, end, content: PartContent::Markdown(contents), source })
            }
            _ => None,
        };
        let operation = self.operation(serial).expect("checked above");
        operation.pending_providers -= 1;
        if let Some(part) = part {
            operation.parts.push(part);
            self.fire_hover_result(serial, cx);
        }
        let operation = self.operation(serial).expect("checked above");
        if operation.pending_providers == 0 && matches!(operation.state, State::WaitingForAsync | State::WaitingForAsyncShowingLoading) {
            operation.state = State::Idle;
            self.fire_hover_result(serial, cx);
        }
    }

    /// The color participant's answer: the picker becomes the hover's color picker part.
    fn color_hover_answered(&mut self, serial: usize, answer: Option<(Position, Position, super::color_picker::HoverColorPicker)>, cx: &mut Context<Self>) {
        if self.operation(serial).is_none() {
            return;
        }
        let part = answer.map(|(start, end, picker)| {
            self.color_detector.picker = Some(picker);
            Part { participant: Participant::ColorPicker, ordinal: 0, start, end, content: PartContent::ColorPicker, source: None }
        });
        let operation = self.operation(serial).expect("checked above");
        operation.pending_providers -= 1;
        if let Some(part) = part {
            operation.parts.push(part);
            self.fire_hover_result(serial, cx);
        }
        let operation = self.operation(serial).expect("checked above");
        if operation.pending_providers == 0 && matches!(operation.state, State::WaitingForAsync | State::WaitingForAsyncShowingLoading) {
            operation.state = State::Idle;
            self.fire_hover_result(serial, cx);
        }
    }

    /// `_triggerSyncComputation`: the marker and unicode parts of the anchor's line decorations.
    fn trigger_sync_hover(&mut self, serial: usize, cx: &mut Context<Self>) {
        let Some(anchor) = self.operation(serial).map(|operation| operation.anchor) else { return };
        let parts = match self.hover_editor(anchor.model_id) {
            Some(editor) => {
                let mut parts = marker_parts(editor, anchor);
                parts.extend(self.unicode_parts(editor, anchor));
                parts.extend(self.link_hover_parts(editor, anchor));
                parts.extend(self.definition_link_hover_parts(editor, anchor));
                parts.extend(self.keybinding_mark_hover_parts(editor, anchor));
                parts.extend(self.debug_inline_value_hover_parts(editor, anchor));
                parts.extend(self.coverage_hover_parts(editor, anchor));
                parts.extend(self.inline_completions_hover_parts(editor, anchor));
                parts
            }
            None => Vec::new(),
        };
        // hoverParticipant.ts `renderHoverParts`: the toolbar asks for every item, for its count.
        if parts.iter().any(|part| part.participant == Participant::InlineCompletions) {
            self.trigger_inline_completions_explicitly(cx);
        }
        let operation = self.operation(serial).expect("checked above");
        operation.parts.extend(parts);
        operation.state = if operation.pending_providers == 0 { State::Idle } else { State::WaitingForAsync };
        self.fire_hover_result(serial, cx);
    }

    fn trigger_hover_loading(&mut self, serial: usize, cx: &mut Context<Self>) {
        let Some(operation) = self.operation(serial) else { return };
        if operation.state == State::WaitingForAsync {
            operation.state = State::WaitingForAsyncShowingLoading;
            self.fire_hover_result(serial, cx);
        }
    }

    /// `_fireResult` and the wrapper's `_withResult`: a visible complete hover stays until the new one is complete.
    fn fire_hover_result(&mut self, serial: usize, cx: &mut Context<Self>) {
        let Some(operation) = self.operation(serial) else { return };
        if matches!(operation.state, State::FirstWait | State::SecondWait) {
            return;
        }
        let anchor = operation.anchor;
        let mut parts = operation.parts.clone();
        if operation.state == State::WaitingForAsyncShowingLoading {
            let (start, end) = (Position::new(anchor.line, anchor.start), Position::new(anchor.line, anchor.end));
            parts.push(Part { participant: Participant::Markdown, ordinal: LOADING_ORDINAL, start, end, content: PartContent::Markdown(vec![json!({ "value": "Loading..." })]), source: None });
        }
        let complete = operation.state == State::Idle;
        let (insist, focus, keyboard, initial_mouse) = (operation.insist, operation.focus, operation.source == HoverSource::Keyboard, operation.initial_mouse);
        let scroll = self.editor_scroll(anchor.model_id);
        let result = || Shown { anchor, parts: parts.clone(), complete, keyboard, initial_mouse, closest_distance: None, scroll };
        if !self.content_hover.shown.as_ref().is_some_and(|shown| shown.complete) {
            self.set_content_hover_result(Some(result()), cx);
            self.content_hover.focus_on_show |= focus;
            if !complete {
                return;
            }
        }
        if !complete || (parts.is_empty() && insist) {
            return;
        }
        self.set_content_hover_result(Some(result()), cx);
        self.content_hover.focus_on_show |= focus;
    }

    /// `_setCurrentResult`: an empty result hides the widget.
    fn set_content_hover_result(&mut self, result: Option<Shown>, cx: &mut Context<Self>) {
        let result = result.filter(|result| !result.parts.is_empty());
        if self.content_hover.shown.is_none() && result.is_none() {
            return;
        }
        if self.content_hover.shown.is_none() {
            self.content_hover.shows += 1;
        }
        if result.is_none() {
            self.content_hover.widget_bounds.set(None);
            // `hide`: `clearSashHoverState`, and a drag in progress has no widget left.
            self.content_hover.resize = None;
            self.content_hover.hovered_sash = None;
        }
        // `handleContentsChanged` lays the new contents out at their own size.
        self.content_hover.size = None;
        self.content_hover.verbosity_requests.clear();
        // `handleHide`: the picker goes with a hover that no longer shows it.
        if !result.as_ref().is_some_and(|result| result.parts.iter().any(|part| part.participant == Participant::ColorPicker)) {
            self.color_detector.picker = None;
        }
        self.content_hover.drawn.set(result.is_some());
        self.content_hover.shown = result;
        self.content_hover.natural_width.set(None);
        self.code_actions_hover_changed(cx);
        cx.notify();
    }

    /// unicodeHighlighter.ts UnicodeHighlighterHoverParticipant `computeSync`: one part per reason.
    fn unicode_parts(&self, editor: &OpenEditor, anchor: Anchor) -> Vec<Part> {
        let Some((options, highlights)) = self.unicode_highlights(editor).filter(|(_, highlights)| !highlights.has_more) else { return Vec::new() };
        let highlighter = CodePointHighlighter::new(&options);
        let text = &editor.document().lines[anchor.line];
        let mut reasons = Vec::new();
        let mut parts = Vec::new();
        for (start, end) in highlights.ranges.iter().filter(|(start, _)| start.line == anchor.line) {
            if start.column > anchor.start || anchor.end > end.column {
                continue;
            }
            let Some(c) = text.chars().nth(start.column) else { continue };
            let Some(reason) = highlighter.reason(c, None) else { continue };
            let reason_text = super::unicode_highlight::unicode_hover_reason(c, reason, &highlighter);
            if reasons.contains(&reason_text) {
                continue;
            }
            reasons.push(reason_text.clone());
            let offset = text.char_indices().nth(start.column).map_or(text.len(), |(offset, _)| offset);
            let token = editor.document().tokens.token_type_at(&editor.document().lines, anchor.line, offset);
            let args = json!({
                "codePoint": c as u32,
                "reason": unicode_reason_value(reason, &highlighter, &options.allowed_locales, c),
                "inComment": token == textmate::StandardTokenType::Comment,
                "inString": token == textmate::StandardTokenType::String,
            });
            let uri = format!("command:editor.action.unicodeHighlight.showExcludeOptions?{}", encode_uri_component(&args.to_string()));
            let value = format!("{reason_text}&nbsp;[Adjust settings]({uri} \"Configure Unicode Highlight Options\")");
            let content = PartContent::Markdown(vec![json!({ "value": value, "isTrusted": true })]);
            parts.push(Part { participant: Participant::Unicode, ordinal: 300 + parts.len(), start: *start, end: *end, content, source: None });
        }
        parts
    }
}

/// markerHoverParticipant.ts `computeSync` over contentHoverComputer.ts `_getLineDecorations`: marker
/// decorations are `showIfCollapsed`, so they take an anchor one column beyond either end.
/// contentHoverRendered.ts `hoverPartsCount`: the parts, and the status bar a marker part brings.
/// The targets of the links of a markdown part's non-empty contents, in the order they draw.
pub(super) fn markdown_link_targets(contents: &[Value]) -> Vec<String> {
    let mut targets = Vec::new();
    for content in contents.iter().filter(|content| !crate::markdown::is_empty(content)) {
        let mut blocks = crate::markdown::parse(&crate::markdown::MarkdownString::from_value(content));
        targets.extend(super::hover::link_spans(&mut blocks).into_iter().filter_map(|spans| spans[0].link.clone()));
    }
    targets
}

fn part_marker(content: &PartContent) -> Option<&Arc<Marker>> {
    match content {
        PartContent::Marker(marker) => Some(marker),
        PartContent::Markdown(_) | PartContent::ColorPicker | PartContent::InlineCompletions => None,
    }
}

fn hover_parts_count(shown: &Shown) -> usize {
    let status_bar = shown.parts.iter().any(|part| matches!(part.content, PartContent::Marker(_)));
    shown.parts.len() + usize::from(status_bar)
}

fn marker_parts(editor: &OpenEditor, anchor: Anchor) -> Vec<Part> {
    let line = anchor.line;
    let max_column = editor.document().lines[line].chars().count();
    let mut parts = Vec::new();
    for decoration in editor.text_model().markers.iter().filter(|decoration| decoration.start.line <= line && decoration.end.line >= line) {
        let start = if decoration.start.line == line { decoration.start.column } else { 0 };
        let end = if decoration.end.line == line { decoration.end.column } else { max_column };
        if start > anchor.start + 1 || anchor.end as isize - 1 > end as isize {
            continue;
        }
        // MarkerSeverity.compare sorts the most severe first.
        let ordinal = 16 - decoration.marker.severity as usize;
        parts.push(Part { participant: Participant::Marker, ordinal, start: Position::new(line, start), end: Position::new(line, end), content: PartContent::Marker(decoration.marker.clone()), source: None });
    }
    parts
}

/// contentHoverWidgetWrapper.ts `_findHoverAnchorCandidates` for a mouse target: the char under the mouse, or the
/// end of the line when the mouse is less than half a char past it (mouseTarget.ts `createMouseTargetFromHitTestPosition`).
pub(super) fn anchor_at(editor: &OpenEditor, line: usize, visible: f32) -> Option<Anchor> {
    let document = editor.document();
    let text = document.lines.get(line)?;
    let tab_size = editor.document().indentation.tab_size;
    let count = text.chars().count();
    let width = column_x(text, count, tab_size);
    let empty = |column| Anchor { model_id: editor.model_id, line, start: column, end: column };
    if visible >= width {
        return (visible - width < 0.5).then(|| empty(count));
    }
    let mut column_left = 0;
    for (index, c) in text.chars().enumerate() {
        column_left += if c == '\t' { tab_size - column_left % tab_size } else { 1 };
        if visible < column_left as f32 {
            return Some(Anchor { model_id: editor.model_id, line, start: index, end: index + 1 });
        }
    }
    Some(empty(count))
}

/// `computeDistanceFromPointToRectangle`.
fn distance_to_rectangle(point: Point<f32>, bounds: Bounds<f32>) -> f32 {
    let x = point.x.clamp(bounds.origin.x, bounds.origin.x + bounds.size.width);
    let y = point.y.clamp(bounds.origin.y, bounds.origin.y + bounds.size.height);
    ((point.x - x).powi(2) + (point.y - y).powi(2)).sqrt()
}

/// `formatCodePointMarkdown`: the `U+XXXX` code and, for a visible char, the char as inline code.
pub(super) fn format_code_point_markdown(c: char) -> String {
    let code = format!("`{}`", code_point_to_hex(c));
    match crate::editor::unicode_highlighter::is_invisible_character(c) {
        true => code,
        false if c == '`' => format!("{code} \"`` ` ``\""),
        false => format!("{code} \"`{c}`\""),
    }
}

/// `codePointToHex`: lowercase, as `toString(16)` writes it.
pub(super) fn code_point_to_hex(c: char) -> String {
    format!("U+{:04x}", c as u32)
}

/// `UnicodeHighlighterReason` as `ShowExcludeOptionsArgs` carries it.
fn unicode_reason_value(reason: HighlightReason, highlighter: &CodePointHighlighter, allowed_locales: &[String], c: char) -> Value {
    match reason {
        HighlightReason::Ambiguous => {
            let confusable = highlighter.ambiguous.get(&(c as u32)).and_then(|code| char::from_u32(*code)).unwrap_or(c);
            json!({ "kind": 0, "confusableWith": confusable.to_string(), "notAmbiguousInLocales": not_ambiguous_in_locales(c, allowed_locales) })
        }
        HighlightReason::Invisible => json!({ "kind": 1 }),
        HighlightReason::NonBasicAscii => json!({ "kind": 2 }),
    }
}

/// `encodeURIComponent`.
pub(super) fn encode_uri_component(text: &str) -> String {
    let mut encoded = String::new();
    for byte in text.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' => encoded.push(byte as char),
            _ => encoded.push_str(&format!("%{byte:02X}")),
        }
    }
    encoded
}

#[cfg(test)]
mod tests;