Skip to content

Visual Studio Code, rebuilt in Rust

Rust
20.4 KB
Raw Blame
//! The Notebook Variables view in the Run and Debug container (notebookVariables.ts, notebookVariablesView.ts,
//! notebookVariablesDataSource.ts, notebookVariablesTree.ts) and its `MenuId.NotebookVariablesContext` menu
//! (notebookVariableCommands.ts).

use std::collections::HashMap;
use std::time::Duration;

use futures::channel::oneshot;
use gpui::{ClickEvent, Context, MouseButton, MouseDownEvent, Window, div, prelude::*, px};
use serde_json::{Value, json};

use super::Workbench;
use super::debug_view::{EXPRESSION_FONT, EXPRESSION_FONT_SIZE};
use super::hover::{HoverContent, HoverOptions};
use crate::commands::Outcome;
use crate::debug::session::Variable;
use crate::menus::{MenuId, menu_group_actions};
use crate::notebook;

pub(super) const NOTEBOOK_VARIABLES_VIEW: &str = "workbench.notebook.variables";
/// notebookKernelService.ts `variablePageSize`.
const PAGE_SIZE: u64 = 100;
/// notebookVariablesDataSource.ts `indexedChildCountLimit`.
const INDEXED_CHILD_COUNT_LIMIT: u64 = 1_000_000;
/// notebookVariablesTree.ts `MAX_VALUE_RENDER_LENGTH_IN_VIEWLET`.
const MAX_VALUE_LENGTH: usize = 1024;
const ROOT: &str = "";

#[derive(Default)]
pub(super) struct NotebookVariables {
    /// notebookVariables.ts `initialized`: the view registers once and stays.
    pub registered: bool,
    /// notebookVariablesView.ts `activeNotebook`, and whether it shows in a REPL (the REPL Variables title).
    notebook: Option<String>,
    repl: bool,
    /// The tree's children by parent element id, `ROOT` for the notebook.
    children: HashMap<String, Vec<Element>>,
    /// `updateScheduler` and `dataSource.cancel`: an answer of an older generation is dropped.
    generation: u64,
}

/// notebookVariablesDataSource.ts `INotebookVariableElement`.
#[derive(Clone, Debug, PartialEq)]
struct Element {
    id: String,
    ext_host_id: Value,
    name: String,
    value: String,
    type_name: Option<String>,
    result: Value,
    indexed_children_count: u64,
    index_start: Option<u64>,
    has_named_children: bool,
}

impl Element {
    /// `createVariableElement`: a `VariablesResult` of the extension host.
    fn from_result(result: &Value) -> Element {
        Element {
            id: result["id"].to_string(),
            ext_host_id: result["id"].clone(),
            name: result["name"].as_str().unwrap_or_default().to_owned(),
            value: result["value"].as_str().unwrap_or_default().to_owned(),
            type_name: result["type"].as_str().map(str::to_owned),
            result: result.clone(),
            indexed_children_count: result["indexedChildrenCount"].as_u64().unwrap_or_default(),
            index_start: None,
            has_named_children: result["hasNamedChildren"] == true,
        }
    }

    fn has_children(&self) -> bool {
        self.has_named_children || self.indexed_children_count > 0
    }

    /// `getIndexedChildren` over a page: the ranges of `nestedPageSize` children it splits into, and a last row when
    /// the count passes the display limit.
    fn index_ranges(&self) -> Vec<Element> {
        let page = (self.indexed_children_count as f64 / PAGE_SIZE as f64).max(100.).floor() as u64;
        let mut start = self.index_start.unwrap_or_default();
        let last = start + self.indexed_children_count.min(INDEXED_CHILD_COUNT_LIMIT);
        let range = |id: String, name: String, count: u64, index_start: Option<u64>| Element {
            id,
            ext_host_id: self.ext_host_id.clone(),
            name,
            value: String::new(),
            type_name: None,
            result: Value::Null,
            indexed_children_count: count,
            index_start,
            has_named_children: false,
        };
        let mut ranges = Vec::new();
        while start < last {
            let end = (start + page).min(last);
            ranges.push(range(format!("{}{start}", self.id), format!("[{start}..{}]", end - 1), end - start, Some(start)));
            start += page;
        }
        if self.indexed_children_count > INDEXED_CHILD_COUNT_LIMIT {
            ranges.push(range(format!("{}{}", self.id, last + 1), "Display limit reached".into(), 0, None));
        }
        ranges
    }
}

impl Workbench {
    /// notebookVariables.ts `handleInitEvent` on an active editor change (`notebook` None), an execution change of
    /// `notebook` or a `notebook.variablesView` change: with the setting on (or a REPL active) and a notebook whose
    /// selected kernel has a variable provider, the view registers and `notebookVariableViewEnabled` turns on.
    pub(super) fn init_notebook_variables_view(&mut self, notebook: Option<&str>, cx: &mut Context<Self>) {
        if self.notebook_variables.registered {
            return;
        }
        let repl = self.active_interactive().is_some_and(|interactive| interactive.repl);
        let enabled = repl || self.setting("notebook.variablesView") == true || self.setting("notebook.experimental.variablesView") == true;
        // `activeEditorPane.getId() === 'workbench.editor.notebook'`: an interactive window or REPL is not one.
        let active = self.active_notebook_editor().filter(|_| self.active_interactive().is_none()).map(|editor| editor.notebook.clone());
        let Some(key) = notebook.map(str::to_owned).or(active).filter(|_| enabled) else { return };
        if !self.has_variable_provider(&key) {
            return;
        }
        self.notebook_variables.registered = true;
        self.context_keys.insert("notebookVariableViewEnabled".into(), json!(true));
        self.notebook_variables_editor_changed(cx);
    }

    fn has_variable_provider(&self, key: &str) -> bool {
        let notebooks = &self.host.notebooks;
        let Some(model) = notebooks.model(key) else { return false };
        notebooks.kernels.matching(&model.view_type, key).1.is_some_and(|kernel| kernel.has_variable_provider)
    }

    /// notebookVariablesView.ts `handleCloseEditor`, the shown notebook's editor closed leaves an empty tree, and
    /// `handleActiveEditorChange`, a new active notebook (a REPL's too) becomes the input.
    pub(super) fn notebook_variables_editor_changed(&mut self, cx: &mut Context<Self>) {
        if !self.notebook_variables.registered {
            return;
        }
        let shown = self.notebook_variables.notebook.clone();
        if shown.as_ref().is_some_and(|key| !self.host.notebooks.editors.iter().any(|editor| editor.notebook == *key)) {
            self.notebook_variables.notebook = None;
            self.notebook_variables.children.clear();
            self.notebook_variables.generation += 1;
        }
        let Some(key) = self.active_notebook_editor().map(|editor| editor.notebook.clone()) else { return };
        if self.notebook_variables.notebook.as_deref() == Some(key.as_str()) {
            return;
        }
        self.notebook_variables.repl = self.active_interactive().is_some();
        self.notebook_variables.notebook = Some(key);
        self.notebook_variables.children.clear();
        self.schedule_notebook_variables_update(cx);
    }

    /// `handleExecutionStateChange`: an execution that starts or runs cancels the pending requests, one that ends
    /// asks again; `handleVariablesChanged` asks again too.
    pub(super) fn notebook_variables_changed(&mut self, key: &str, ended: bool, cx: &mut Context<Self>) {
        if self.notebook_variables.notebook.as_deref() != Some(key) {
            return;
        }
        self.notebook_variables.generation += 1;
        if ended {
            self.schedule_notebook_variables_update(cx);
        }
    }

    /// `updateScheduler`: 100ms later `tree.updateChildren()` asks again for the root and every expanded element.
    fn schedule_notebook_variables_update(&mut self, cx: &mut Context<Self>) {
        self.notebook_variables.generation += 1;
        let generation = self.notebook_variables.generation;
        cx.spawn(async move |workbench, cx| {
            cx.background_executor().timer(Duration::from_millis(100)).await;
            let _ = workbench.update(cx, |workbench, cx| {
                if workbench.notebook_variables.generation == generation {
                    workbench.load_notebook_variables(None, cx);
                }
            });
        })
        .detach();
    }

    /// notebookVariablesDataSource.ts `getChildren` of `parent` (the root for None), then of its expanded children.
    fn load_notebook_variables(&mut self, parent: Option<Element>, cx: &mut Context<Self>) {
        let Some(key) = self.notebook_variables.notebook.clone() else { return };
        let parent_id = parent.as_ref().map_or(ROOT.to_owned(), |parent| parent.id.clone());
        if let Some(parent) = parent.as_ref().filter(|parent| parent.indexed_children_count > PAGE_SIZE) {
            let ranges = parent.index_ranges();
            return self.set_notebook_variables(parent_id, ranges, cx);
        }
        // The named children come first, then a page of the indexed ones (`getIndexedChildren`).
        let mut requests = Vec::new();
        match &parent {
            None => requests.push((self.provide_variables(&key, Value::Null, "named", 0, cx), usize::MAX)),
            Some(parent) => {
                if parent.has_named_children {
                    requests.push((self.provide_variables(&key, parent.ext_host_id.clone(), "named", 0, cx), usize::MAX));
                }
                if parent.indexed_children_count > 0 {
                    requests.push((self.provide_variables(&key, parent.ext_host_id.clone(), "indexed", parent.index_start.unwrap_or_default(), cx), PAGE_SIZE as usize));
                }
            }
        }
        let generation = self.notebook_variables.generation;
        cx.spawn(async move |workbench, cx| {
            let mut children = Vec::new();
            for (request, limit) in requests {
                let Some(request) = request else { continue };
                let results = request.await.ok().and_then(Result::ok).unwrap_or_default();
                children.extend(results.iter().take(limit).map(Element::from_result));
            }
            let _ = workbench.update(cx, |workbench, cx| {
                if workbench.notebook_variables.generation == generation {
                    workbench.set_notebook_variables(parent_id, children, cx);
                }
            });
        })
        .detach();
    }

    fn set_notebook_variables(&mut self, parent_id: String, children: Vec<Element>, cx: &mut Context<Self>) {
        let expanded: Vec<Element> = children.iter().filter(|child| child.has_children() && self.debug_view.expanded.contains(&row_key(&child.id))).cloned().collect();
        self.notebook_variables.children.insert(parent_id, children);
        for child in expanded {
            self.load_notebook_variables(Some(child), cx);
        }
        cx.notify();
    }

    /// mainThreadNotebookKernels.ts `provideVariables` of the notebook's selected kernel: the variables
    /// `$receiveVariable` brought while `$provideVariables` ran. None without a variable provider.
    fn provide_variables(&mut self, key: &str, parent: Value, kind: &str, start: u64, cx: &mut Context<Self>) -> Option<oneshot::Receiver<Result<Vec<Value>, Value>>> {
        let model = self.host.notebooks.model(key)?;
        let (uri, view_type) = (model.uri.clone(), model.view_type.clone());
        let kernels = &mut self.host.notebooks.kernels;
        let handle = kernels.matching(&view_type, key).1.filter(|kernel| kernel.has_variable_provider)?.handle;
        let request_id = format!("{handle}variables{}", kernels.variable_request_index);
        kernels.variable_request_index += 1;
        kernels.variable_requests.insert(request_id.clone(), Vec::new());
        let call = self.host.call_cancellable("ExtHostNotebookKernels", "$provideVariables", vec![json!(handle), json!(request_id), uri, parent, json!(kind), json!(start)]);
        let (sender, receiver) = oneshot::channel();
        cx.spawn(async move |workbench, cx| {
            let answer = call.await;
            let collected = workbench.update(cx, |workbench, _| workbench.host.notebooks.kernels.variable_requests.remove(&request_id).unwrap_or_default()).unwrap_or_default();
            let _ = sender.send(match answer {
                Ok(Err(error)) => Err(error),
                _ => Ok(collected),
            });
        })
        .detach();
        Some(receiver)
    }

    /// notebookVariableCommands.ts `_executeNotebookVariableProvider`: the named variables of the notebook's selected
    /// kernel, when it has a variable provider.
    pub(super) fn execute_notebook_variable_provider(&mut self, resource: Option<&Value>, cx: &mut Context<Self>) -> Outcome {
        let key = resource.map(notebook::uri_string).unwrap_or_default();
        let Some(request) = self.provide_variables(&key, Value::Null, "named", 0, cx) else { return Outcome::Ready(Ok(json!([]))) };
        let (sender, receiver) = oneshot::channel();
        cx.spawn(async move |_, _| {
            let _ = sender.send(request.await.unwrap_or(Ok(Vec::new())).map(|collected| json!(collected)));
        })
        .detach();
        Outcome::Pending(receiver)
    }

    pub(super) fn register_notebook_variable_commands(&mut self) {
        self.commands.register("_executeNotebookVariableProvider", |workbench, args, _, cx| workbench.execute_notebook_variable_provider(args.first(), cx));
        // COPY_NOTEBOOK_VARIABLE_VALUE_ID: the menu's `contextMenuArg`.
        self.commands.register("workbench.debug.viewlet.action.copyWorkspaceVariableValue", |_, args, _, cx| {
            if let Some(value) = args.first().and_then(|arg| arg["value"].as_str()).filter(|value| !value.is_empty()) {
                cx.write_to_clipboard(gpui::ClipboardItem::new_string(value.to_owned()));
            }
            Outcome::done()
        });
    }

    pub(super) fn notebook_variables_pane(&self, window: &Window, cx: &mut Context<Self>) -> super::view_panes::ViewPane {
        // notebookVariablesView.ts `setActiveNotebook`: `REPL_TITLE` for a composite notebook editor.
        let title = if self.notebook_variables.repl { "REPL Variables" } else { "Notebook Variables" };
        let focus = self.debug_view.list_focus[NOTEBOOK_VARIABLES_VIEW].clone();
        let menu_return = self.context_menu.as_ref().and_then(|menu| menu.focus_to_return.as_ref());
        let list_focused = focus.is_focused(window) || menu_return == Some(&focus);
        let mut rows = Vec::new();
        self.notebook_variable_rows(ROOT, 0, list_focused, &mut rows, cx);
        let body = div().id(NOTEBOOK_VARIABLES_VIEW).track_focus(&focus).capture_any_mouse_down(move |_, window, cx| window.focus(&focus, cx));
        super::view_panes::ViewPane { id: NOTEBOOK_VARIABLES_VIEW, title: title.into(), description: None, actions: None, draws_more: false, show_actions: false, body: self.scrollable(NOTEBOOK_VARIABLES_VIEW, None, body.children(rows), cx).flex_1().into_any_element() }
    }

    /// notebookVariablesTree.ts `NotebookVariableRenderer`: `name:` with the type as its title, then the value in the
    /// debug token colors, cut at 1024 characters.
    fn notebook_variable_rows(&self, parent: &str, depth: usize, list_focused: bool, rows: &mut Vec<gpui::AnyElement>, cx: &mut Context<Self>) {
        let Some(children) = self.notebook_variables.children.get(parent) else { return };
        for element in children {
            let key = row_key(&element.id);
            let expandable = element.has_children();
            let expanded = expandable && self.debug_view.expanded.contains(&key);
            let name = if element.value.trim().is_empty() { element.name.clone() } else { format!("{}:", element.name) };
            let mut value = element.value.clone();
            if value.len() > MAX_VALUE_LENGTH {
                value = format!("{}...", value.chars().take(MAX_VALUE_LENGTH).collect::<String>());
            }
            let color = self.value_color(&Variable { value: value.clone(), ..Variable::default() });
            let mut name_label = div().id(gpui::SharedString::from(format!("{key}/name"))).flex_none().text_color(self.color("debugTokenExpression.name")).child(name);
            if let Some(type_name) = element.type_name.clone().filter(|type_name| !type_name.is_empty()) {
                name_label = name_label.child(self.hover_target(gpui::SharedString::from(format!("{key}/type")), HoverContent::Text(type_name), HoverOptions::mouse()));
            }
            let label = div().flex().min_w_0().overflow_hidden().whitespace_nowrap().font_family(EXPRESSION_FONT).text_size(px(EXPRESSION_FONT_SIZE)).child(name_label).child(div().ml(px(6.)).text_color(color).overflow_hidden().text_ellipsis().child(value));
            let (toggled, menu_element) = (element.clone(), element.clone());
            let row = self.debug_row(key.clone(), depth, expandable.then_some(expanded), self.row_selected(&key), list_focused, cx).child(label);
            let row = row.on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
                if expandable {
                    workbench.toggle_notebook_variable(toggled.clone(), cx);
                }
            }));
            let row = row.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                workbench.show_notebook_variable_menu(&menu_element, gpui::Bounds::new(event.position, Default::default()), window, cx);
            }));
            rows.push(row.into_any_element());
            if expanded {
                self.notebook_variable_rows(&element.id, depth + 1, list_focused, rows, cx);
            }
        }
    }

    fn toggle_notebook_variable(&mut self, element: Element, cx: &mut Context<Self>) {
        let key = row_key(&element.id);
        if !self.debug_view.expanded.remove(&key) {
            self.debug_view.expanded.insert(key);
            if !self.notebook_variables.children.contains_key(&element.id) {
                self.load_notebook_variables(Some(element), cx);
            }
        }
        cx.notify();
    }

    /// notebookVariablesView.ts `onContextMenu`: the row's keys over the context and its `contextMenuArg` forwarded.
    fn show_notebook_variable_menu(&mut self, element: &Element, anchor: gpui::Bounds<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let Some(key) = self.notebook_variables.notebook.clone() else { return };
        let source = self.host.notebooks.model(&key).map(|model| model.uri_string()).unwrap_or(key);
        let result = &element.result;
        let mut context = self.key_context(window);
        let keys = [("variableName", json!(element.name)), ("variableValue", json!(element.value)), ("variableType", result["type"].clone()), ("variableInterfaces", result["interfaces"].clone()), ("variableLanguage", result["language"].clone()), ("variableExtensionId", result["extensionId"].clone())];
        for (name, value) in keys {
            context.insert(name.into(), value);
        }
        let arg = json!({ "source": source, "name": element.name, "value": element.value, "type": result["type"], "expression": result["expression"], "language": result["language"], "extensionId": result["extensionId"] });
        let actions = menu_group_actions(&self.menus, MenuId::NotebookVariablesContext, &context, |_| true);
        self.show_context_menu_actions(actions, &context, anchor, vec![arg], window, cx);
    }
}

#[cfg(test)]
impl Workbench {
    /// The shown rows' names, two spaces deeper per level.
    pub(super) fn notebook_variable_names(&self) -> Vec<String> {
        fn walk(workbench: &Workbench, parent: &str, depth: usize, names: &mut Vec<String>) {
            for element in workbench.notebook_variables.children.get(parent).into_iter().flatten() {
                names.push(format!("{}{}", "  ".repeat(depth), element.name));
                if workbench.debug_view.expanded.contains(&row_key(&element.id)) {
                    walk(workbench, &element.id, depth + 1, names);
                }
            }
        }
        let mut names = Vec::new();
        walk(self, ROOT, 0, &mut names);
        names
    }

    fn notebook_variable(&self, id: &str) -> Element {
        self.notebook_variables.children.values().flatten().find(|element| element.id == id).expect("a shown row").clone()
    }

    pub(super) fn toggle_notebook_variable_row(&mut self, id: &str, cx: &mut Context<Self>) {
        self.toggle_notebook_variable(self.notebook_variable(id), cx);
    }

    pub(super) fn show_notebook_variable_row_menu(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {
        self.show_notebook_variable_menu(&self.notebook_variable(id), Default::default(), window, cx);
    }
}

fn row_key(id: &str) -> String {
    format!("{NOTEBOOK_VARIABLES_VIEW}/{id}")
}