Skip to content

Visual Studio Code, rebuilt in Rust

Rust
38.0 KB
Raw Blame
//! contentHoverWidget.ts and the participants' `renderHoverParts`: the hover box above or below its anchor, the
//! marker, markdown and unicode rows, their copy buttons, the status bar, and the `hoverHighlight` decoration.

use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;

use gpui::{
    Animation, AnimationExt, AnyElement, Bounds, BoxShadow, ClickEvent, Context, CursorStyle, Div, MouseButton, MouseDownEvent, MouseMoveEvent,
    MouseUpEvent, Point, SharedString, Size, Stateful, Window, canvas, deferred, div, point, prelude::*, px, rgba,
};
use serde_json::Value;

use super::Workbench;
use super::content_hover::{MouseTarget, Part, PartContent, PartStop, ProviderHover, Shown};
use super::hover::HoverOptions;
use super::editor_message::horizontal_in_page;
use super::markdown_view::MarkdownStyle;
use crate::editor::{LINE_HEIGHT, OpenEditor, Position};
use crate::markdown::{MarkdownString, parse, plain_text};
use crate::markers::{ERROR, HINT, INFO, Marker, WARNING};

const UI_FONT: &str = ".SystemUIFont";
const EDITOR_FONT: &str = "Menlo";
const EDITOR_FONT_SIZE: f32 = 12.;
/// cornerRadius-large.
pub(super) const RADIUS: f32 = 8.;
/// sash.ts `size`, centered on the widget's edges.
const SASH_SIZE: f32 = 4.;
/// contentHoverWidget.ts `minimumSize`'s width.
const MIN_WIDTH: f32 = 150.;
/// resizableContentWidget.ts TOP_HEIGHT and BOTTOM_HEIGHT.
const TOP_HEIGHT: f32 = 30.;
const BOTTOM_HEIGHT: f32 = 24.;

impl Workbench {
    /// contentHoverRendered.ts `_createEditorDecorations`: `.hoverHighlight` over the union of the parts' ranges on
    /// model line `index`.
    pub(super) fn content_hover_highlight(&self, editor: &OpenEditor, index: usize, char_width: f32) -> Option<Div> {
        let shown = self.content_hover.shown.as_ref().filter(|shown| shown.anchor.model_id == editor.model_id)?;
        let (start, end) = highlight_range(&shown.parts)?;
        if index < start.line || index > end.line {
            return None;
        }
        let text = &editor.document().lines[index];
        let from = if index == start.line { start.column } else { 0 };
        let to = if index == end.line { end.column } else { text.chars().count() };
        let (left, right) = editor.line_layout(index).range(from, to);
        let (left, right) = (left * char_width, right * char_width);
        Some(div().absolute().top_0().h_full().left(px(left)).w(px(right - left)).bg(self.color("editor.hoverHighlightBackground")))
    }

    /// The widget over the text area: at the anchor's start, pulled toward the parts' start (`showAtSecondaryPosition`),
    /// above the line when `editor.hover.above` and it fits, else below (`_findPositionPreference`).
    pub(super) fn content_hover_widget(&self, editor: &OpenEditor, content_left: f32, char_width: f32, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
        let shown = self.content_hover.shown.as_ref().filter(|shown| shown.anchor.model_id == editor.model_id)?;
        self.content_hover.drawn.set(true);
        let anchor = shown.anchor;
        if anchor.line >= editor.document().lines.len() || editor.folding.is_hidden(anchor.line) {
            return None;
        }
        let mut secondary = anchor.start;
        for part in shown.parts.iter().filter(|part| part.start.line == anchor.line && part.end.line == anchor.line) {
            secondary = secondary.min(part.start.column);
        }
        let view_line = editor.position_view_line(Position::new(anchor.line, anchor.start), false);
        let segment = editor.segment(view_line);
        let primary_left = editor.segment_pixel_left(segment, anchor.start, char_width);
        let secondary_left = editor.segment_pixel_left(segment, secondary.max(segment.start), char_width);
        // The measuring canvas fills the padding box: add the 1px border on each side.
        let measured = self.content_hover.widget_bounds.get().map(|bounds| Size { width: bounds.size.width + 2., height: bounds.size.height + 2. });
        let mut size = measured.unwrap_or(Size { width: 0., height: 0. });
        if measured.is_some() {
            size.height = self.content_hover.content_height.get() + 2.;
        }
        let user_size = self.content_hover.size;
        if let Some((width, height)) = user_size {
            size = Size { width, height };
        }
        // contentWidgets.ts `_reduceAnchorCoordinates`: a full-width glyph is 1em of the editor font.
        let left = secondary_left.max(primary_left - size.width + EDITOR_FONT_SIZE);
        let editor_bounds = self.text_area_bounds.get();
        let window_size = window.viewport_size().map(f32::from);
        let left = horizontal_in_page(left - editor.scroll.left + content_left, size.width, editor_bounds, window_size);
        let anchor_top = editor.line_top(view_line, self.editors.viewport) - editor.scroll.top;
        let space_above = editor_bounds.origin.y + anchor_top - TOP_HEIGHT;
        let space_below = window_size.height - (editor_bounds.origin.y + anchor_top + LINE_HEIGHT) - BOTTOM_HEIGHT;
        let height = size.height.min(space_above.max(space_below).min(size.height));
        let above = match self.hover_settings(editor).above {
            true => height <= space_above.min(size.height),
            false => height > space_below.min(size.height),
        };
        let top = if above { anchor_top - size.height } else { anchor_top + LINE_HEIGHT };
        // contentHoverWidget.ts `_updateMaxDimensions` and `_findMaximumRenderingHeight`.
        let last_size = self.content_hover.last_size;
        let max_width = (editor_bounds.size.width * 0.66).max(750.).max(last_size.0);
        let space = if above { space_above } else { space_below };
        let max_height = (editor_bounds.size.height / 4.).max(250.).max(last_size.1).min(space);
        let limits = ResizeLimits {
            min: (self.content_hover.natural_width.get().map_or(MIN_WIDTH, |width| (width + 2.).min(MIN_WIDTH)), LINE_HEIGHT + 8.),
            max: (max_width, max_height + 2.),
            page_width: window_size.width,
            space,
            capped: self.content_hover.natural_width.get().is_some_and(|width| width + 2. >= max_width - 0.5),
        };
        let high_contrast = self.theme.kind.is_high_contrast();
        let focused = self.content_hover_focus.is_focused(window);
        let widget_bounds = self.content_hover.widget_bounds.clone();
        let natural_width = self.content_hover.natural_width.clone();
        let set_width = natural_width.get();
        let measure = canvas(
            move |bounds, window, cx| {
                let bounds: Bounds<f32> = bounds.map(f32::from);
                if natural_width.get().is_none() {
                    natural_width.set(Some(bounds.size.width));
                    super::part_view::redraw_after_frame(window, cx);
                }
                if widget_bounds.get().map(|old| old.size) != Some(bounds.size) {
                    super::part_view::redraw_after_frame(window, cx);
                }
                widget_bounds.set(Some(bounds));
            },
            |_, _, _, _| (),
        )
        .absolute()
        .inset_0();
        let widget = div()
            .id("content-hover")
            .debug_selector(|| "content-hover".into())
            .track_focus(&self.content_hover_focus)
            .absolute()
            .left(px(left))
            .top(px(top))
            .map(|widget| match user_size {
                // `_setAdjustedHoverWidgetDimensions`: the dragged size without max dimensions.
                Some((width, _)) => widget.w(px(width)),
                // `handleContentsChanged` sets the contents to their rounded `offsetWidth` + 2, inside the 1px border.
                None => widget.max_w(px(max_width)).when_some(set_width, |widget, width| widget.w(px(width.round() + 4.))),
            })
            .border_1()
            .border_color(self.color("editorHoverWidget.border"))
            .rounded(px(RADIUS))
            .text_color(self.foreground_or("editorHoverWidget.foreground"))
            .font_family(UI_FONT)
            .text_size(px(EDITOR_FONT_SIZE))
            .line_height(px(LINE_HEIGHT))
            .cursor_default()
            .occlude()
            .when(measured.is_none(), |widget| widget.invisible())
            .when(high_contrast, |widget| widget.bg(self.color("editorHoverWidget.background")))
            .when(!high_contrast, |widget| {
                // --vscode-shadow-lg under frostedGlass.css's `.monaco-resizable-hover`.
                widget.child(self.frosted_glass("editorHoverWidget.background", RADIUS)).shadow(vec![BoxShadow {
                    color: rgba(0x00000024).into(),
                    offset: point(px(0.), px(0.)),
                    blur_radius: px(12.),
                    spread_radius: px(0.),
                    inset: false,
                }])
            })
            .on_mouse_move(cx.listener(|workbench, event: &MouseMoveEvent, window, cx| {
                workbench.content_hover_mouse_moved(MouseTarget::Widget, event.position, event.modifiers, event.pressed_button.is_some(), window, cx);
            }))
            .on_any_mouse_down(cx.listener(|workbench, _: &MouseDownEvent, window, cx| {
                cx.stop_propagation();
                // A press in a part focused that part first.
                if !workbench.content_hover_focused(window) {
                    window.focus(&workbench.content_hover_focus, cx);
                }
            }))
            // contentHoverWidgetWrapper.ts `_onMouseLeave`: leaving the widget for outside the editor hides it.
            .on_hover(cx.listener(|workbench, hovered: &bool, window, cx| {
                let mouse = window.mouse_position().map(f32::from);
                if !*hovered && !workbench.text_area_bounds.get().contains(&mouse) {
                    workbench.hide_content_hover(cx);
                }
            }))
            .child(measure)
            .child(self.content_hover_rows(shown, editor, user_size.map_or(max_width, |(width, _)| width), max_height, user_size.map(|(_, height)| height - 2.), window, cx))
            // workbench.css `[tabindex="0"]:focus`: a 1px focusBorder outline inside the focused widget.
            .when(focused, |widget| widget.child(div().absolute().inset_0().rounded(px(RADIUS - 1.)).border_1().border_color(self.color("focusBorder"))))
            .when_some(user_size.map(|(width, height)| Size { width, height }).or(measured), |widget, drawn| widget.children(self.content_hover_sashes(drawn, above, limits, cx)));
        let widget = widget.with_animation(("content-hover-fade-in", self.content_hover.shows), Animation::new(Duration::from_millis(100)), |widget, delta| widget.opacity(delta));
        Some(deferred(widget).with_priority(1).into_any_element())
    }

    /// The participants' rows in `hoverOrdinal` order, each participant's parts in its own order, then the status bar.
    fn content_hover_rows(&self, shown: &Shown, editor: &OpenEditor, max_width: f32, max_height: f32, height: Option<f32>, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
        let mut parts: Vec<&Part> = shown.parts.iter().collect();
        parts.sort_by_key(|part| (part.participant, part.ordinal));
        let focused_part = self.focused_hover_part_index(window);
        let focused_stop = self.focused_hover_stop(window);
        let stop_in = |index: usize| focused_stop.filter(|(part, _)| *part == index).map(|(_, stop)| stop);
        let mut rows = Vec::new();
        for (index, part) in parts.iter().enumerate() {
            let stop = stop_in(index);
            let (row, copy_text) = match &part.content {
                PartContent::Marker(marker) => (self.marker_hover_row(marker, index, stop, cx), marker_accessible_content(marker)),
                PartContent::Markdown(contents) => {
                    let link = match stop {
                        Some(PartStop::Link(link)) => Some(link),
                        _ => None,
                    };
                    let (row, text) = self.markdown_hover_row(contents, index, link, max_width, &editor.document().language_id, cx);
                    (self.with_verbosity_actions(row, part.source.as_ref(), index, stop, cx), text)
                }
                PartContent::ColorPicker => {
                    rows.push(div().child(self.color_picker_row(cx)));
                    continue;
                }
                PartContent::InlineCompletions => {
                    rows.push(self.inline_completions_hover_toolbar(window, cx));
                    continue;
                }
            };
            rows.push(self.hover_row_with_copy(row, index, copy_text, focused_part == Some(index), stop == Some(PartStop::Copy), cx));
        }
        let first_marker = parts.iter().find_map(|part| match &part.content {
            PartContent::Marker(marker) => Some(marker.clone()),
            PartContent::Markdown(_) | PartContent::ColorPicker | PartContent::InlineCompletions => None,
        });
        if let Some(marker) = first_marker {
            rows.push(self.marker_hover_status_bar(marker, stop_in(rows.len()), window, cx));
        }
        let mut separator = self.color("editorHoverWidget.border");
        separator.a *= 0.5;
        let content_height = self.content_hover.content_height.clone();
        let measure = canvas(
            move |bounds, window, cx| {
                let height = f32::from(bounds.size.height);
                if content_height.get() != height {
                    content_height.set(height);
                    super::part_view::redraw_after_frame(window, cx);
                }
            },
            |_, _, _, _| (),
        )
        .absolute()
        .inset_0();
        let mut column = div().relative().flex().flex_col().child(measure);
        for (index, row) in rows.into_iter().enumerate() {
            let focused = focused_part == Some(index) && stop_in(index).is_none();
            let row = row.relative().track_focus(&self.content_hover.part_focus[index]).when(focused, |row| row.child(self.focus_outline()));
            // hoverContribution.ts: `.hover-row:not(:first-child):not(:empty)` has a top border at half alpha.
            column = column.child(row.when(index > 0, |row| row.border_t_1().border_color(separator)));
        }
        let contents = self.scrollable("content-hover-contents", Some(&self.content_hover.scroll), div().id("content-hover-contents").child(column), cx);
        match height {
            Some(height) => contents.h(px(height)),
            None => contents.max_h(px(max_height)),
        }
    }

    /// resizableContentWidget.ts `_findPositionPreference`: the north and east sashes above the line, east and south
    /// below it, with the corner where they meet; `size` is the widget's border box.
    fn content_hover_sashes(&self, size: Size<f32>, above: bool, limits: ResizeLimits, cx: &mut Context<Self>) -> Vec<AnyElement> {
        let half = SASH_SIZE / 2.;
        // The widget's absolute children sit in its padding box, inside the 1px border.
        let (right, bottom) = (size.width - 1., size.height - 1.);
        let vertical = if above { (true, -1. - half) } else { (false, bottom - half) };
        // [north, east, south] and [left, top, width, height].
        let corner = if above { CursorStyle::ResizeUpRightDownLeft } else { CursorStyle::ResizeUpLeftDownRight };
        let sashes = [
            ([false, true, false], [right - half, -1., SASH_SIZE, size.height], CursorStyle::ResizeLeftRight),
            ([vertical.0, false, !vertical.0], [-1., vertical.1, size.width, SASH_SIZE], CursorStyle::ResizeUpDown),
            ([vertical.0, true, !vertical.0], [right - half, vertical.1, SASH_SIZE, SASH_SIZE], corner),
        ];
        let dragging = self.content_hover.resize.as_ref().map(|resize| [resize.north, resize.east, resize.south]);
        let workbench = cx.entity();
        let mut elements = Vec::new();
        for (index, (edges, [left, top, width, height], cursor)) in sashes.into_iter().enumerate() {
            let [north, east, south] = edges;
            let sash = div()
                .id(("content-hover-sash", index))
                .debug_selector(move || format!("content-hover-sash-{}{}{}", if north { "n" } else { "" }, if east { "e" } else { "" }, if south { "s" } else { "" }))
                .absolute()
                .left(px(left))
                .top(px(top))
                .w(px(width))
                .h(px(height))
                .cursor(cursor)
                .occlude()
                .children(self.sash_highlight(("content-hover-sash", index), (dragging == Some(edges) || self.content_hover.hovered_sash == Some(index)) && index < 2, div().absolute().inset_0()))
                .on_hover(self.content_hover_sash_hover_listener(index, cx))
                .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, _, cx| {
                    cx.stop_propagation();
                    let pointer = event.position.map(f32::from);
                    workbench.content_hover.resize = Some(HoverResize { north, east, south, pointer, start: (size.width, size.height), limits });
                    cx.notify();
                }))
                .when(dragging.is_some() && index == 0, |sash| {
                    let workbench = workbench.clone();
                    sash.child(
                        canvas(
                            |_, _, _| (),
                            move |_, _, window, _| {
                                let moved = workbench.clone();
                                window.on_mouse_event(move |event: &MouseMoveEvent, _, _, cx| {
                                    moved.update(cx, |workbench, cx| workbench.drag_content_hover_sash(event.position.map(f32::from), false, cx));
                                });
                                let released = workbench.clone();
                                window.on_mouse_event(move |event: &MouseUpEvent, _, _, cx| {
                                    released.update(cx, |workbench, cx| workbench.drag_content_hover_sash(event.position.map(f32::from), true, cx));
                                });
                            },
                        )
                        .size_0(),
                    )
                });
            elements.push(sash.into_any_element());
        }
        elements
    }

    /// sash.ts `onMouseEnter`: the `hover` class, and its `sash.hoverBorder`, after `workbench.sash.hoverDelay`.
    fn content_hover_sash_hover_listener(&self, index: usize, cx: &mut Context<Self>) -> impl Fn(&bool, &mut Window, &mut gpui::App) + 'static {
        cx.listener(move |workbench, hovered: &bool, window, cx| {
            if !*hovered {
                if workbench.content_hover.hovered_sash == Some(index) {
                    workbench.content_hover.hovered_sash = None;
                }
                workbench.content_hover.sash_hover = None;
                cx.notify();
                return;
            }
            let delay = workbench.sash_hover_delay();
            workbench.content_hover.sash_hover = Some(cx.spawn_in(window, async move |workbench, cx| {
                cx.background_executor().timer(delay).await;
                let _ = workbench.update(cx, |workbench, cx| {
                    workbench.content_hover.hovered_sash = Some(index);
                    cx.notify();
                });
            }));
        })
    }

    /// ResizableHTMLElement's `onDidChange`: the size from the drag's start, clamped by `layout` to the limits the
    /// last `_resize` left (`_updateResizableNodeMaxDimensions`); every step is `_lastDimensions`.
    fn drag_content_hover_sash(&mut self, pointer: Point<f32>, done: bool, cx: &mut Context<Self>) {
        let content_height = self.content_hover.content_height.get();
        let natural_width = self.content_hover.natural_width.get().unwrap_or(0.);
        let Some(resize) = self.content_hover.resize.as_mut() else { return };
        let (mut width, mut height) = resize.start;
        if resize.east {
            width += pointer.x - resize.pointer.x;
        }
        if resize.north {
            height -= pointer.y - resize.pointer.y;
        }
        if resize.south {
            height += pointer.y - resize.pointer.y;
        }
        let ResizeLimits { min, max, page_width, space, capped } = resize.limits;
        let size = (width.min(max.0).max(min.0), height.min(max.1).max(min.1));
        // `_findMaximumRenderingWidth`: text that wraps may widen to the page, else the widget keeps its width.
        let overflowing = capped || size.0 < natural_width + 2.;
        resize.limits.max = (if overflowing { page_width - 14. } else { size.0 }, space.min(content_height + 2.));
        if done {
            self.content_hover.resize = None;
        }
        self.content_hover.size = Some(size);
        self.content_hover.last_size = size;
        cx.notify();
    }

    /// markerHoverParticipant.ts `_renderMarkerHover`: the severity icon, the message in the editor font, the source
    /// and code at 60% opacity, and the related information.
    fn marker_hover_row(&self, marker: &Marker, index: usize, stop: Option<PartStop>, cx: &mut Context<Self>) -> Div {
        let (icon, color) = match marker.severity {
            ERROR => ("error", self.color("problemsErrorIcon.foreground")),
            WARNING => ("warning", self.color("problemsWarningIcon.foreground")),
            INFO => ("info", self.color("problemsInfoIcon.foreground")),
            _ => ("lightbulb", self.foreground_or("editorHoverWidget.foreground")),
        };
        let mut message = div().min_w_0().flex().flex_col().child(div().whitespace_normal().child(marker.message.clone()));
        let details = match &marker.code {
            Value::Object(code) => {
                let value = code.get("value").and_then(Value::as_str).unwrap_or_default().to_string();
                let target = code.get("target").cloned().unwrap_or(Value::Null);
                let link = div()
                    .id(("marker-hover-code", index))
                    .debug_selector(move || format!("marker-hover-code-{index}"))
                    .relative()
                    .cursor_pointer()
                    .when(stop == Some(PartStop::MarkerCode), |link| link.child(self.focus_outline()))
                    .flex()
                    .child("(")
                    .child(div().underline().child(value))
                    .child(")")
                    .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                        cx.stop_propagation();
                        workbench.open_marker_code(&target, window, cx);
                    }));
                Some(div().flex().children(marker.source.clone()).child(link))
            }
            Value::String(code) => Some(div().child(match &marker.source {
                Some(source) => format!("{source}({code})"),
                None => format!("({code})"),
            })),
            _ => marker.source.clone().map(|source| div().child(source)),
        };
        if let Some(details) = details {
            message = message.child(details.opacity(0.6).pl(px(6.)));
        }
        let link = self.color("textLink.foreground");
        for (related_index, related) in marker.related_information.as_array().into_iter().flatten().enumerate() {
            let resource = super::host_requests::uri_parts(&related["resource"]).ok().map(|(scheme, path)| crate::editor::uri_string(scheme, &path));
            let basename = resource.as_deref().and_then(|uri| uri.rsplit('/').next()).unwrap_or_default().to_string();
            let label = format!("{basename}({}, {}): ", related["startLineNumber"], related["startColumn"]);
            let related_message = related["message"].as_str().unwrap_or_default().to_string();
            let item = related.clone();
            message = message.child(
                div()
                    .mt(px(8.))
                    .child(div().id(("marker-hover-related", index * 1000 + related_index)).relative().cursor_pointer().text_color(link).child(label).when(stop == Some(PartStop::MarkerRelated(related_index)), |label| label.child(self.focus_outline())).on_click(cx.listener(
                        move |workbench, _: &ClickEvent, window, cx| {
                            cx.stop_propagation();
                            workbench.hide_content_hover(cx);
                            workbench.open_marker_related(&item, window, cx);
                        },
                    )))
                    .child(related_message),
            );
        }
        div()
            .flex()
            .gap(px(8.))
            .px(px(8.))
            .py(px(4.))
            .font_family(EDITOR_FONT)
            .child(div().flex_none().h(px(LINE_HEIGHT)).flex().items_center().child(self.icon(icon, 16., 16., color)))
            .child(message)
    }

    /// markdownHoverParticipant.ts `renderMarkdown`: each non-empty markdown string in its own `.hover-contents`.
    fn markdown_hover_row(&self, contents: &[Value], index: usize, focused_link: Option<usize>, max_width: f32, model_language: &str, cx: &mut Context<Self>) -> (Div, String) {
        let style = MarkdownStyle { font_size: EDITOR_FONT_SIZE, line_height: LINE_HEIGHT, foreground: self.foreground_or("editorHoverWidget.foreground"), action_handler: None, code_foreground: None, code_background: Some(self.color("textCodeBlock.background")), selectable: false };
        let mut row = div().min_w_0().flex().flex_col();
        let mut texts = Vec::new();
        let mut links_before = 0;
        for (content_index, content) in contents.iter().enumerate() {
            if crate::markdown::is_empty(content) {
                continue;
            }
            let mut blocks = parse(&MarkdownString::from_value(content));
            let links = super::hover::link_spans(&mut blocks);
            let count = links.len();
            if let Some(spans) = focused_link.and_then(|link| link.checked_sub(links_before)).and_then(|link| links.into_iter().nth(link)) {
                spans.into_iter().for_each(|span| span.focused = true);
            }
            links_before += count;
            texts.push(plain_text(&blocks));
            let blocks = self.markdown_blocks(&format!("content-hover-{index}-{content_index}"), &blocks, style, model_language, cx);
            row = row.child(div().px(px(8.)).py(px(4.)).max_w(px(max_width)).child(blocks));
        }
        (row, texts.join("\n"))
    }

    /// markdownHoverParticipant.ts `_renderHoverPart`: a provider's hover that can change its verbosity gets the
    /// `.verbosity-actions` column, its + and - at the bottom of the row's visible part (`handleScroll`).
    fn with_verbosity_actions(&self, row: Div, source: Option<&ProviderHover>, index: usize, stop: Option<PartStop>, cx: &mut Context<Self>) -> Div {
        let Some(source) = source.filter(|source| source.supports(1) || source.supports(-1)) else { return row };
        // `.verbosity-actions-inner`, the target its actions' hovers place against.
        let column_bounds = Rc::new(Cell::new(None));
        let record_column = column_bounds.clone();
        let mut icons = div().absolute().left_0().px(px(5.)).flex().flex_col().child(canvas(move |bounds, _, _| record_column.set(Some(bounds)), |_, _, _, _| ()).absolute().inset_0());
        for (delta, icon, title, command) in [
            (1, "hover-increase-verbosity", "Increase Hover Verbosity", "editor.action.increaseHoverVerbosityLevel"),
            (-1, "hover-decrease-verbosity", "Decrease Hover Verbosity", "editor.action.decreaseHoverVerbosityLevel"),
        ] {
            let enabled = source.supports(delta);
            let color = if enabled { self.color("textLink.foreground") } else { self.foreground_or("editorHoverWidget.foreground") };
            let action = div()
                .id(SharedString::from(format!("content-hover-verbosity-{index}-{delta}")))
                .debug_selector(move || format!("content-hover-verbosity-{index}-{delta}"))
                .relative()
                .cursor_pointer()
                .when(!enabled, |action| action.opacity(0.6))
                .child(self.icon(icon, 11., 11., color))
                .when(stop == Some(PartStop::Verbosity(delta)), |action| action.child(self.focus_outline()))
                .child(self.action_hover_placed_at(title, command, HoverOptions::left(), column_bounds.clone()))
                .when(enabled, |action| {
                    action.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                        cx.stop_propagation();
                        workbench.update_hover_verbosity_level(delta, Some(index), true, window, cx);
                    }))
                });
            icons = icons.child(action);
        }
        let overflow = self.content_hover.verbosity_overflow.clone();
        let widget_bounds = self.content_hover.widget_bounds.clone();
        let bottom = overflow.borrow().get(&index).copied().unwrap_or(0.);
        let measure = canvas(
            move |bounds, window, cx| {
                let Some(visible) = widget_bounds.get() else { return };
                let (top, bottom, visible_bottom) = (f32::from(bounds.top()), f32::from(bounds.bottom()), visible.bottom());
                let below_view = if top >= visible_bottom { 0. } else { (bottom - visible_bottom).max(0.) };
                if overflow.borrow_mut().insert(index, below_view) != Some(below_view) {
                    super::part_view::redraw_after_frame(window, cx);
                }
            },
            |_, _, _, _| (),
        )
        .absolute()
        .inset_0();
        let actions = div().relative().flex_none().w(px(23.)).border_r_1().border_color(self.color("editorHoverWidget.border")).overflow_hidden().child(icons.bottom(px(bottom)));
        div().relative().flex().child(measure).child(actions).child(row)
    }

    /// hoverCopyButton.ts on every part: a copy button in the top right corner while the row is hovered.
    fn hover_row_with_copy(&self, row: Div, index: usize, text: String, focused: bool, button_focused: bool, cx: &mut Context<Self>) -> Div {
        let group = format!("content-hover-row-{index}");
        let toolbar_hover = self.color("toolbar.hoverBackground");
        let button = div()
            .id(("content-hover-copy", index))
            .debug_selector(move || format!("content-hover-copy-{index}"))
            .absolute()
            .top(px(4.))
            .right(px(4.))
            .px(px(4.))
            .py(px(2.))
            .rounded(px(3.))
            .opacity(0.)
            // hover.css: `.hover-row-with-copy:hover` and `:focus-within` show the button.
            .when(focused, |button| button.opacity(1.))
            .group_hover(group.clone(), |style| style.opacity(1.))
            .hover(move |style| style.bg(toolbar_hover).cursor_pointer())
            .child(self.icon("copy", 16., 16., self.foreground_or("foreground")))
            // hover.css `.hover-copy-button:focus`.
            .when(button_focused, |button| button.child(self.focus_outline().rounded(px(3.))))
            .on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
                cx.stop_propagation();
                workbench.copy_hover_part(text.clone(), cx);
            }));
        div().group(group).relative().flex().pr(px(20.)).child(row).child(button)
    }

    /// markerHoverParticipant.ts `_renderMarkerStatusbar` for the most severe marker: View Problem, then the quick fix
    /// placeholder of a writable editor.
    fn marker_hover_status_bar(&self, marker: std::sync::Arc<Marker>, stop: Option<PartStop>, window: &Window, cx: &mut Context<Self>) -> Div {
        let marker_for_fixes = marker.clone();
        let mut actions = div().w_full().flex().px(px(8.)).bg(self.color("editorHoverWidget.statusBarBackground"));
        if matches!(marker.severity, ERROR | WARNING | INFO) {
            let label = self.hover_action_label("View Problem", "editor.action.marker.next", window);
            let action = div()
                .id("content-hover-view-problem")
                .relative()
                .mr(px(16.))
                .cursor_pointer()
                .whitespace_nowrap()
                .overflow_hidden()
                .text_ellipsis()
                .text_color(self.color("textLink.foreground"))
                .child(label)
                .when(stop == Some(PartStop::ViewProblem), |action| action.child(self.focus_outline()))
                .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                    cx.stop_propagation();
                    workbench.view_problem_from_hover(&marker, window, cx);
                }));
            actions = actions.child(action);
        }
        if self.active_editor_readonly().is_none() {
            actions = match self.marker_quick_fix_status(&marker_for_fixes) {
                super::code_actions::QuickFixStatus::Text(text) => actions.child(div().child(text)),
                super::code_actions::QuickFixStatus::QuickFix => {
                    let label = self.hover_action_label("Quick Fix...", "editor.action.quickFix", window);
                    let bounds = self.code_actions.marker_fixes.label_bounds.clone();
                    let measure = gpui::canvas(move |element_bounds, _, _| bounds.set(element_bounds.map(f32::from)), |_, _, _, _| ()).absolute().inset_0();
                    let action = div()
                        .id("content-hover-quick-fix")
                        .relative()
                        .mr(px(16.))
                        .cursor_pointer()
                        .whitespace_nowrap()
                        .text_color(self.color("textLink.foreground"))
                        .child(measure)
                        .child(label)
                        .when(stop == Some(PartStop::QuickFix), |action| action.child(self.focus_outline()))
                        .on_click(cx.listener(|workbench, _: &ClickEvent, _, cx| {
                            cx.stop_propagation();
                            workbench.show_marker_quick_fixes(cx);
                        }));
                    actions.child(action)
                }
            };
        }
        div().flex().font_family(UI_FONT).text_size(px(12.)).line_height(px(22.)).child(actions)
    }

    /// markerHoverParticipant.ts View Problem: the hover goes and the marker navigation widget shows the marker.
    pub(super) fn view_problem_from_hover(&mut self, marker: &Marker, window: &mut Window, cx: &mut Context<Self>) {
        self.hide_content_hover(cx);
        self.show_marker_navigation_at(marker, window, cx);
        window.focus(&self.editor_focus, cx);
    }

    /// workbench.css `[tabindex="0"]:focus`: a 1px focusBorder outline inside the focused element.
    pub(super) fn focus_outline(&self) -> Div {
        div().absolute().inset_0().border_1().border_color(self.color("focusBorder"))
    }

    /// contentHoverRendered.ts `getAccessibleHoverContentAtIndex` for the status bar of `marker_hover_status_bar`.
    pub(super) fn marker_status_bar_accessible_content(&self, marker: &Marker, window: &Window) -> String {
        let mut actions = Vec::new();
        if matches!(marker.severity, ERROR | WARNING | INFO) {
            actions.push(("View Problem", "editor.action.marker.next"));
        }
        if self.active_editor_readonly().is_none() && matches!(self.marker_quick_fix_status(marker), super::code_actions::QuickFixStatus::QuickFix) {
            actions.push(("Quick Fix...", "editor.action.quickFix"));
        }
        let context = self.key_context(window);
        let mut description = vec!["This is a hover status bar.".to_owned()];
        for (label, command) in actions {
            description.push(match self.keybindings.resolver.lookup_primary_keybinding(command, &context) {
                Some(item) => format!("It has an action with label {label} and keybinding {}.", crate::keybindings::label(&item.keybinding)),
                None => format!("It has an action with label {label}."),
            });
        }
        description.join("\n")
    }

    /// statusBar `addAction`: the label with the command's keybinding.
    pub(super) fn hover_action_label(&self, label: &str, command: &str, window: &Window) -> String {
        let context = self.key_context(window);
        match self.keybindings.resolver.lookup_primary_keybinding(command, &context) {
            Some(item) => format!("{label} ({})", crate::keybindings::label(&item.keybinding)),
            None => label.to_owned(),
        }
    }
}

/// A sash drag: the edges it moves, ResizableHTMLElement's `currentSize` at the start pointer, and the limits.
pub(super) struct HoverResize {
    north: bool,
    east: bool,
    south: bool,
    pointer: Point<f32>,
    start: (f32, f32),
    limits: ResizeLimits,
}

/// `minSize` and `maxSize` of the border box, the page width and the space on the widget's side of the line that
/// `_updateResizableNodeMaxDimensions` reads, and whether the contents wrap at the max width.
#[derive(Clone, Copy)]
struct ResizeLimits {
    min: (f32, f32),
    max: (f32, f32),
    page_width: f32,
    space: f32,
    capped: bool,
}

/// `Range.plusRange` over the parts.
fn highlight_range(parts: &[Part]) -> Option<(Position, Position)> {
    let mut range: Option<(Position, Position)> = None;
    for part in parts {
        range = Some(match range {
            None => (part.start, part.end),
            Some((start, end)) => (start.min(part.start), end.max(part.end)),
        });
    }
    range
}

/// markerHoverParticipant.ts `getAccessibleContent`.
pub(super) fn marker_accessible_content(marker: &Marker) -> String {
    let severity = match marker.severity {
        ERROR => "Error",
        WARNING => "Warning",
        INFO => "Info",
        HINT => "Hint",
        _ => "",
    };
    let mut lines = vec![format!("{severity}: {}", marker.message)];
    for related in marker.related_information.as_array().into_iter().flatten() {
        let resource = super::host_requests::uri_parts(&related["resource"]).ok().map(|(scheme, path)| crate::editor::uri_string(scheme, &path));
        let basename = resource.as_deref().and_then(|uri| uri.rsplit('/').next()).unwrap_or_default().to_string();
        lines.push(format!("{basename}({}, {}): {}", related["startLineNumber"], related["startColumn"], related["message"].as_str().unwrap_or_default()));
    }
    lines.join("\n")
}