Visual Studio Code, rebuilt in Rust
Rust
//! The workbench hover: hoverService.ts `setupManagedHover` and `setupDelayedHover` showing a hoverWidget.ts
//! `HoverWidget` in a context view, placed by its `layout` and drawn as hover.css, hoverWidget.css and the
//! Modern UI frosted glass draw it. Targets add `hover_target` as a child; the editor hover reuses the widget.
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use std::time::{Duration, Instant};
use gpui::{
Animation, AnimationExt, AnyElement, AnyView, App, Bounds, BoxShadow, Context, DispatchPhase, ElementId, EntityId, FocusHandle, HitboxBehavior, MouseDownEvent, MouseMoveEvent, PathBuilder, Pixels, Point, Size, Task,
Rgba, TextRun, Window, canvas, div, point, prelude::*, px, rgba,
};
use serde_json::Value;
use super::Workbench;
use super::context_menu::{LayoutAnchorPosition, layout2d};
use super::markdown_view::MarkdownStyle;
use crate::markdown::{Block, MarkdownString, Span, parse};
use crate::notifications::{Node, parse_linked_text};
#[cfg(test)]
mod tests;
/// hoverWidget.ts `Constants`.
const POINTER_SIZE: f32 = 3.;
const HOVER_BORDER_WIDTH: f32 = 2.;
const WINDOW_EDGE_MARGIN: f32 = 2.;
/// `.compact`: 12px text, 19px lines, 2px 8px padding (hover.css).
pub(super) const FONT_SIZE: f32 = 12.;
pub(super) const LINE_HEIGHT: f32 = 19.;
const PADDING_X: f32 = 8.;
const PADDING_Y: f32 = 2.;
const MAX_WIDTH: f32 = 700.;
const TEXT_MAX_WIDTH: f32 = 500.;
const STATUS_BAR_HEIGHT: f32 = 22.;
const POLICY_ACTION: &str = "View policy settings";
/// CompositeMouseTracker's `_eventDebounceDelay` and WorkbenchHoverDelegate's `timeLimit`.
const MOUSE_OUT_DELAY: Duration = Duration::from_millis(200);
/// `.with-pointer` has 3px corners; roundedCorners.css gives other hovers cornerRadius.large.
const POINTER_RADIUS: f32 = 3.;
const RADIUS: f32 = 8.;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HoverPosition {
Left,
Right,
Below,
Above,
}
#[derive(Clone, Debug, PartialEq)]
pub enum HoverContent {
Text(String),
/// An action's tooltip: its title and the keybinding of its command, looked up when the hover shows.
Action { title: &'static str, command: &'static str },
/// editorTabsControl.ts `getHoverTitle` of a preview editor: the title, then "(_preview_ $(gear))".
Preview(String),
/// An `IMarkdownString` tooltip: `value`, with `isTrusted` and `supportThemeIcons`.
Markdown(Value),
/// languageStatus.ts `_combinedEntryTooltip`: one row per status of the current view model.
LanguageStatus,
/// updateTooltip.ts, pointing at the title bar's update entry.
Update,
/// settingsEditorSettingIndicators.ts' policy indicator: the text, then the "View policy settings" action in the
/// hover's status bar.
Policy(String),
/// treeView.ts `getHover` of an extension's tree item whose tooltip the host resolves (`$resolve`) when it shows.
TreeItem { view: &'static str, handle: String },
}
/// What the target's hover delegate decides.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HoverOptions {
position: HoverPosition,
/// 'mouse' placement: 10px right of the pointer, without a pointer caret.
follows_mouse: bool,
/// `instantHover`: within 200ms of hiding a hover the next one shows without delay.
instant: bool,
/// `setupDelayedHover`'s `groupId`: moving to a target of the showing hover's group shows at once.
group: Option<&'static str>,
max_height_ratio: f32,
/// `persistence.sticky`: the hover stays until a click outside it or a key.
sticky: bool,
/// `AnchorAlignment.RIGHT`: above or below, the hover's right edge meets the target's.
anchor_right: bool,
/// `persistence.hideOnKeyDown`: a key no keybinding takes hides the hover.
hide_on_key_down: bool,
/// More horizontal padding inside the border, in px on each side.
extra_padding_x: f32,
}
impl HoverOptions {
/// getDefaultHoverDelegate('mouse'): tabs and Explorer rows.
pub fn mouse() -> Self {
HoverOptions { position: HoverPosition::Below, follows_mouse: true, instant: false, group: None, max_height_ratio: 0.5, sticky: false, anchor_right: false, hide_on_key_down: true, extra_padding_x: 0. }
}
/// quickInput.ts `QuickInputHoverDelegate`: WorkbenchHoverDelegate('mouse') whose hover a key down leaves shown.
pub fn quick_input() -> Self {
HoverOptions { hide_on_key_down: false, ..Self::mouse() }
}
/// quickInputList.ts `showHover`: an item's tooltip right of its row, with a pointer.
pub fn quick_input_item() -> Self {
// Its host sits in the list, so quickInput.css `.quick-input-list .monaco-scrollable-element { padding: 0 6px }` pads it too.
HoverOptions { position: HoverPosition::Right, follows_mouse: false, extra_padding_x: 6., ..Self::quick_input() }
}
/// createInstantHoverDelegate: the title bar's actions and command center.
pub fn instant() -> Self {
HoverOptions { position: HoverPosition::Above, follows_mouse: false, instant: true, group: None, max_height_ratio: 0.5, sticky: false, anchor_right: false, hide_on_key_down: true, extra_padding_x: 0. }
}
/// statusbarPart.ts's WorkbenchHoverDelegate, with `maxHeightRatio: 0.9`.
pub fn status_bar() -> Self {
HoverOptions { max_height_ratio: 0.9, ..Self::instant() }
}
/// getDefaultHoverDelegate('element'): above the target, after the hover delay.
pub fn element() -> Self {
HoverOptions { instant: false, ..Self::instant() }
}
/// markdownHoverParticipant.ts' verbosity actions: WorkbenchHoverDelegate('mouse') overridden to the left of its
/// target.
pub fn left() -> Self {
HoverOptions { position: HoverPosition::Left, ..Self::element() }
}
/// updatableHoverWidget.ts: an action item's managed hover asks for `HoverPosition.BELOW`.
pub fn managed() -> Self {
HoverOptions { position: HoverPosition::Below, ..Self::instant() }
}
/// A pointer on an action item: its managed hover below the element, after the default element delegate's delay.
pub fn action_item() -> Self {
HoverOptions { instant: false, ..Self::managed() }
}
/// `showInstantHover` with `HoverPosition.BELOW` and `showPointer`: the profile icon picker.
pub fn sticky_below() -> Self {
HoverOptions { position: HoverPosition::Below, ..Self::instant() }
}
/// compositeBarActions.ts: `HoverStyle.Pointer` on the side away from the side bar.
pub fn composite_bar(position: HoverPosition) -> Self {
HoverOptions { position, follows_mouse: false, instant: false, group: Some("composite-bar-actions"), max_height_ratio: 0.5, sticky: false, anchor_right: false, hide_on_key_down: true, extra_padding_x: 0. }
}
pub fn sticky(self) -> Self {
HoverOptions { sticky: true, ..self }
}
pub fn anchored_right(self) -> Self {
HoverOptions { anchor_right: true, ..self }
}
}
#[derive(Clone)]
struct HoverTarget {
id: ElementId,
content: HoverContent,
options: HoverOptions,
bounds: Bounds<Pixels>,
/// `target.x` of a mouse placed hover: the last pointer x plus 10; none for a hover shown from the keyboard.
mouse_x: Option<f32>,
}
struct ShownHover {
target: HoverTarget,
text: String,
fade_in: bool,
serial: usize,
/// `IHoverOptions.trapFocus`: Tab stays in the hover.
trap_focus: bool,
/// hoverService.ts `lastFocusedElementBeforeOpen`, recorded for a trapFocus hover.
return_focus: Option<FocusHandle>,
/// The markdown link with the focus, by its order in the hover; none while the container has it.
focused_link: Option<usize>,
/// The markdown contents' size, measured by the first frame, which draws the hover hidden.
measured: Rc<Cell<Option<Size<f32>>>>,
}
#[derive(Default)]
pub struct Hovers {
/// The target under the pointer, its hover pending or shown.
target: Option<HoverTarget>,
/// A click or a key hid the target's hover; it shows again only after the pointer leaves the target.
dismissed: bool,
shown: Option<ShownHover>,
shown_count: usize,
pending: Option<Task<()>>,
hiding: Option<Task<()>>,
/// WorkbenchHoverDelegate's `lastHoverHideTime`.
last_hide: Option<Instant>,
/// `HoverWidget.isLocked`: Alt is held, so the hover stays when the pointer leaves for it.
locked: bool,
/// `HoverWidget.isMouseIn`.
pub(super) mouse_in_hover: bool,
/// hoverService.ts `_lastHoverOptions`.
last: Option<HoverTarget>,
/// The targets the last frame painted and the view each was painted in, for `_showAndFocusHoverForActiveElement`.
painted: Rc<RefCell<HashMap<ElementId, (EntityId, HoverTarget)>>>,
}
impl Hovers {
#[cfg(test)]
pub fn shown_text(&self) -> Option<&str> {
self.shown.as_ref().map(|hover| hover.text.as_str())
}
pub fn is_shown(&self) -> bool {
self.shown.is_some()
}
/// Whether the sticky hover of the target `id` shows.
pub fn sticky_shown(&self, id: &str) -> bool {
self.shown.as_ref().is_some_and(|shown| shown.target.options.sticky && shown.target.id == ElementId::from(id.to_owned()))
}
/// `persistence.sticky`: the shown hover is locked and listens to no key (hoverService.ts `_createHover`).
pub fn is_sticky(&self) -> bool {
self.shown.as_ref().is_some_and(|shown| shown.target.options.sticky)
}
/// The shown hover stays on a key down: sticky, or `hideOnKeyDown: false`.
pub fn stays_on_key_down(&self) -> bool {
self.shown.as_ref().is_some_and(|shown| shown.target.options.sticky || !shown.target.options.hide_on_key_down)
}
/// Called as a view renders: the frame about to paint records the targets of the views `redrawn` takes again; a
/// cached part view that is not drawn again keeps its own.
pub fn forget_painted_targets(&self, redrawn: impl Fn(EntityId) -> bool) {
self.painted.borrow_mut().retain(|_, (painted_in, _)| !redrawn(*painted_in));
}
}
impl Workbench {
/// `setupManagedHover`: an overlay over its parent that shows the hover while the pointer rests on the parent.
pub(super) fn hover_target(&self, id: impl Into<ElementId>, content: HoverContent, options: HoverOptions) -> impl IntoElement {
self.hover_target_placed_at(id, content, options, None)
}
/// `hover_target` whose hover places against the bounds `placed_at` holds, a delegate's `target` override, over
/// its parent's.
fn hover_target_placed_at(&self, id: impl Into<ElementId>, content: HoverContent, options: HoverOptions, placed_at: Option<Rc<Cell<Option<Bounds<Pixels>>>>>) -> impl IntoElement {
let id = id.into();
let painted = self.hovers.painted.clone();
canvas(
|bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
move |bounds, hitbox, window, _| {
let bounds = placed_at.as_ref().and_then(|placed_at| placed_at.get()).unwrap_or(bounds);
let target = HoverTarget { id: id.clone(), content: content.clone(), options, bounds, mouse_x: None };
painted.borrow_mut().insert(id.clone(), (window.current_view(), target.clone()));
let pressed = hitbox.clone();
// Capture phase, as the reference's listeners: a target's own handlers may stop the event.
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if phase != DispatchPhase::Capture {
return;
}
let Some(workbench) = super::auxiliary_windows::window_workbench(window, cx) else { return };
// Every drag of the reference is an HTML5 drag, which fires no mouse events.
let hovered = hitbox.is_hovered(window) && !cx.has_active_drag();
if !hovered && !workbench.read(cx).hovers.is_target(&target.id) {
return;
}
workbench.update(cx, |workbench, cx| workbench.hover_mouse_moved(&target, hovered, event.position, window, cx));
});
window.on_mouse_event(move |_: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Capture || !pressed.is_hovered(window) {
return;
}
let Some(workbench) = super::auxiliary_windows::window_workbench(window, cx) else { return };
workbench.update(cx, |workbench, cx| workbench.dismiss_hover(cx));
});
},
)
.absolute()
.inset_0()
}
/// An action view item's hover: its title, and its keybinding when it has one.
pub(super) fn action_hover(&self, title: &'static str, command: &'static str, options: HoverOptions) -> impl IntoElement {
self.hover_target(command, HoverContent::Action { title, command }, options)
}
/// `action_hover` placed against the bounds `placed_at` holds.
pub(super) fn action_hover_placed_at(&self, title: &'static str, command: &'static str, options: HoverOptions, placed_at: Rc<Cell<Option<Bounds<Pixels>>>>) -> impl IntoElement {
self.hover_target_placed_at(command, HoverContent::Action { title, command }, options, Some(placed_at))
}
fn hover_mouse_moved(&mut self, target: &HoverTarget, hovered: bool, position: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
// setupManagedHover's `x: e.x + 10`; MouseEvent.x is whole pixels.
let mouse_x = f32::from(position.x).floor() + 10.;
if !hovered {
self.leave_hover_target(cx);
return;
}
if let Some(current) = self.hovers.target.as_mut().filter(|current| current.id == target.id) {
current.mouse_x = Some(mouse_x);
return;
}
// Entering a target leaves the previous one first, whichever target's handler runs first.
self.leave_hover_target(cx);
let target = HoverTarget { mouse_x: Some(mouse_x), ..target.clone() };
// Back on the target within the mouse tracker's delay: the hover stays.
if self.hovers.shown.as_ref().is_some_and(|shown| shown.target.id == target.id) {
self.hovers.hiding = None;
self.hovers.target = Some(target);
return;
}
let instantly = target.options.instant && self.hovers.last_hide.is_some_and(|hidden| cx.background_executor().now() - hidden < MOUSE_OUT_DELAY);
let same_group = target.options.group.is_some() && self.hovers.shown.as_ref().is_some_and(|shown| shown.target.options.group == target.options.group);
self.hovers.target = Some(target);
if instantly || same_group {
self.show_hover(false, window, cx);
return;
}
let delay = self.hover_delay();
self.hovers.pending = Some(cx.spawn_in(window, async move |workbench, cx| {
cx.background_executor().timer(delay).await;
let _ = workbench.update_in(cx, |workbench, window, cx| workbench.show_hover(true, window, cx));
}));
}
fn hover_delay(&self) -> Duration {
Duration::from_millis(self.setting("workbench.hover.delay").as_u64().unwrap_or(1500))
}
/// setupManagedHover's `onFocus`: an action item the keyboard focused shows its hover after the delay while it
/// keeps the focus. A composite bar item's `setupDelayedHover` (its `group`) shows none on focus.
pub(super) fn hover_focused_action_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(focused) = window.focused(cx) else { return };
let Some(id) = self.focused_action_bar_item(window).and_then(|bounds| self.painted_hover_within(bounds)) else { return };
let Some((_, target)) = self.hovers.painted.borrow().get(&id).cloned() else { return };
if target.options.group.is_some() {
return;
}
self.hovers.target = Some(target);
self.hovers.dismissed = false;
let delay = self.hover_delay();
self.hovers.pending = Some(cx.spawn_in(window, async move |workbench, cx| {
cx.background_executor().timer(delay).await;
let _ = workbench.update_in(cx, |workbench, window, cx| {
if focused.is_focused(window) {
workbench.show_hover(true, window, cx);
}
});
}));
}
/// The pointer left the target: a pending hover is cancelled, a shown one hides once the mouse tracker's delay passes.
pub(super) fn leave_hover_target(&mut self, cx: &mut Context<Self>) {
if self.hovers.target.take().is_none() {
return;
}
self.hovers.pending = None;
self.hovers.dismissed = false;
self.hide_hover_later(cx);
}
/// CompositeMouseTracker's `onMouseOut`: the hover hides once the pointer stays out of the target, and of the
/// hover when it has a link, for 200ms.
fn hide_hover_later(&mut self, cx: &mut Context<Self>) {
let Some(shown) = self.hovers.shown.as_ref().filter(|shown| !shown.target.options.sticky) else { return };
self.hovers.last_hide = Some(cx.background_executor().now());
let serial = shown.serial;
self.hovers.hiding = Some(cx.spawn(async move |workbench, cx| {
cx.background_executor().timer(MOUSE_OUT_DELAY).await;
let _ = workbench.update(cx, |workbench, cx| {
if !workbench.hovers.locked && workbench.hovers.shown.as_ref().is_some_and(|shown| shown.serial == serial) {
workbench.hovers.shown = None;
cx.notify();
}
});
}));
}
/// hoverService.ts `showManagedHover` (`list.showHover`): the target's hover at once, placed by its bounds.
pub(super) fn show_managed_hover(&mut self, id: impl Into<ElementId>, content: HoverContent, options: HoverOptions, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
self.hovers.target = Some(HoverTarget { id: id.into(), content, options, bounds, mouse_x: None });
self.hovers.dismissed = false;
self.show_hover(false, window, cx);
}
fn show_hover(&mut self, fade_in: bool, window: &mut Window, cx: &mut Context<Self>) {
let Some(target) = self.hovers.target.clone().filter(|_| !self.hovers.dismissed) else { return };
// `_createHover`: no other hover while a locked (sticky) one shows.
if self.hovers.is_sticky() && self.hovers.shown.as_ref().is_some_and(|shown| shown.target.id != target.id) {
return;
}
self.hovers.pending = None;
self.hovers.hiding = None;
self.hovers.shown_count += 1;
let text = self.hover_text(&target.content, window);
// showInstantHover: no hover for empty content.
if text.is_empty() {
return;
}
self.hovers.last = Some(target.clone());
if matches!(target.content, HoverContent::LanguageStatus) {
self.count_language_status_interaction();
}
if let HoverContent::TreeItem { view, handle } = &target.content {
self.resolve_tree_item_hover(view, handle.clone(), target.id.clone(), window, cx);
}
self.hovers.shown = Some(ShownHover { target, text, fade_in, serial: self.hovers.shown_count, trap_focus: false, return_focus: None, focused_link: None, measured: Rc::default() });
cx.notify();
}
/// The content computed after `target`'s hover showed replaces its "Loading..." in place; none hides it.
pub(super) fn replace_shown_hover(&mut self, target: &gpui::ElementId, content: Option<HoverContent>, window: &Window) {
if !self.hovers.shown.as_ref().is_some_and(|shown| shown.target.id == *target) {
return;
}
let Some(content) = content else {
self.hovers.shown = None;
return;
};
let text = self.hover_text(&content, window);
let shown = self.hovers.shown.as_mut().expect("checked above");
shown.text = text;
shown.target.content = content.clone();
self.hovers.last = Some(shown.target.clone());
if let Some(target) = self.hovers.target.as_mut().filter(|target| target.id == shown.target.id) {
target.content = content;
}
}
/// The last hover's `textContent`, which hoverAccessibleViews.ts `ExtHoverAccessibleView` reads.
pub(super) fn last_hover_text(&self, window: &Window) -> Option<String> {
let content = &self.hovers.last.as_ref()?.content;
Some(match content {
HoverContent::Markdown(markdown) => MarkdownString::from_value(markdown).value.split("\n\n").filter(|paragraph| paragraph.trim() != "---").map(|paragraph| linked_text_label(&parse_linked_text(paragraph))).collect(),
_ => self.hover_text(content, window),
})
}
/// hoverService.ts `showAndFocusLastHover`: the last hover again, at once, with the focus in it
/// (`HoverContextViewDelegate.render`).
pub(super) fn show_last_hover(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(last) = self.hovers.last.clone() else { return };
self.hovers.target = Some(last);
self.hovers.dismissed = false;
self.show_hover(false, window, cx);
if self.hovers.shown.is_some() {
window.focus(&self.workbench_hover_focus, cx);
}
}
pub(super) fn register_hover_commands(&mut self) {
self.commands.register("workbench.action.showHover", |workbench, _, window, cx| {
workbench.show_and_focus_hover_for_active_element(window, cx);
crate::commands::Outcome::done()
});
}
/// hoverService.ts `_showAndFocusHoverForActiveElement`: the focused element's hover at once, with the focus in it.
/// A managed hover (`ActionViewItem`) traps the focus and gives it back to the element; a delayed one does
/// neither, and shows nothing when its hover already shows (`showInstantHover`'s identity check).
fn show_and_focus_hover_for_active_element(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.focus_update_tooltip(window, cx) {
return;
}
let Some((id, managed)) = self.focused_hover_target(window) else { return };
let Some((_, target)) = self.hovers.painted.borrow().get(&id).cloned() else { return };
if !managed && self.hovers.shown.as_ref().is_some_and(|shown| shown.target.id == id) {
return;
}
self.show_focused_hover(target, managed, window, cx);
}
/// `showInstantHover` with `focus`, and `trapFocus` for a managed hover.
fn show_focused_hover(&mut self, target: HoverTarget, managed: bool, window: &mut Window, cx: &mut Context<Self>) {
// `trapFocus || isScreenReaderOptimized()` records the element; only `trapFocus` adds the tab loop.
let return_focus = window.focused(cx).filter(|_| managed || self.is_screen_reader_optimized());
self.hovers.target = Some(target);
self.hovers.dismissed = false;
self.show_hover(false, window, cx);
let Some(shown) = self.hovers.shown.as_mut() else { return };
shown.trap_focus = managed;
shown.return_focus = return_focus;
window.focus(&self.workbench_hover_focus, cx);
}
pub(super) fn painted_hover_bounds(&self, id: &ElementId) -> Option<Bounds<Pixels>> {
self.hovers.painted.borrow().get(id).map(|(_, target)| target.bounds)
}
/// The target the last frame painted inside `bounds`, the focused item's: the item's hover.
pub(super) fn painted_hover_within(&self, bounds: Bounds<Pixels>) -> Option<ElementId> {
let painted = self.hovers.painted.borrow();
painted.values().find(|(_, target)| bounds.contains(&target.bounds.center())).map(|(_, target)| target.id.clone())
}
/// The focused element's hover target and whether it is a managed hover. Only these targets take the focus
/// as their own element in the port.
fn focused_hover_target(&self, window: &Window) -> Option<(ElementId, bool)> {
let status_entry = || self.focused_status_entry_bounds(window).and_then(|bounds| self.painted_hover_within(bounds));
if let Some(id) = self.accessible_view_focused_hover(window).or_else(|| self.timeline_focused_hover(window)).or_else(|| self.banner_focused_hover(window)).or_else(|| self.focused_editor_tab_hover(window)).or_else(status_entry).or_else(|| self.focused_action_bar_item(window).and_then(|bounds| self.painted_hover_within(bounds))) {
return Some((id, true));
}
// settingsWidgets.ts rows: `setupDelayedHover`.
Some((self.list_widget_focused_hover(window)?, false))
}
/// A key in the focused hover: hoverWidget.ts's Escape hides it; a trapFocus hover keeps Tab and Shift+Tab, which
/// move through the container and its links (`addFocusTrap`), and Enter or Space opens the focused link.
/// True when handled.
pub(super) fn workbench_hover_key_down(&mut self, keystroke: &gpui::Keystroke, window: &mut Window, cx: &mut Context<Self>) -> bool {
if !self.workbench_hover_focus.is_focused(window) {
return false;
}
let Some(shown) = self.hovers.shown.as_mut() else { return false };
let modifiers = keystroke.modifiers;
match keystroke.key.as_str() {
"escape" => self.hide_hover_on_key_down(window, cx),
"tab" if shown.trap_focus && !(modifiers.control || modifiers.platform || modifiers.alt) => {
let links = hover_link_hrefs(shown).len();
shown.focused_link = next_tab_stop(shown.focused_link, links, modifiers.shift);
cx.notify();
return true;
}
"enter" | "space" if !modifiers.modified() => {
let Some(href) = shown.focused_link.and_then(|link| hover_link_hrefs(shown).into_iter().nth(link)) else { return false };
self.open_hover_link(&href, window, cx);
return true;
}
_ => {}
}
false
}
/// hoverService.ts `_keyDown` with hideOnKeyDown and the hover's `onDispose`: the hover hides, and the focus goes
/// back to `lastFocusedElementBeforeOpen`, or to nothing when the hover had it.
pub(super) fn hide_hover_on_key_down(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let return_focus = self.hovers.shown.as_ref().and_then(|shown| shown.return_focus.clone());
let focused = self.workbench_hover_focus.is_focused(window);
self.dismiss_hover(cx);
match return_focus {
Some(element) => window.focus(&element, cx),
None if focused => window.blur(cx),
None => {}
}
}
/// hoverService.ts `_keyDown` and `_keyUp` of Alt: Alt locks the shown hover; releasing it hides the hover
/// unless the pointer is on it or its target.
pub(super) fn hover_modifiers_changed(&mut self, alt: bool, cx: &mut Context<Self>) {
if self.hovers.shown.is_none() || self.hovers.is_sticky() || alt == self.hovers.locked {
return;
}
self.hovers.locked = alt;
if !alt && !self.hovers.mouse_in_hover && self.hovers.target.is_none() {
self.hovers.shown = None;
self.hovers.last_hide = Some(cx.background_executor().now());
cx.notify();
}
}
/// `hideHover` on mouse down, and `hideOnKeyDown` for a key no keybinding takes.
pub(super) fn dismiss_hover(&mut self, cx: &mut Context<Self>) {
self.hovers.pending = None;
self.hovers.dismissed = self.hovers.target.is_some();
self.hovers.locked = false;
self.hovers.mouse_in_hover = false;
if let Some(shown) = self.hovers.shown.take() {
if shown.target.content == HoverContent::Update && shown.target.options.sticky {
self.update_tooltip_dismissed();
}
self.hovers.last_hide = Some(cx.background_executor().now());
cx.notify();
}
}
fn hover_text(&self, content: &HoverContent, window: &Window) -> String {
match content {
HoverContent::Text(text) | HoverContent::Preview(text) | HoverContent::Policy(text) => text.clone(),
HoverContent::Markdown(markdown) => MarkdownString::from_value(markdown).value.to_owned(),
HoverContent::Action { title, command } => self.keybindings.resolver.append_keybinding(title, command, &self.key_context(window)),
HoverContent::LanguageStatus => self.language_status_hover_text(),
HoverContent::Update => "Update".into(),
HoverContent::TreeItem { .. } => "Loading...".into(),
}
}
pub(super) fn hover_widget(&self, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
let hover = self.hovers.shown.as_ref()?;
let preview = matches!(hover.target.content, HoverContent::Preview(_));
let markdown = match &hover.target.content {
HoverContent::Markdown(markdown) => Some(markdown),
_ => None,
};
let update = hover.target.content == HoverContent::Update;
let language_status = match &hover.target.content {
HoverContent::LanguageStatus => Some(self.language_status_hover(window, cx)),
HoverContent::Update => Some(self.update_tooltip(window, cx)),
_ => None,
};
let policy = matches!(hover.target.content, HoverContent::Policy(_));
let interactive_rows = language_status.is_some() || policy;
let is_markdown = markdown.is_some();
// Markdown is measured as it draws.
let mut content_width = if is_markdown { 0. } else { text_width(&hover.text, false, window) };
if preview {
content_width += text_width(" (", false, window) + text_width("preview", true, window) + text_width(" )", false, window) + FONT_SIZE;
}
let mut content_height = LINE_HEIGHT;
// `.markdown-hover > .hover-contents`: max-width 500px, word-wrap.
let wraps = !is_markdown && !preview && language_status.is_none();
// Only text past the max width wraps: one that fits keeps its line in a box of its rounded width.
let overflows = wraps && content_width > TEXT_MAX_WIDTH;
if overflows {
content_width = TEXT_MAX_WIDTH;
content_height = wrapped_lines(&hover.text, window) as f32 * LINE_HEIGHT;
}
// hoverWidget.css `.hover-row.status-bar`: a 1px top border over 22px lines, the action 8px in and 16px before the end.
if policy {
content_width = content_width.max(text_width(POLICY_ACTION, false, window) + 2. * PADDING_X);
content_height += 1. + STATUS_BAR_HEIGHT;
}
if let Some((content_size, _)) = &language_status {
(content_width, content_height) = (content_size.width, content_size.height);
}
let measuring = is_markdown && hover.measured.get().is_none();
if let Some(measured) = hover.measured.get() {
(content_width, content_height) = (measured.width, measured.height);
}
let padding_x = PADDING_X + hover.target.options.extra_padding_x;
let size = Size { width: (content_width + 2. * padding_x).min(MAX_WIDTH - HOVER_BORDER_WIDTH) + HOVER_BORDER_WIDTH, height: content_height + 2. * PADDING_Y + HOVER_BORDER_WIDTH };
let viewport = window.viewport_size();
// A tooltip shown by itself has no hovered target: it points at where the entry was laid out.
let target = if update { self.update_entry_bounds()? } else { hover.target.bounds };
let target = Bounds { origin: point(f32::from(target.origin.x), f32::from(target.origin.y)), size: Size { width: f32::from(target.size.width), height: f32::from(target.size.height) } };
let mouse_x = hover.target.mouse_x.filter(|_| hover.target.options.follows_mouse);
let layout = layout_hover(Size { width: f32::from(viewport.width), height: f32::from(viewport.height) }, target, size, &hover.target.options, mouse_x);
let radius = if layout.pointer.is_some() { POINTER_RADIUS } else { RADIUS };
let foreground = self.color("editorHoverWidget.foreground");
let border = self.color("editorHoverWidget.border");
let high_contrast = self.theme.kind.is_high_contrast();
let gear = self.app_root.join("node_modules/@vscode/codicons/src/icons/gear.svg");
// The measuring frame lays the contents out at the window's origin, where nothing narrows them.
let origin = if measuring { point(0., 0.) } else { layout.origin };
let panel = div()
.id("workbench-hover")
.debug_selector(|| "workbench-hover".into())
.track_focus(&self.workbench_hover_focus)
.absolute()
.left(px(origin.x))
.top(px(origin.y))
.when(measuring, |panel| panel.invisible())
.when(!measuring, |panel| panel.w(px(size.width)))
.when(!update && !measuring, |panel| panel.h(px(size.height)))
.px(px(padding_x))
.py(px(PADDING_Y))
.border_1()
.border_color(border)
.rounded(px(radius))
.text_size(px(FONT_SIZE))
.line_height(px(LINE_HEIGHT))
.text_color(foreground)
.whitespace_nowrap()
.when(high_contrast, |panel| panel.bg(self.color("editorHoverWidget.background")))
.when(!high_contrast, |panel| {
// --vscode-shadow-lg.
panel.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,
}])
})
.when_some(language_status.map(|(_, rows)| rows), |panel, rows| panel.child(rows))
.when_some(markdown, |panel, markdown| panel.child(self.hover_markdown(markdown, hover, cx)))
.when(wraps, |panel| panel.child(div().debug_selector(|| "workbench-hover-text".into()).when(overflows, |text| text.whitespace_normal()).child(hover.text.clone())))
.when(policy, |panel| panel.child(self.policy_status_bar(cx)))
.when(preview, |panel| panel.child(
div()
.relative()
.flex()
.items_center()
.child(hover.text.clone())
.child(" (")
.child(div().italic().child("preview"))
.child(" ")
.child(
div()
.id("configure-preview-mode")
.cursor_pointer()
.child(gpui::svg().external_path(gear.to_string_lossy().into_owned()).size(px(FONT_SIZE)).text_color(self.color("textLink.foreground")))
.on_click(cx.listener(|workbench, _, window, cx| {
workbench.dismiss_hover(cx);
workbench.execute_command("workbench.action.openSettings", vec![serde_json::json!("workbench.editor.enablePreview")], window, cx);
})),
)
.child(")"),
))
// hideOnHover is off for markdown with a link: the pointer may move onto the hover to click it. A locked
// hover tracks the pointer too (`_lockMouseTracker`), to hide once Alt is up and the pointer leaves.
.when(hover.target.options.sticky, |panel| panel.on_mouse_down_out(cx.listener(|workbench, _, _, cx| workbench.dismiss_hover(cx))))
.on_hover(cx.listener(move |workbench, hovered: &bool, _, cx| {
workbench.hovers.mouse_in_hover = *hovered;
match hovered {
true if preview || is_markdown || interactive_rows || workbench.hovers.locked => workbench.hovers.hiding = None,
false if workbench.hovers.target.is_none() && !workbench.hovers.locked => workbench.hide_hover_later(cx),
_ => {}
}
}));
let caret = layout.pointer.filter(|_| !measuring).map(|offset| self.hover_pointer(layout.side, layout.origin, size, offset));
let widget = div().absolute().inset_0().child(panel).children(caret);
let element = match hover.fade_in {
true => widget.with_animation(("hover-fade-in", hover.serial), Animation::new(Duration::from_millis(100)), |widget, delta| widget.opacity(delta)).into_any_element(),
false => widget.into_any_element(),
};
Some(element)
}
/// hoverWidget.ts: `_markdownRenderer.render` of the contents into `.hover-contents`, at most 500px wide, with the
/// focused link outlined. A canvas over them records their size for the next frame's layout.
fn hover_markdown(&self, markdown: &Value, hover: &ShownHover, cx: &mut Context<Self>) -> impl IntoElement {
let mut blocks = parse(&MarkdownString::from_value(markdown));
if let Some(link) = hover.focused_link {
for span in link_spans(&mut blocks).into_iter().nth(link).into_iter().flatten() {
span.focused = true;
}
}
let style = MarkdownStyle { font_size: FONT_SIZE, line_height: LINE_HEIGHT, foreground: self.foreground_or("editorHoverWidget.foreground"), action_handler: Some(Self::open_hover_link), code_foreground: None, code_background: Some(self.color("textCodeBlock.background")), selectable: false };
let measured = hover.measured.clone();
let measure = canvas(
move |bounds, window, cx| {
if measured.get().is_none() {
measured.set(Some(bounds.size.map(f32::from)));
super::part_view::redraw_after_frame(window, cx);
}
},
|_, _, _, _| (),
)
.absolute()
.inset_0();
div().relative().max_w(px(TEXT_MAX_WIDTH)).whitespace_normal().child(self.markdown_blocks("workbench-hover", &blocks, style, "", cx)).child(measure)
}
/// hoverWidget.ts `HoverAction` in `.hover-row.status-bar`, over the panel's padding; hoverService.ts gives the row a top
/// border of the hover border at half alpha.
fn policy_status_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
let mut separator = self.color("editorHoverWidget.border");
separator.a *= 0.5;
let action = div()
.id("hover-policy-action")
.debug_selector(|| "hover-policy-action".into())
.mr(px(16.))
.cursor_pointer()
.text_color(self.color("textLink.foreground"))
.child(POLICY_ACTION)
.on_click(cx.listener(|workbench, _, window, cx| {
workbench.dismiss_hover(cx);
workbench.apply_settings_filter("@hasPolicy", window, cx);
}));
div()
.mt(px(PADDING_Y))
.mx(px(-PADDING_X))
.mb(px(-PADDING_Y))
.border_t_1()
.border_color(separator)
.child(div().flex().px(px(PADDING_X)).line_height(px(STATUS_BAR_HEIGHT)).bg(self.color("editorHoverWidget.statusBarBackground")).child(action))
}
/// A hover link clicked or opened with Enter: the hover hides, then the opener opens the link. Links the markdown
/// string does not trust never get here: parsing drops them to text.
pub(super) fn open_hover_link(&mut self, href: &str, window: &mut Window, cx: &mut Context<Self>) {
let terminal_link = self.hovers.shown.as_ref().is_some_and(|shown| matches!(&shown.target.id, ElementId::NamedInteger(name, _) if name == super::terminal_links::TERMINAL_LINK_HOVER));
self.dismiss_hover(cx);
// terminalLinkManager.ts `_showHover`'s `linkHandler`: a terminal link's hover activates that link, not the href.
// The hover is trusted, so its href (terminal output) must never reach the opener.
if terminal_link {
if let Some(link) = self.terminal_view.link_in_hover.take() {
self.activate_terminal_link(link, window, cx);
}
return;
}
self.open_notification_link(href, window, cx);
}
/// `.workbench-hover-pointer:after`: a 6px square turned 45 degrees, centered on the hover's edge, in the solid
/// hover background (it sits outside `.monaco-hover`, which frosted glass makes transparent) with its two outer borders.
pub(super) fn hover_pointer(&self, side: HoverPosition, origin: Point<f32>, size: Size<f32>, offset: f32) -> impl IntoElement {
let (square, arms) = pointer_shape(side, origin, size, offset);
let background = self.color("editorHoverWidget.background");
let border = self.color("editorHoverWidget.border");
canvas(
|_, _, _| (),
move |_, _, window, _| {
let to_pixels = |p: Point<f32>| point(px(p.x), px(p.y));
let mut fill = PathBuilder::fill();
fill.move_to(to_pixels(square[0]));
for corner in &square[1..] {
fill.line_to(to_pixels(*corner));
}
fill.close();
if let Ok(path) = fill.build() {
window.paint_path(path, background);
}
let mut stroke = PathBuilder::stroke(px(1.));
stroke.move_to(to_pixels(arms[0]));
stroke.line_to(to_pixels(arms[1]));
stroke.line_to(to_pixels(arms[2]));
if let Ok(path) = stroke.build() {
window.paint_path(path, border);
}
},
)
.absolute()
.inset_0()
}
}
/// The pointer's square, centered on the hover's outer edge, and the centerline of its two outer 1px borders: they run
/// half a pixel inside the square's outward sides, from its side corners to its tip.
fn pointer_shape(side: HoverPosition, origin: Point<f32>, size: Size<f32>, offset: f32) -> ([Point<f32>; 4], [Point<f32>; 3]) {
let half = POINTER_SIZE * std::f32::consts::SQRT_2;
let (center, outward) = match side {
HoverPosition::Right => (point(origin.x, origin.y + offset), point(-1f32, 0.)),
HoverPosition::Left => (point(origin.x + size.width, origin.y + offset), point(1., 0.)),
HoverPosition::Below => (point(origin.x + offset, origin.y), point(0., -1.)),
HoverPosition::Above => (point(origin.x + offset, origin.y + size.height), point(0., 1.)),
};
let along = point(outward.y.abs(), outward.x.abs());
let at = |a: f32, o: f32| point(center.x + along.x * a + outward.x * o, center.y + along.y * a + outward.y * o);
let inset = 0.5 * std::f32::consts::FRAC_1_SQRT_2;
let square = [at(-half, 0.), at(0., half), at(half, 0.), at(0., -half)];
let arms = [at(-half + inset, -inset), at(0., half - 2. * inset), at(half - inset, -inset)];
(square, arms)
}
impl Hovers {
fn is_target(&self, id: &ElementId) -> bool {
self.target.as_ref().is_some_and(|target| &target.id == id)
}
}
fn wrapped_lines(text: &str, window: &Window) -> usize {
let run = TextRun { len: text.len(), font: window.text_style().font(), color: gpui::black(), background_color: None, underline: None, strikethrough: None };
let lines = window.text_system().shape_text(text.to_string().into(), px(FONT_SIZE), &[run], Some(px(TEXT_MAX_WIDTH)), None);
lines.map(|lines| lines.iter().map(|line| line.wrap_boundaries().len() + 1).sum()).unwrap_or(1)
}
fn linked_text_label(nodes: &[Node]) -> String {
nodes.iter().map(|node| match node {
Node::Text(text) => text.as_str(),
Node::Link { label, .. } => label.as_str(),
}).collect()
}
/// The hrefs of the hover's markdown links, in tab order.
fn hover_link_hrefs(shown: &ShownHover) -> Vec<String> {
let HoverContent::Markdown(markdown) = &shown.target.content else { return Vec::new() };
let mut blocks = parse(&MarkdownString::from_value(markdown));
link_spans(&mut blocks).into_iter().filter_map(|spans| spans[0].link.clone()).collect()
}
/// The spans of each link (`<a>`) in the order markdown_view draws them; the styled parts of one link are adjacent
/// spans with its `link_index`.
pub(super) fn link_spans(blocks: &mut [Block]) -> Vec<Vec<&mut Span>> {
let mut links: Vec<Vec<&mut Span>> = Vec::new();
for block in blocks {
match block {
Block::Paragraph(inline) | Block::Heading(_, inline) => {
for span in &mut inline.spans {
if span.link.is_none() {
continue;
}
let continues = links.last().is_some_and(|link| link[0].link_index == span.link_index);
match links.last_mut().filter(|_| continues) {
Some(link) => link.push(span),
None => links.push(vec![span]),
}
}
}
Block::List { items, .. } => items.iter_mut().for_each(|item| links.extend(link_spans(item))),
Block::Quote(blocks) => links.extend(link_spans(blocks)),
Block::Code { .. } | Block::Rule => {}
}
}
links
}
/// hoverWidget.ts `addFocusTrap`: Tab goes from the container through the links and from the last link (the after
/// sentinel) back to the container; Shift+Tab from the container (the before sentinel) to the last link.
fn next_tab_stop(focused_link: Option<usize>, links: usize, backward: bool) -> Option<usize> {
if links == 0 {
return None;
}
match (focused_link, backward) {
(None, false) => Some(0),
(Some(link), false) => (link + 1 < links).then_some(link + 1),
(None, true) => Some(links - 1),
(Some(link), true) => link.checked_sub(1),
}
}
pub(super) fn text_width(text: &str, italic: bool, window: &Window) -> f32 {
let mut font = window.text_style().font();
if italic {
font.style = gpui::FontStyle::Italic;
}
let run = TextRun { len: text.len(), font, color: gpui::black(), background_color: None, underline: None, strikethrough: None };
f32::from(window.text_system().shape_line(text.to_string().into(), px(FONT_SIZE), &[run], None).width)
}
#[derive(Debug, PartialEq)]
pub struct HoverLayout {
/// The hover's border box.
pub origin: Point<f32>,
/// Where the hover went after the fallbacks.
pub side: HoverPosition,
/// The pointer caret's center along the side facing the target, from the box's origin.
pub pointer: Option<f32>,
}
/// hoverWidget.ts `layout`, then the context view's `layout2d` of the anchor it computes. `size` is the border box.
pub fn layout_hover(viewport: Size<f32>, target: Bounds<f32>, size: Size<f32>, options: &HoverOptions, mouse_x: Option<f32>) -> HoverLayout {
let pointer = !options.follows_mouse;
let pointer_offset = if pointer { POINTER_SIZE } else { 0. };
// clientWidth and clientHeight are whole pixels.
let client = Size { width: (size.width - HOVER_BORDER_WIDTH).round(), height: (size.height - HOVER_BORDER_WIDTH).round() };
let hover_width = client.width + HOVER_BORDER_WIDTH;
let (mut left, mut top) = (target.origin.x, target.origin.y);
let (width, height) = (target.size.width, target.size.height);
let mut side = options.position;
// adjustHorizontalHoverPosition
if mouse_x.is_none() {
let room_right = viewport.width - (left + width);
let needed = client.width + pointer_offset;
if side == HoverPosition::Right && room_right < needed {
side = if left >= needed { HoverPosition::Left } else { HoverPosition::Below };
} else if side == HoverPosition::Left {
if left < needed {
side = if room_right >= needed { HoverPosition::Right } else { HoverPosition::Below };
}
if side == HoverPosition::Left && left - needed <= 0. {
side = HoverPosition::Right;
}
}
}
// adjustVerticalHoverPosition
let max_height = viewport.height * options.max_height_ratio;
if side == HoverPosition::Above && top - client.height.min(max_height) - pointer_offset < 0. {
side = HoverPosition::Below;
} else if side == HoverPosition::Below && top + height + size.height.min(max_height) + pointer_offset > viewport.height {
side = HoverPosition::Above;
}
if pointer {
match side {
HoverPosition::Right => left += POINTER_SIZE,
HoverPosition::Left => left -= POINTER_SIZE,
HoverPosition::Below => top += POINTER_SIZE,
HoverPosition::Above => top -= POINTER_SIZE,
}
}
let (right, bottom) = (left + width, top + height);
let center = point(left + width / 2., top + height / 2.);
// computeXCordinate
let mut right_aligned = false;
let mut x = match (mouse_x, side) {
(Some(x), _) => x,
(None, HoverPosition::Right) => right,
(None, HoverPosition::Left) => left - hover_width,
(None, _) => {
let x = if options.anchor_right {
right - hover_width
} else if pointer {
center.x - client.width / 2.
} else {
left
};
right_aligned = x + hover_width >= viewport.width;
if right_aligned { (viewport.width - hover_width - WINDOW_EDGE_MARGIN).max(0.) } else { x }
}
};
if x < 0. {
x = left + WINDOW_EDGE_MARGIN;
}
// computeYCordinate
let mut y = match side {
HoverPosition::Above => top,
HoverPosition::Below => bottom - 2.,
HoverPosition::Left | HoverPosition::Right => {
let y = if pointer { center.y + client.height / 2. } else { bottom };
y.min(viewport.height - WINDOW_EDGE_MARGIN).max(client.height + HOVER_BORDER_WIDTH + WINDOW_EDGE_MARGIN)
}
};
if y > viewport.height {
y = bottom;
}
// The context view anchors the hover at (x, y), below it only for BELOW.
let position = if side == HoverPosition::Below { LayoutAnchorPosition::Before } else { LayoutAnchorPosition::After };
let anchor = Bounds { origin: point(x, y), size: Size { width: 1., height: 2. } };
let origin = layout2d(viewport, size, anchor, position, LayoutAnchorPosition::Before);
let origin = point(f32::from(origin.x), f32::from(origin.y));
// setHoverPointerPosition
let pointer = pointer.then(|| match side {
HoverPosition::Left | HoverPosition::Right if client.height > height => center.y - (y - client.height),
HoverPosition::Left | HoverPosition::Right => client.height / 2.,
HoverPosition::Above | HoverPosition::Below => {
let caret_left = x + client.width / 2. - POINTER_SIZE;
if caret_left < left || caret_left > right { center.x - x } else { client.width / 2. }
}
});
// hover.css `.right-aligned { left: 1px }` moves the hover, not its container with the pointer.
let shift = if right_aligned { 1. } else { 0. };
HoverLayout { origin: point(origin.x + shift, origin.y), side, pointer: pointer.map(|pointer| pointer - shift) }
}
impl Workbench {
/// A native `title` tooltip (`nativeHoverDelegate`): GPUI's tooltip, so it also shows over a workbench hover.
pub(super) fn title_tooltip(&self, text: String) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static {
let colors = (self.color("editorHoverWidget.background"), self.color("editorHoverWidget.border"), self.color("editorHoverWidget.foreground"));
move |_, cx| cx.new(|_| TitleTooltip { text: text.clone(), colors }).into()
}
}
struct TitleTooltip {
text: String,
/// `editorHoverWidget` background, border and foreground.
colors: (Rgba, Rgba, Rgba),
}
impl Render for TitleTooltip {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let (background, border, foreground) = self.colors;
div()
.debug_selector(|| "title-tooltip".into())
.max_w(px(700.))
.px(px(8.))
.py(px(2.))
.bg(background)
.border_1()
.border_color(border)
.rounded(px(8.))
.text_size(px(12.))
.line_height(px(19.))
.text_color(foreground)
.child(self.text.clone())
}
}