gpui-base 0.12.0

Behavior, interaction, and infrastructure foundations for GPUI applications.
Documentation
use anyhow::Result;
use gpui::{App, Context, MouseMoveEvent, Task, Window};
use instant::Duration;
use ropey::Rope;

use crate::input::{EditorMode, HoverPopoverState, InputBaseState, RopeExt, ShowHover};

/// Hover provider
///
/// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_hover
pub trait HoverProvider {
    /// textDocument/hover
    ///
    /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_hover
    fn hover(
        &self,
        _text: &Rope,
        _offset: usize,
        _window: &mut Window,
        _cx: &mut App,
    ) -> Task<Result<Option<lsp_types::Hover>>>;
}

impl InputBaseState<EditorMode> {
    /// Handle hover trigger LSP request.
    pub(super) fn handle_hover_popover(
        &mut self,
        offset: usize,
        window: &mut Window,
        cx: &mut Context<InputBaseState<EditorMode>>,
    ) {
        if self.selecting {
            return;
        }

        let Some(provider) = self.extras.lsp.hover_provider.clone() else {
            return;
        };

        if let Some(hover_popover) = self.extras.hover_popover.as_ref() {
            if hover_popover.symbol_range.contains(&offset) {
                return;
            }
        }

        let text = self.text.clone();
        let symbol_range = self.text.word_range(offset).unwrap_or(offset..offset);
        let editor = cx.entity();
        let should_delay = self.extras.hover_popover.is_none();
        // Ask the provider only after the delay: every mouse move replaces this
        // task, so positions the pointer merely passes over never reach it.
        self.extras.lsp._hover_task = cx.spawn_in(window, async move |this, cx| {
            if should_delay {
                cx.background_executor()
                    .timer(Duration::from_millis(150))
                    .await;
            }

            let task = this.update_in(cx, |_, window, cx| {
                provider.hover(&text, offset, window, cx)
            })?;
            let result = task.await?;

            _ = editor.update(cx, |editor, cx| {
                editor.apply_hover_result(result, symbol_range, cx);
            });

            Ok(())
        });
    }

    /// Show the provider's answer anchored to `symbol_range`, or close the
    /// popover when there is none. The answer's own range takes precedence.
    fn apply_hover_result(
        &mut self,
        result: Option<lsp_types::Hover>,
        mut symbol_range: std::ops::Range<usize>,
        cx: &mut Context<Self>,
    ) {
        match result {
            Some(hover) => {
                if let Some(range) = hover.range {
                    let start = self.text.position_to_offset(&range.start);
                    let end = self.text.position_to_offset(&range.end);
                    symbol_range = start..end;
                }
                self.extras.hover_popover = Some(HoverPopoverState {
                    symbol_range,
                    hover,
                });
            }
            None => {
                self.extras.hover_popover = None;
            }
        }
        cx.notify();
    }

    pub(crate) fn on_action_show_hover(
        &mut self,
        _: &ShowHover,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.show_hover(window, cx);
    }

    /// Ask the [`HoverProvider`] about the caret and open the hover popover
    /// there, as resting the mouse on the text does. Focuses the editor.
    ///
    /// There is no default keybinding; applications can dispatch [`ShowHover`]
    /// in the `Input && mode == editor` context or call this method from a
    /// command.
    ///
    /// The popover is shown without the mouse delay. Escape, editing, moving
    /// the caret and losing focus close it, and a late answer is dropped once
    /// any of those happened. Disabled editors, editors without a provider and
    /// IME preedit issue no request; a popover already open for the symbol
    /// under the caret is left as it is.
    pub fn show_hover(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.disabled || self.ime_marked_range.is_some() {
            return;
        }
        let Some(provider) = self.extras.lsp.hover_provider.clone() else {
            return;
        };

        let offset = self.cursor();
        self.focus(window, cx);
        if let Some(hover_popover) = self.extras.hover_popover.as_ref() {
            if hover_popover.symbol_range.contains(&offset) {
                return;
            }
        }

        let symbol_range = self.text.word_range(offset).unwrap_or(offset..offset);
        let revision = self.document_revision;
        let task = provider.hover(&self.text, offset, window, cx);
        self.extras.lsp._show_hover_task = cx.spawn_in(window, async move |editor, cx| {
            let result = task.await?;
            editor.update_in(cx, |editor, window, cx| {
                if !editor.focus_handle.is_focused(window)
                    || editor.document_revision != revision
                    || editor.cursor() != offset
                    || editor.ime_marked_range.is_some()
                {
                    return;
                }
                editor.apply_hover_result(result, symbol_range, cx);
            })?;
            Ok(())
        });
    }

    /// Close the hover popover and cancel a pending [`ShowHover`] request.
    ///
    /// Unlike [`Self::clear_hover_state`], this leaves the go-to-definition
    /// underline and its pending lookup alone, so a caret move made by the same
    /// click does not cancel them.
    pub(crate) fn dismiss_hover_popover(&mut self, cx: &mut Context<Self>) {
        self.extras.lsp._show_hover_task = Task::ready(Ok(()));
        if self.extras.hover_popover.take().is_some() {
            cx.notify();
        }
    }

    pub(crate) fn handle_mouse_move(
        &mut self,
        offset: usize,
        event: &MouseMoveEvent,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if event.modifiers.alt {
            self.clear_hover_state(cx);
            return;
        }
        if event.modifiers.secondary(cx) {
            self.handle_hover_definition(offset, window, cx);
        } else {
            // Repaint only when the definition underline goes away; the hover
            // and definition results notify when they arrive.
            if !self.extras.hover_definition.is_empty() {
                self.extras.hover_definition.clear();
                cx.notify();
            }
            self.handle_hover_popover(offset, window, cx);
        }
    }

    pub fn clear_hover_state(&mut self, cx: &mut Context<Self>) {
        let changed =
            !self.extras.hover_definition.is_empty() || self.extras.hover_popover.is_some();
        self.extras.hover_definition.clear();
        self.extras.hover_popover = None;
        self.extras.lsp._hover_task = Task::ready(Ok(()));
        self.extras.lsp._show_hover_task = Task::ready(Ok(()));
        if changed {
            cx.notify();
        }
    }
}