Skip to content

Visual Studio Code, rebuilt in Rust

Rust
8.1 KB
Raw Blame
//! markersViewActions.ts `QuickFixAction` with markersTreeViewer.ts `MarkersViewModel` and `MarkerViewModel`: a marker
//! row hovered for 300 ms, or selected, asks once for the quick fixes of its range and keeps them while its markers
//! stand; with fixes, the row shows the light bulb in place of the severity icon, and a click lists their titles.
//! Running one opens the marker's file and applies the fix.

use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

use gpui::{Bounds, Context, Pixels, Task, Window};
use serde_json::json;

use super::Workbench;
use super::code_actions::CodeActionSet;
use crate::commands::Outcome;
use crate::markers::Marker;
use crate::menus::MenuAction;

/// `MarkersViewModel.hoverDelayer`.
const HOVER_DELAY: Duration = Duration::from_millis(300);

#[derive(Default)]
pub(super) struct ProblemsQuickFixes {
    /// `markersViewStates`: the markers asked for their fixes, by identity, as upstream keys them by `Marker.id`.
    markers: Vec<MarkerFixes>,
    /// `hoveredMarker` and its `hoverDelayer`.
    hovered: Option<Arc<Marker>>,
    hover: Option<Task<()>>,
    /// The marker whose fixes the menu lists.
    menu: Option<Arc<Marker>>,
    /// The `problems.quickFix.<index>` commands registered so far.
    commands: usize,
}

/// `MarkerViewModel`: `request` is its `codeActionsPromise`, asked once; `set` holds the fixes it found, if any.
struct MarkerFixes {
    marker: Arc<Marker>,
    request: Option<Task<()>>,
    set: Option<Rc<CodeActionSet>>,
}

impl Workbench {
    /// `onMarkerMouseHover`: the marker the pointer is over gets its fixes after the delay, which a newer hover restarts.
    pub(super) fn problems_marker_hovered(&mut self, marker: &Arc<Marker>, cx: &mut Context<Self>) {
        self.problems_quick_fixes.hovered = Some(marker.clone());
        self.problems_quick_fixes.hover = Some(cx.spawn(async move |workbench, cx| {
            cx.background_executor().timer(HOVER_DELAY).await;
            let _ = workbench.update(cx, |workbench, cx| {
                if let Some(hovered) = workbench.problems_quick_fixes.hovered.clone() {
                    workbench.show_problems_light_bulb(&hovered, cx);
                }
            });
        }));
    }

    /// `onMarkerMouseLeave`.
    pub(super) fn problems_marker_left(&mut self, marker: &Arc<Marker>) {
        if self.problems_quick_fixes.hovered.as_ref().is_some_and(|hovered| Arc::ptr_eq(hovered, marker)) {
            self.problems_quick_fixes.hovered = None;
        }
    }

    /// `MarkerViewModel.showLightBulb`: asks for the marker's fixes unless it did; without a model of the marker's file
    /// it waits for one (`getModel(waitForModel)`).
    pub(super) fn show_problems_light_bulb(&mut self, marker: &Arc<Marker>, cx: &mut Context<Self>) {
        let fixes = &mut self.problems_quick_fixes.markers;
        if !fixes.iter().any(|fixes| Arc::ptr_eq(&fixes.marker, marker)) {
            fixes.push(MarkerFixes { marker: marker.clone(), request: None, set: None });
        }
        self.request_problems_quick_fixes(marker, cx);
    }

    /// A marker waiting for its model gets its fixes once its model opens.
    pub(super) fn problems_quick_fix_model_opened(&mut self, cx: &mut Context<Self>) {
        let waiting: Vec<Arc<Marker>> = self.problems_quick_fixes.markers.iter().filter(|fixes| fixes.request.is_none()).map(|fixes| fixes.marker.clone()).collect();
        for marker in waiting {
            self.request_problems_quick_fixes(&marker, cx);
        }
    }

    /// markersView.ts `onDidChangeModel`: the markers of a changed resource are new ones, without fixes.
    pub(super) fn problems_quick_fix_markers_changed(&mut self, resources: &[String]) {
        let fixes = &mut self.problems_quick_fixes;
        let (dropped, kept): (Vec<MarkerFixes>, Vec<MarkerFixes>) = std::mem::take(&mut fixes.markers).into_iter().partition(|fixes| resources.contains(&fixes.marker.resource));
        fixes.markers = kept;
        if fixes.hovered.as_ref().is_some_and(|hovered| resources.contains(&hovered.resource)) {
            fixes.hovered = None;
        }
        for set in dropped.into_iter().filter_map(|fixes| fixes.set) {
            self.release_code_action_set(set);
        }
    }

    fn request_problems_quick_fixes(&mut self, marker: &Arc<Marker>, cx: &mut Context<Self>) {
        let Some(index) = self.problems_quick_fixes.markers.iter().position(|fixes| Arc::ptr_eq(&fixes.marker, marker) && fixes.request.is_none()) else { return };
        let Some(editor) = self.editors.all_editors().find(|editor| editor.document().uri_string() == marker.resource) else { return };
        let request = self.request_marker_quick_fixes(editor, marker);
        let marker = marker.clone();
        self.problems_quick_fixes.markers[index].request = Some(cx.spawn(async move |workbench, cx| {
            let set = request.await;
            let _ = workbench.update(cx, |workbench, cx| {
                let fixes = workbench.problems_quick_fixes.markers.iter_mut().find(|fixes| Arc::ptr_eq(&fixes.marker, &marker));
                match fixes {
                    Some(fixes) if !set.valid.is_empty() => fixes.set = Some(Rc::new(set)),
                    _ => workbench.release_code_action_set(Rc::new(set)),
                }
                cx.notify();
            });
        }));
    }

    /// The light bulb of `marker`'s row, `None` without fixes. `QuickFixAction.autoFixable` only adds a class no CSS
    /// rule styles, and markers.css colors `codicon-light-bulb`, not the `codicon-lightbulb` the action has, so the
    /// icon is always the plain one in the row's color.
    pub(super) fn problems_quick_fix_icon(&self, marker: &Marker) -> Option<&'static str> {
        self.problems_quick_fixes.markers.iter().find(|fixes| std::ptr::eq(fixes.marker.as_ref(), marker) && fixes.set.is_some()).map(|_| "lightbulb")
    }

    /// `QuickFixActionViewItem.showQuickFixes`: `marker`'s fixes' titles in a context menu 10px right of and 4px below
    /// the light bulb's top left corner.
    pub(super) fn show_problems_quick_fixes(&mut self, marker: &Arc<Marker>, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let Some(set) = self.problems_quick_fix_set(marker) else { return };
        while self.problems_quick_fixes.commands < set.valid.len() {
            let index = self.problems_quick_fixes.commands;
            self.commands.register(format!("problems.quickFix.{index}"), move |workbench, _, window, cx| {
                workbench.run_problems_quick_fix(index, window, cx);
                Outcome::done()
            });
            self.problems_quick_fixes.commands += 1;
        }
        let actions = set.valid.iter().enumerate().map(|(index, item)| MenuAction::Command { id: format!("problems.quickFix.{index}"), title: item.action["title"].as_str().unwrap_or_default().to_owned(), enabled: true, checked: false, alt: None }).collect();
        self.problems_quick_fixes.menu = Some(marker.clone());
        let anchor = Bounds { origin: gpui::point(anchor.origin.x + gpui::px(10.), anchor.origin.y + anchor.size.height + gpui::px(4.)), size: gpui::Size::default() };
        let context = self.key_context(window);
        self.show_context_menu_actions(actions, &context, anchor, Vec::new(), window, cx);
    }

    /// `toActions`' run: open the file at the marker, then apply the fix.
    fn run_problems_quick_fix(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        let Some(marker) = self.problems_quick_fixes.menu.clone() else { return };
        let Some(set) = self.problems_quick_fix_set(&marker) else { return };
        let Some(item) = set.valid.get(index).cloned() else { return };
        let target = json!({ "resource": crate::debug::uri_from_string(&marker.resource), "startLineNumber": marker.start_line, "startColumn": marker.start_column });
        self.open_marker_related(&target, window, cx);
        self.apply_code_action(item, set, false, false, window.window_handle(), cx).detach();
    }

    fn problems_quick_fix_set(&self, marker: &Arc<Marker>) -> Option<Rc<CodeActionSet>> {
        self.problems_quick_fixes.markers.iter().find(|fixes| Arc::ptr_eq(&fixes.marker, marker)).and_then(|fixes| fixes.set.clone())
    }
}