Skip to content

Visual Studio Code, rebuilt in Rust

Rust
55.4 KB
Raw Blame
//! Extension tree views (mainThreadTreeViews.ts, treeView.ts `TreeView`, viewsExtensionPoint.ts): the views
//! extensions contribute to the Explorer, their items fetched from `ExtHostTreeViews`, drawn as panes.

use std::collections::{HashMap, HashSet};
use std::sync::{LazyLock, Mutex};

use futures::FutureExt;
use futures::channel::oneshot;
use futures::future::Shared;
use gpui::{AnyElement, AppContext, ClickEvent, Context, Div, FocusHandle, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, ParentElement, StatefulInteractiveElement, Styled, Task, Window, div, img, prelude::FluentBuilder, px};
use serde_json::{Value, json};

use super::Workbench;
use super::hover::{HoverContent, HoverOptions};
use super::markdown_view::MarkdownStyle;
use super::opener::{OpenOptions, Target};
use crate::commands::Outcome;
use crate::contextkey::Expr;
use crate::custom_tree::{Collapsible, CustomTree, DragAndDrop, TreeItem};
use crate::markdown::MarkdownString;
use crate::menus::MenuId;
use crate::notifications::{Node, Severity, parse_linked_text};

#[cfg(test)]
mod tests;

/// A tree or webview view of `contributes.views`.
pub(super) struct ContributedView {
    pub id: &'static str,
    pub name: String,
    /// The `contributes.views` key: `explorer`, `scm`, `debug`, `test` or a `viewsContainers` id.
    pub container: String,
    pub when: Option<Expr>,
    /// `"visibility": "hidden"`: hidden until shown from the container's Views submenu.
    pub hide_by_default: bool,
    /// `"visibility": "collapsed"`.
    pub collapsed: bool,
    /// `accessibilityHelpContent`, read only with the `contribAccessibilityHelpContent` proposal enabled.
    pub accessibility_help_content: Option<String>,
    /// `type: webview`: a webview view (webview_views.rs), whose pane holds a webview, not a tree.
    pub webview: bool,
}

#[derive(Default)]
pub(super) struct TreeViews {
    pub views: Vec<ContributedView>,
    pub containers: Vec<super::view_containers::ViewContainer>,
    trees: HashMap<String, CustomTree>,
    /// Views whose tree shows, as last told to the host (`$setVisible`).
    visible: HashSet<String>,
    pub focus: HashMap<String, FocusHandle>,
    /// The roots being fetched per view, which a reveal waits for (AsyncDataTree shares a node's refresh).
    root_fetches: HashMap<String, Shared<Task<()>>>,
    /// treeViewsDndService: the host's data transfer of a drag (`$handleDrag`) by operation id, until its drop.
    drag_transfers: HashMap<String, Shared<Task<Value>>>,
    /// Each view's drag not dropped yet, released when its next drag starts (`cancelDragOperation`).
    drag_operations: HashMap<&'static str, String>,
    /// `DataTransferFileCache`'s request ids.
    drop_requests: u64,
}

/// treeView.ts `CustomTreeViewDragAndDrop.onDragStart`: the items a drag on a view's row carries.
#[derive(Clone)]
pub(super) struct DraggedTreeItems {
    view: &'static str,
    handles: Vec<String>,
    /// The source controller's `dragMimeTypes`, set empty on the drag (`addExtensionProvidedTransferTypes`).
    drag_mime_types: Vec<String>,
    uuid: String,
    label: String,
    colors: (gpui::Rgba, gpui::Rgba, Option<gpui::Rgba>),
}

impl gpui::Render for DraggedTreeItems {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        super::explorer_actions::drag_image(self.label.clone(), self.colors.0, self.colors.1, self.colors.2)
    }
}

/// `CustomTreeViewDragAndDrop.treeMimeType`.
fn tree_mime_type(view: &str) -> String {
    format!("application/vnd.code.tree.{}", view.to_lowercase())
}

/// `onDragOver`: the view takes a drag that carries its own tree's type or one of its `dropMimeTypes`.
fn accepts_drop(view: &str, controller: Option<&DragAndDrop>, dragged: &DraggedTreeItems) -> bool {
    let Some(controller) = controller.filter(|controller| !controller.drop_mime_types.is_empty()) else { return false };
    let own = tree_mime_type(view);
    dragged.mime_types().iter().any(|mime| *mime == own || controller.drop_mime_types.contains(mime))
}

impl DraggedTreeItems {
    /// The types on the drag: the source tree's, then its `dragMimeTypes`.
    fn mime_types(&self) -> Vec<String> {
        let mut types = vec![tree_mime_type(self.view)];
        types.extend(self.drag_mime_types.iter().cloned());
        types
    }
}

/// Pane ids are `&'static str`; a contributed view's id is interned once, so a reinstall does not leak again.
/// A line of a markdown `TreeView.message` (treeView.ts `processMessage`): a lone link is a button, secondary right
/// after another button; any other line renders as markdown.
#[derive(Debug, PartialEq)]
enum MessageLine<'a> {
    Button { label: String, href: String, title: Option<String>, secondary: bool },
    Markdown(&'a str),
}

fn message_lines(value: &str) -> Vec<MessageLine<'_>> {
    let mut lines = Vec::new();
    let mut after_button = false;
    for line in value.split('\n') {
        let mut nodes = parse_linked_text(line);
        match nodes.as_mut_slice() {
            [Node::Link { label, href, title }] => {
                lines.push(MessageLine::Button { label: std::mem::take(label), href: std::mem::take(href), title: title.take(), secondary: after_button });
                after_button = true;
            }
            _ => {
                lines.push(MessageLine::Markdown(line));
                after_button = false;
            }
        }
    }
    lines
}

pub(super) fn static_id(id: &str) -> &'static str {
    static IDS: LazyLock<Mutex<HashSet<&'static str>>> = LazyLock::new(Mutex::default);
    let mut ids = IDS.lock().unwrap();
    if let Some(&interned) = ids.get(id) {
        return interned;
    }
    let interned: &'static str = Box::leak(id.to_owned().into_boxed_str());
    ids.insert(interned);
    interned
}

/// viewsExtensionPoint.ts: the tree and webview views of every container, in extension order.
pub(super) fn contributed_views(extensions: &[exthost::scan::ScannedExtension]) -> Vec<ContributedView> {
    let mut known_containers: HashSet<String> = ["explorer", "debug", "scm", "remote"].map(String::from).into();
    known_containers.extend(super::view_containers::valid_view_containers(extensions).into_iter().filter(|(_, location, _)| ["activitybar", "panel", "secondarySidebar"].contains(location)).filter_map(|(_, _, descriptor)| descriptor["id"].as_str().map(String::from)));
    known_containers.extend(crate::command_palette::REFERENCE["viewContainers"].as_array().expect("an array").iter().filter_map(|id| id.as_str()?.strip_prefix("workbench.view.extension.").map(String::from)));
    let built_in_views = crate::command_palette::REFERENCE["viewIds"].as_array().expect("an array");
    let mut ids = HashSet::new();
    let mut views = Vec::new();
    for extension in extensions {
        let Some(containers) = extension.description["contributes"]["views"].as_object() else { continue };
        let report = |severity, message| crate::perf::extension_point_message(&extension.id, severity, message);
        let proposed = |proposal: &str| extension.description["enabledApiProposals"].as_array().is_some_and(|proposals| proposals.iter().any(|enabled| enabled == proposal));
        for (key, container_views) in containers {
            if let Err(message) = validate_view_descriptors(container_views) {
                report(Severity::Error, message);
                continue;
            }
            if key == "remote" && !proposed("contribViewsRemote") {
                report(Severity::Warning, format!("View container '{key}' requires 'enabledApiProposals: [\"contribViewsRemote\"]' to be added to 'Remote'."));
                continue;
            }
            if key == "agentSessions" && !proposed("chatSessionsProvider") {
                report(Severity::Warning, format!("View container '{key}' requires 'enabledApiProposals: [\"chatSessionsProvider\"]'."));
                continue;
            }
            let container = if known_containers.contains(key) {
                key.clone()
            } else {
                report(Severity::Warning, format!("View container '{key}' does not exist and all views registered to it will be added to 'Explorer'."));
                "explorer".to_owned()
            };
            for view in container_views.as_array().expect("validated") {
                let id = view["id"].as_str().expect("validated");
                if ids.contains(id) {
                    report(Severity::Error, format!("Cannot register multiple views with same id `{id}`"));
                    continue;
                }
                if built_in_views.iter().any(|built_in| built_in == id) {
                    report(Severity::Error, format!("A view with id `{id}` is already registered."));
                    continue;
                }
                // `getViewType`: a falsy type is a tree.
                let webview = match &view["type"] {
                    Value::Null | Value::Bool(false) => false,
                    Value::String(kind) if kind.is_empty() || kind == "tree" => false,
                    Value::String(kind) if kind == "webview" => true,
                    Value::Number(number) if number.as_f64() == Some(0.) => false,
                    kind => {
                        report(Severity::Error, format!("Unknown view type `{}`.", kind.as_str().map_or_else(|| kind.to_string(), String::from)));
                        continue;
                    }
                };
                ids.insert(id);
                let (hide_by_default, collapsed) = super::view_visibility::initial_visibility(view);
                views.push(ContributedView { id: static_id(id), name: view["name"].as_str().expect("validated").to_owned(), container: container.clone(), when: view["when"].as_str().and_then(Expr::deserialize), hide_by_default, collapsed, accessibility_help_content: accessibility_help_content(extension, view), webview });
            }
        }
    }
    views
}

/// viewsExtensionPoint.ts `isValidViewDescriptors`.
fn validate_view_descriptors(views: &Value) -> Result<(), String> {
    let Some(views) = views.as_array() else { return Err("views must be an array".into()) };
    // `descriptor.x && typeof descriptor.x !== 'string'`: a JS-truthy value that is not a string.
    let truthy_non_string = |value: &Value| match value {
        Value::Null | Value::Bool(false) | Value::String(_) => false,
        Value::Number(number) => number.as_f64() != Some(0.),
        _ => true,
    };
    for view in views {
        for property in ["id", "name"] {
            if !view[property].is_string() {
                return Err(format!("property `{property}` is mandatory and must be of type `string`"));
            }
        }
        for property in ["when", "icon", "contextualTitle"] {
            if truthy_non_string(&view[property]) {
                return Err(format!("property `{property}` can be omitted or must be of type `string`"));
            }
        }
        let visibility = &view["visibility"];
        let falsy = matches!(visibility, Value::Null | Value::Bool(false)) || visibility == "" || visibility.as_f64() == Some(0.);
        if !falsy && !["visible", "hidden", "collapsed"].iter().any(|value| visibility == value) {
            return Err("property `visibility` can be omitted or must be one of visible, hidden, collapsed".into());
        }
    }
    Ok(())
}

/// A view's `accessibilityHelpContent`, read only with the `contribAccessibilityHelpContent` proposal enabled.
pub(super) fn accessibility_help_content(extension: &exthost::scan::ScannedExtension, view: &Value) -> Option<String> {
    let proposals = extension.description["enabledApiProposals"].as_array()?;
    let content = view["accessibilityHelpContent"].as_str().filter(|content| !content.is_empty())?;
    proposals.iter().any(|proposal| proposal == "contribAccessibilityHelpContent").then(|| content.to_owned())
}

impl Workbench {
    pub(crate) fn set_tree_views(&mut self, extensions: &[exthost::scan::ScannedExtension]) {
        let mut previous: Vec<_> = self.tree_views.containers.iter().map(|container| container.id.to_owned()).collect();
        previous.extend(self.tree_views.views.iter().map(|view| format!("{}.focus", view.id)));
        self.quick_access.menu.retain(|item| !previous.contains(&item.id));
        self.tree_views.views = contributed_views(extensions);
        self.tree_views.containers = super::view_containers::contributed_view_containers(extensions);
        self.register_view_container_commands();
    }

    /// The contributed views of the Explorer whose `when` holds, which it shows as panes.
    pub(super) fn shown_tree_views(&self) -> Vec<&'static str> {
        self.shown_views_of("explorer")
    }

    /// viewContainerModel.ts `visibleViewDescriptors`: the container's contributed views whose `when` holds and
    /// that are not hidden.
    pub(super) fn shown_views_of(&self, container: &str) -> Vec<&'static str> {
        let views = self.tree_views.views.iter().filter(|view| view.container == container && view.when.as_ref().is_none_or(|when| when.evaluate(&self.context_keys)) && !self.view_hidden(container, view.id));
        views.map(|view| view.id).collect()
    }

    pub(crate) fn handle_tree_view_request(&mut self, method: &str, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let null = Value::Null;
        let arg = |index: usize| args.get(index).unwrap_or(&null);
        let id = arg(0).as_str().unwrap_or_default().to_owned();
        match method {
            "$registerTreeViewDataProvider" => {
                let tree = self.tree_views.trees.entry(id.clone()).or_default();
                tree.has_provider = true;
                tree.show_collapse_all = arg(1)["showCollapseAll"] == true;
                let collapse_all = format!("workbench.actions.treeView.{id}.collapseAll");
                if tree.show_collapse_all && self.commands.get(&collapse_all).is_none() {
                    let view = id.clone();
                    self.commands.register(collapse_all, move |workbench, _, _, cx| {
                        workbench.update_tree(&view, |tree| tree.expanded.clear(), cx);
                        Outcome::done()
                    });
                }
                tree.can_select_many = arg(1)["canSelectMany"] == true;
                tree.manually_manage_checkboxes = arg(1)["manuallyManageCheckboxes"] == true;
                let strings = |key: &str| arg(1)[key].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
                tree.drag_and_drop = (arg(1)["hasHandleDrag"] == true || arg(1)["hasHandleDrop"] == true).then(|| DragAndDrop { drop_mime_types: strings("dropMimeTypes"), drag_mime_types: strings("dragMimeTypes"), has_handle_drag: arg(1)["hasHandleDrag"] == true });
                let has_resolve = self.host.call("ExtHostTreeViews", "$hasResolve", vec![json!(id)]);
                let view = id.clone();
                cx.spawn(async move |workbench, cx| {
                    let has_resolve = has_resolve.await == Ok(Ok(Value::Bool(true)));
                    let _ = workbench.update(cx, |workbench, _| workbench.tree_views.trees.get_mut(&view).map(|tree| tree.has_resolve = has_resolve));
                })
                .detach();
                let visible = self.tree_views.visible.contains(&id);
                self.host.send("ExtHostTreeViews", "$setVisible", vec![json!(id), json!(visible)]);
                cx.notify();
            }
            "$refresh" => {
                let Some(tree) = self.tree_views.trees.get_mut(&id).filter(|tree| tree.has_provider) else { return Outcome::done() };
                let parents = match arg(1).as_object().filter(|items| !items.is_empty()) {
                    Some(items) => tree.refresh(items),
                    None => vec![None],
                };
                // treeView.ts `refresh`: the tree is created when its view is visible; before that nothing is fetched.
                if self.tree_views.visible.contains(&id) {
                    for parent in parents {
                        if let Some(tree) = self.tree_views.trees.get_mut(&id) {
                            match &parent {
                                None => tree.roots = None,
                                Some(parent) => drop(tree.children.remove(parent)),
                            }
                        }
                    }
                    self.fetch_missing_children(cx);
                }
                cx.notify();
            }
            "$reveal" => return self.reveal_tree_item(id, arg(1).clone(), arg(2).clone(), window, cx),
            "$setMessage" => self.update_tree(&id, |tree| tree.message = Some(arg(1).clone()).filter(|message| message.as_str() != Some("")), cx),
            "$setTitle" => self.update_tree(&id, |tree| (tree.title, tree.description) = (arg(1).as_str().map(str::to_owned), arg(2).as_str().map(str::to_owned)), cx),
            "$setBadge" => self.update_tree(&id, |tree| tree.badge = Some(arg(1).clone()).filter(|badge| !badge.is_null()), cx),
            "$disposeTree" => self.update_tree(&id, |tree| *tree = CustomTree::default(), cx),
            "$resolveDropFileData" => return Outcome::error("Unknown tree"),
            // `$logResolveTreeNodeFailure` is telemetry.
            _ => {}
        }
        Outcome::done()
    }

    /// The `$setBadge` value of a contributed view (`{ value, tooltip }`).
    pub(super) fn tree_view_badge(&self, id: &str) -> Option<&Value> {
        self.tree_views.trees.get(id).and_then(|tree| tree.badge.as_ref()).or_else(|| self.webview_view_badge(id))
    }

    fn update_tree(&mut self, id: &str, update: impl FnOnce(&mut CustomTree), cx: &mut Context<Self>) {
        update(self.tree_views.trees.entry(id.to_owned()).or_default());
        cx.notify();
    }

    /// mainThreadTreeViews.ts `$reveal`: opens the view, then (its tree shown) fetches the roots if there are none,
    /// expands the parents, selects and focuses the item and expands it `expand` levels (3 at most).
    fn reveal_tree_item(&mut self, id: String, item_info: Value, options: Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        self.open_tree_view(&id, false, window, cx);
        let (sender, receiver) = oneshot::channel();
        let handle = item_info["item"]["handle"].as_str().map(str::to_owned);
        let parents: Vec<String> = item_info["parentChain"].as_array().into_iter().flatten().filter_map(|parent| parent["handle"].as_str().map(str::to_owned)).collect();
        let select = options["select"] == true;
        let focus = options["focus"] == true;
        let levels = match &options["expand"] {
            Value::Number(levels) => levels.as_u64().unwrap_or(0).min(3),
            Value::Bool(true) => 1,
            _ => 0,
        };
        cx.spawn_in(window, async move |workbench, cx| {
            let shown = workbench.update(cx, |workbench, _| workbench.tree_views.visible.contains(&id) && workbench.tree_views.trees.get(&id).is_some_and(|tree| tree.has_provider));
            if let (Ok(true), Some(handle)) = (shown, handle) {
                let roots = workbench.update(cx, |workbench, cx| workbench.tree_views.trees[&id].roots.is_none().then(|| workbench.fetch_roots(&id, cx)));
                if let Ok(Some(roots)) = roots {
                    roots.await;
                }
                let mut to_expand: Vec<String> = parents;
                let mut level = 0;
                loop {
                    let fetches = workbench.update(cx, |workbench, cx| workbench.expand_tree_items(&id, &to_expand, cx));
                    let Ok(fetches) = fetches else { break };
                    for fetch in fetches {
                        fetch.await;
                    }
                    let next = workbench.update(cx, |workbench, _| {
                        let tree = &workbench.tree_views.trees[&id];
                        if level == 0 {
                            return vec![handle.clone()].into_iter().filter(|handle| tree.items.contains_key(handle)).collect();
                        }
                        to_expand.iter().flat_map(|parent| tree.children.get(parent).cloned().unwrap_or_default()).collect::<Vec<String>>()
                    });
                    let Ok(next) = next else { break };
                    if level == 0 {
                        let _ = workbench.update_in(cx, |workbench, window, cx| workbench.select_tree_item(&id, &handle, select, focus, window, cx));
                    }
                    level += 1;
                    if level > levels || next.is_empty() {
                        break;
                    }
                    to_expand = next;
                }
            }
            let _ = sender.send(Ok(Value::Null));
        })
        .detach();
        Outcome::Pending(receiver)
    }

    /// Expands the items and fetches the children nobody fetched yet, returning those fetches.
    fn expand_tree_items(&mut self, id: &str, handles: &[String], cx: &mut Context<Self>) -> Vec<Task<()>> {
        let Some(tree) = self.tree_views.trees.get_mut(id) else { return Vec::new() };
        let mut missing = Vec::new();
        for handle in handles {
            let Some(item) = tree.items.get(handle).filter(|item| item.collapsible != Collapsible::None) else { continue };
            if tree.expanded.insert(item.handle.clone()) {
                self.host.send("ExtHostTreeViews", "$setExpanded", vec![json!(id), json!(handle), json!(true)]);
            }
            if !tree.children.contains_key(handle) {
                missing.push(handle.clone());
            }
        }
        cx.notify();
        if missing.is_empty() {
            return Vec::new();
        }
        vec![self.fetch_tree_children(id.to_owned(), Some(missing), cx)]
    }

    fn select_tree_item(&mut self, id: &str, handle: &str, select: bool, focus: bool, window: &mut Window, cx: &mut Context<Self>) {
        let tree = self.tree_views.trees.get_mut(id).expect("revealed in a known tree");
        if select {
            tree.selection = vec![handle.to_owned()];
        }
        tree.focus = Some(handle.to_owned());
        self.host.send("ExtHostTreeViews", "$setSelectionAndFocus", vec![json!(id), json!(tree.selection), json!(handle)]);
        if focus && let Some(focus) = self.tree_views.focus.get(id) {
            window.focus(&focus.clone(), cx);
        }
        cx.notify();
    }

    /// `TreeViewDataProvider.getChildrenBatch`: `$getChildren` answers one `[index, ...items]` group per parent.
    fn fetch_tree_children(&mut self, id: String, parents: Option<Vec<String>>, cx: &mut Context<Self>) -> Task<()> {
        let tree = self.tree_views.trees.entry(id.clone()).or_default();
        let keys: Vec<Option<String>> = match &parents {
            None => vec![None],
            Some(parents) => parents.iter().cloned().map(Some).collect(),
        };
        tree.fetching.extend(keys.iter().cloned());
        let reply = self.host.call("ExtHostTreeViews", "$getChildren", vec![json!(id), json!(parents)]);
        cx.spawn(async move |workbench, cx| {
            let groups = match reply.await {
                Ok(Ok(Value::Array(groups))) => groups,
                Ok(Err(error)) => {
                    let _ = workbench.update(cx, |workbench, cx| {
                        workbench.notify_error(error["message"].as_str().unwrap_or_default());
                        cx.notify();
                    });
                    Vec::new()
                }
                _ => Vec::new(),
            };
            let _ = workbench.update(cx, |workbench, cx| {
                if parents.is_none() {
                    workbench.tree_views.root_fetches.remove(&id);
                }
                let Some(tree) = workbench.tree_views.trees.get_mut(&id) else { return };
                for key in &keys {
                    tree.fetching.remove(key);
                }
                let mut children: Vec<Vec<Value>> = vec![Vec::new(); keys.len()];
                for group in groups {
                    let Value::Array(mut group) = group else { continue };
                    let Some(index) = group.first().and_then(Value::as_u64).map(|index| index as usize).filter(|index| *index < keys.len()) else { continue };
                    group.remove(0);
                    children[index] = group;
                }
                let mut checked = Vec::new();
                for (key, items) in keys.iter().zip(children) {
                    checked.extend(tree.set_children(key.as_deref(), items));
                }
                if !checked.is_empty() {
                    workbench.send_checkbox_states(&id, &checked);
                }
                cx.notify();
            });
        })
    }

    /// The view's root fetch, started unless one is under way.
    fn fetch_roots(&mut self, id: &str, cx: &mut Context<Self>) -> Shared<Task<()>> {
        if let Some(fetch) = self.tree_views.root_fetches.get(id) {
            return fetch.clone();
        }
        let fetch = self.fetch_tree_children(id.to_owned(), None, cx).shared();
        self.tree_views.root_fetches.insert(id.to_owned(), fetch.clone());
        fetch
    }

    /// Fetches the roots of each shown tree with a provider and the children of its expanded items.
    fn fetch_missing_children(&mut self, cx: &mut Context<Self>) {
        let visible: Vec<String> = self.tree_views.visible.iter().cloned().collect();
        for id in visible {
            let Some(tree) = self.tree_views.trees.get(&id).filter(|tree| tree.has_provider) else { continue };
            if tree.roots.is_none() {
                drop(self.fetch_roots(&id, cx));
                continue;
            }
            let missing: Vec<String> = tree.missing_children().into_iter().filter(|handle| !tree.fetching.contains(&Some(handle.clone()))).collect();
            if !missing.is_empty() {
                self.fetch_tree_children(id, Some(missing), cx).detach();
            }
        }
    }

    /// treeView.ts `onDidChangeBodyVisibility`: `$setVisible` when a view's tree shows or hides; the first show
    /// activates `onView:<id>` (`TreeView.activate`) and fetches the roots.
    pub(super) fn sync_tree_views(&mut self, cx: &mut Context<Self>) {
        for id in self.tree_views.views.iter().map(|view| view.id).collect::<Vec<_>>() {
            self.tree_views.focus.entry(id.to_owned()).or_insert_with(|| cx.focus_handle().tab_stop(true));
        }
        let shown: Vec<&'static str> = self.tree_views.views.iter().map(|view| view.id).filter(|&id| self.tree_view_body_visible(id)).collect();
        for id in shown.iter().copied().chain(self.tree_views.visible.iter().map(|id| static_id(id)).collect::<Vec<_>>()) {
            let visible = shown.contains(&id);
            if visible == self.tree_views.visible.contains(id) {
                continue;
            }
            if visible {
                self.tree_views.visible.insert(id.to_owned());
                drop(self.host.activate_by_event(&format!("onView:{id}")));
            } else {
                self.tree_views.visible.remove(id);
            }
            if self.tree_views.trees.get(id).is_some_and(|tree| tree.has_provider) {
                self.host.send("ExtHostTreeViews", "$setVisible", vec![json!(id), json!(visible)]);
            }
        }
        self.fetch_missing_children(cx);
    }

    /// The pane of a contributed view: its title (the view's `name`, or `TreeView.title`), title actions, message
    /// and rows.
    pub(super) fn tree_view_pane(&self, id: &'static str, window: &Window, cx: &mut Context<Self>) -> super::view_panes::ViewPane {
        let view = self.tree_views.views.iter().find(|view| view.id == id);
        let name = view.map(|view| view.name.clone()).unwrap_or_default();
        if view.is_some_and(|view| view.webview) {
            return self.webview_view_pane(id, name, window, cx);
        }
        let focus = self.tree_views.focus[id].clone();
        let empty = CustomTree::default();
        let tree = self.tree_views.trees.get(id).unwrap_or(&empty);
        let title = tree.title.clone().unwrap_or(name);
        let foreground = self.foreground_or("sideBar.foreground");
        let mut context = self.key_context(window);
        context.insert("view".into(), json!(id));
        // treeView.ts `CollapseAllAction`: last in the navigation group of a view made with `showCollapseAll`.
        let collapse_all = tree.show_collapse_all.then(|| self.action_bar_item(id, "collapse-all", self.search_action("collapse-all", static_id(&format!("workbench.actions.treeView.{id}.collapseAll")), true, cx), cx));
        // paneCompositePart.css: 4px after each title action.
        let actions = div().flex().gap(px(4.)).child(self.inline_actions(MenuId::ViewTitle, Some(id), &context, Vec::new(), foreground, cx).gap(px(4.))).children(collapse_all).into_any_element();
        // treeView.ts `updateMessage`: `noDataProviderMessage` until the extension registers a provider.
        let no_provider = (!tree.has_provider).then(|| json!("There is no data provider registered that can provide view data."));
        let message = tree.message.as_ref().filter(|message| *message != "").or(no_provider.as_ref()).map(|message| self.tree_view_message(id, message, &context, cx));
        let focused = focus.is_focused(window);
        let controller = tree.drag_and_drop.clone();
        let tree_rows = tree.rows();
        let depths: Vec<usize> = tree_rows.iter().map(|(_, depth)| depth + 1).collect();
        let active: Vec<usize> = tree_rows.iter().enumerate().filter(|(_, (item, _))| tree.selection.contains(&item.handle) || tree.focus.as_ref() == Some(&item.handle)).map(|(index, _)| index).collect();
        let group = gpui::SharedString::from(format!("tree-body-{id}"));
        let guides = self.tree_guides_in_group(group.clone(), depths, &active);
        // `.monaco-tl-row` starts at the 4px row margin, its guides 16px further (TreeGuides adds 3px to the inset).
        let rows: Vec<AnyElement> = tree_rows.into_iter().enumerate().map(|(index, (item, depth))| div().relative().child(self.tree_row(id, tree, item, depth, index, focused, window, cx)).children(guides.row(index, 4.)).into_any_element()).collect();
        // treeView.ts `updateContentAreas`: a message over an empty tree makes the view's node the focus target, outlined.
        let outlined = focused && message.is_some() && rows.is_empty();
        let body = div()
            .id(id)
            .group(group)
            .track_focus(&focus)
            .relative()
            .flex()
            .flex_col()
            .children(message)
            .children(rows)
            .when(outlined, |body| body.child(self.focus_outline().debug_selector(move || format!("tree-view-outline-{id}"))))
            .can_drop(move |dragged, _, _| dragged.downcast_ref::<DraggedTreeItems>().is_some_and(|dragged| accepts_drop(id, controller.as_ref(), dragged)))
            .on_drop(cx.listener(move |workbench, dragged: &DraggedTreeItems, _, cx| workbench.drop_tree_items(id, None, dragged, cx)));
        let body = self.scrollable(id, None, body, cx).size_full().into_any_element();
        super::view_panes::ViewPane { id, title, description: tree.description.clone(), actions: Some(actions), draws_more: false, show_actions: focused, body }
    }

    /// treeView.ts `showMessage` in views.css `.message`: a string as text, a markdown string by `processMessage`.
    fn tree_view_message(&self, id: &str, message: &Value, context: &HashMap<String, Value>, cx: &mut Context<Self>) -> Div {
        let selector = format!("tree-message-{id}");
        let container = div().debug_selector(move || selector).flex().pt(px(4.)).pb(px(4.)).pl(px(18.)).pr(px(12.)).line_height(px(18.2));
        if let Some(text) = message.as_str() {
            return container.child(div().flex_1().min_w_0().child(text.to_owned()));
        }
        let markdown = MarkdownString::from_value(message);
        let enablements = crate::keybindings::command_enablements(&self.extensions);
        let style = MarkdownStyle { font_size: 13., line_height: 18.2, foreground: self.foreground_or("sideBar.foreground"), action_handler: None, code_foreground: None, code_background: None, selectable: false };
        let lines = message_lines(markdown.value);
        let count = lines.len();
        let mut rendered = div().w_full().flex().flex_col();
        for (index, line) in lines.into_iter().enumerate() {
            let element_id = format!("tree-message-{id}-{index}");
            rendered = match line {
                MessageLine::Button { label, href, title, secondary } => {
                    let command = href.strip_prefix("command:").map(|command| command.split('?').next().unwrap_or(command));
                    let enabled = command.and_then(|command| enablements.get(command)).is_none_or(|precondition| precondition.evaluate(context));
                    // views.css: `.button-container` at most 300px wide, centered, 8px above the next line.
                    let button = self.tree_message_button(element_id, &label, href, title, secondary, enabled, cx);
                    rendered.child(div().w_full().max_w(px(300.)).mx_auto().when(index + 1 < count, |container| container.pb(px(8.))).child(button))
                }
                MessageLine::Markdown(line) => {
                    let blocks = crate::markdown::parse(&MarkdownString { value: line, is_trusted: markdown.is_trusted, support_theme_icons: markdown.support_theme_icons });
                    // views.css: `.message p` has 4px of bottom padding.
                    rendered.when(!blocks.is_empty(), |rendered| rendered.child(self.markdown_blocks(&element_id, &blocks, style, "", cx).pb(px(4.))))
                }
            };
        }
        container.child(rendered)
    }

    /// A `monaco-text-button` with `supportIcons` (button.css: 4px 8px padding, 16px lines of 12px text), secondary
    /// colors after another button; a disabled one is dimmed and takes no click.
    #[allow(clippy::too_many_arguments)]
    fn tree_message_button(&self, id: String, label: &str, href: String, title: Option<String>, secondary: bool, enabled: bool, cx: &mut Context<Self>) -> impl IntoElement {
        let [background, foreground, hover] = match secondary {
            true => ["button.secondaryBackground", "button.secondaryForeground", "button.secondaryHoverBackground"],
            false => ["button.background", "button.foreground", "button.hoverBackground"],
        }
        .map(|key| self.color(key));
        let border = self.theme.color(if secondary { "button.secondaryBorder" } else { "button.border" }).or_else(|| self.theme.color("button.border"));
        div()
            .id(gpui::SharedString::from(id.clone()))
            .w_full()
            .px(px(8.))
            .py(px(4.))
            .flex()
            .justify_center()
            .rounded(px(4.))
            .border_1()
            .border_color(border.unwrap_or(gpui::transparent_black().into()))
            .text_size(px(12.))
            .line_height(px(16.))
            .bg(background)
            .text_color(foreground)
            .overflow_hidden()
            .whitespace_nowrap()
            .child(self.button_label(label, foreground))
            .when_some(title, |button, title| button.child(self.hover_target(gpui::SharedString::from(id), HoverContent::Text(title), HoverOptions::mouse())))
            .when(!enabled, |button| button.opacity(0.4))
            .when(enabled, |button| {
                button.cursor_pointer().hover(move |button| button.bg(hover)).on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                    drop(workbench.open_link(Target::Text(href.clone()), OpenOptions { allow_commands: true, ..Default::default() }, window, cx));
                }))
            })
    }

    #[allow(clippy::too_many_arguments)]
    fn tree_row(&self, id: &'static str, tree: &CustomTree, item: &TreeItem, depth: usize, index: usize, focused: bool, window: &Window, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let foreground = self.foreground_or("sideBar.foreground");
        let handle = item.handle.clone();
        let selected = tree.selection.contains(&handle);
        let is_focus = focused && tree.focus.as_ref() == Some(&handle);
        let expanded = tree.expanded.contains(&handle);
        let mut context = self.key_context(window);
        context.insert("view".into(), json!(id));
        context.insert("viewItem".into(), item.dto["contextValue"].clone());
        // treeView.ts `TreeViewItemHandleArg`, revived by the host into the extension's element.
        let args = vec![json!({ "$treeViewId": id, "$treeItemHandle": handle })];
        let actions = self.inline_actions(MenuId::ViewItemContext, None, &context, args.clone(), foreground, cx);
        let row_id = gpui::SharedString::from(format!("tree-{id}-{handle}"));
        let twistie = match (item.collapsible, expanded) {
            (Collapsible::None, _) => div().size(px(16.)).flex_none(),
            (_, true) => self.icon("chevron-down", 16., 16., foreground),
            (_, false) => self.icon("chevron-right", 16., 16., foreground),
        };
        let toggled = handle.clone();
        let twistie = twistie.id(("tree-twistie", index)).on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
            cx.stop_propagation();
            workbench.toggle_tree_item(id, &toggled, cx);
        }));
        let (selection, selection_foreground) = match focused {
            true => (self.color("list.activeSelectionBackground"), self.theme.color("list.activeSelectionForeground")),
            false => (self.color("list.inactiveSelectionBackground"), self.theme.color("list.inactiveSelectionForeground")),
        };
        let hover = self.tree_item_hover(id, tree, item);
        let checkbox = item.checked().map(|checked| self.tree_item_checkbox(id, &handle, checked, selected, cx));
        let label = self.tree_item_label(item);
        // `description: true`: the resource's folder as the label service shows it, relative to the workspace.
        let description = match item.dto["description"] {
            Value::Bool(true) => item.dto["resourceUri"]["path"].as_str().and_then(|path| std::path::Path::new(path).parent()).map(|folder| crate::quick_input::path_label(folder, self.workspace())),
            _ => item.description(),
        };
        let clicked = handle.clone();
        let context_menu = context.clone();
        let menu_args = args.clone();
        let dragged = self.tree_items_drag(id, tree, item);
        let workbench = cx.entity().downgrade();
        let controller = tree.drag_and_drop.clone();
        let can_drop = controller.clone();
        let drop_background = self.color("list.dropBackground");
        let dropped_on = handle.clone();
        let selector = format!("tree-row-{handle}");
        div()
            .id(row_id.clone())
            .debug_selector(move || selector)
            .when_some(dragged, |row, dragged| {
                row.on_drag(dragged, move |dragged, _, _, cx| {
                    let _ = workbench.update(cx, |workbench, cx| workbench.start_tree_drag(dragged, cx));
                    cx.new(|_| dragged.clone())
                })
            })
            .can_drop(move |dragged, _, _| dragged.downcast_ref::<DraggedTreeItems>().is_some_and(|dragged| accepts_drop(id, can_drop.as_ref(), dragged)))
            .drag_over::<DraggedTreeItems>(move |row, dragged, _, _| if accepts_drop(id, controller.as_ref(), dragged) { row.bg(drop_background) } else { row })
            .on_drop(cx.listener(move |workbench, dragged: &DraggedTreeItems, _, cx| {
                cx.stop_propagation();
                workbench.drop_tree_items(id, Some(dropped_on.clone()), dragged, cx);
            }))
            .group(row_id.clone())
            .relative()
            .h(px(22.))
            .mx(px(self.pane_row_inset()))
            .pl(px(11. + self.tree_indent() * depth as f32))
            .pr(px(12.))
            .flex()
            .items_center()
            .rounded(px(4.))
            // list.css: .monaco-list.mouse-support .monaco-list-row is cursor: pointer.
            .cursor_pointer()
            .hover(|row| row.bg(self.color("list.hoverBackground")))
            .when(selected, |row| row.bg(selection).when_some(selection_foreground, |row, color| row.text_color(color)))
            .when_some(self.theme.color("list.focusOutline").filter(|_| is_focus), |row, color| row.child(div().absolute().inset_0().rounded(px(4.)).border_1().border_color(color)))
            .when_some(hover, |row, hover| row.child(self.hover_target(("tree-hover", index), hover, HoverOptions::mouse())))
            .child(twistie)
            .children(checkbox)
            .children(self.tree_item_icon(item, foreground).map(|icon| icon.ml(px(3.)).mr(px(6.))))
            // iconLabel.ts: the label shrinks with an ellipsis once its description is gone.
            .child(div().min_w_0().truncate().when(item.strikethrough(), |label| label.line_through()).child(label))
            .children(description.map(|description| super::icon_label::label_description().flex_1().min_w_0().truncate().opacity(0.7).child(description)))
            .child(div().flex_none().ml_auto().invisible().group_hover(row_id, |actions| actions.visible()).when(selected || is_focus, |actions| actions.visible()).child(actions))
            .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| workbench.tree_item_clicked(id, &clicked, window, cx)))
            .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                workbench.show_context_menu(MenuId::ViewItemContext, &context_menu, gpui::Bounds::new(event.position, Default::default()), menu_args.clone(), window, cx);
            }))
    }

    /// treeView.ts `TreeRenderer`: a theme icon as a codicon (`file` and `folder` take the resource's file icon), an
    /// icon path as an image, else the resource's file icon.
    /// `ITreeItemLabel.highlights` (UTF-16 offsets) on `list.filterMatchBackground` (views.css `.pane-body .monaco-tl-contents`).
    fn tree_item_label(&self, item: &TreeItem) -> gpui::StyledText {
        let label = item.label();
        let background = self.theme.color("list.filterMatchBackground").map(Into::into);
        let byte = |utf16: u64| {
            let mut units = 0;
            label.char_indices().find(|(_, char)| {
                let reached = units >= utf16;
                units += char.len_utf16() as u64;
                reached
            }).map_or(label.len(), |(byte, _)| byte)
        };
        let highlights: Vec<_> = item.dto["label"]["highlights"].as_array().into_iter().flatten().filter_map(|range| Some((byte(range[0].as_u64()?), byte(range[1].as_u64()?)))).filter(|(start, end)| start < end).map(|(start, end)| (start..end, gpui::HighlightStyle { background_color: background, ..Default::default() })).collect();
        gpui::StyledText::new(label).with_highlights(highlights)
    }

    fn tree_item_icon(&self, item: &TreeItem, foreground: gpui::Rgba) -> Option<Div> {
        let resource = item.dto["resourceUri"]["path"].as_str().map(std::path::PathBuf::from);
        match item.theme_icon() {
            Some("file" | "folder") | None if item.dto["icon"].is_null() => {
                let path = resource?;
                let language = self.languages.language_of(&path, "").to_string();
                self.file_icons.as_ref().and_then(|icons| icons.file_icon(&path, &language, self.theme.kind, 13., 22., foreground))
            }
            Some(icon) => Some(self.icon(icon, 16., 16., foreground)),
            None => {
                let key = if self.theme.kind == crate::theme::ThemeKind::Light || item.dto["iconDark"].is_null() { "icon" } else { "iconDark" };
                let path = item.dto[key]["path"].as_str()?.to_owned();
                Some(div().size(px(16.)).flex().items_center().justify_center().child(img(std::path::PathBuf::from(path)).size(px(16.))))
            }
        }
    }

    /// treeView.ts: a click selects the item, then runs its command (`resolveCommand` asks the host first when the
    /// item has none); an item without a command or a checkbox toggles (`expandOnlyOnTwistieClick`).
    fn tree_item_clicked(&mut self, id: &'static str, handle: &str, window: &mut Window, cx: &mut Context<Self>) {
        self.select_clicked_tree_item(id, handle, window, cx);
        let tree = &self.tree_views.trees[id];
        let item = &tree.items[handle];
        let has_command = !item.dto["command"].is_null();
        let resolves = tree.has_resolve && !item.resolved;
        if !has_command && item.checked().is_none() {
            self.toggle_tree_item(id, handle, cx);
        }
        if has_command || !resolves {
            self.run_tree_item_command(id, handle, window, cx);
            return;
        }
        let resolve = self.resolve_tree_item(id, handle, cx);
        let handle = handle.to_owned();
        cx.spawn_in(window, async move |workbench, cx| {
            resolve.await;
            let _ = workbench.update_in(cx, |workbench, window, cx| workbench.run_tree_item_command(id, &handle, window, cx));
        })
        .detach();
    }

    fn select_clicked_tree_item(&mut self, id: &'static str, handle: &str, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(focus) = self.tree_views.focus.get(id).cloned() {
            window.focus(&focus, cx);
        }
        let tree = self.tree_views.trees.get_mut(id).expect("a drawn row's tree");
        tree.selection = vec![handle.to_owned()];
        tree.focus = Some(handle.to_owned());
        self.host.send("ExtHostTreeViews", "$setSelectionAndFocus", vec![json!(id), json!([handle]), json!(handle)]);
        cx.notify();
    }

    fn run_tree_item_command(&mut self, id: &'static str, handle: &str, window: &mut Window, cx: &mut Context<Self>) {
        let Some(item) = self.tree_views.trees.get(id).and_then(|tree| tree.items.get(handle)) else { return };
        let command = item.dto["command"].clone();
        let Some(command_id) = command["id"].as_str() else { return };
        let args = command["arguments"].as_array().cloned().unwrap_or_default();
        drop(self.execute_command(command_id, args, window, cx));
    }

    /// views.ts `ResolvableTreeItem.resolve`: the host's tooltip and command fill in the ones the item lacks.
    fn resolve_tree_item(&mut self, id: &'static str, handle: &str, cx: &mut Context<Self>) -> Task<()> {
        let reply = self.host.call_cancellable("ExtHostTreeViews", "$resolve", vec![json!(id), json!(handle)]);
        let handle = handle.to_owned();
        cx.spawn(async move |workbench, cx| {
            let Ok(Ok(resolved)) = reply.await else { return };
            let _ = workbench.update(cx, |workbench, cx| {
                let Some(item) = workbench.tree_views.trees.get_mut(id).and_then(|tree| tree.items.get_mut(&handle)) else { return };
                for key in ["tooltip", "command"] {
                    if item.dto[key].is_null() && !resolved[key].is_null() {
                        item.dto[key] = resolved[key].clone();
                    }
                }
                item.resolved = true;
                cx.notify();
            });
        })
    }

    /// updatableHoverWidget.ts `update`: "Loading..." shows while the item resolves, then its hover replaces it.
    pub(super) fn resolve_tree_item_hover(&mut self, id: &'static str, handle: String, target: gpui::ElementId, window: &mut Window, cx: &mut Context<Self>) {
        let resolve = self.resolve_tree_item(id, &handle, cx);
        cx.spawn_in(window, async move |workbench, cx| {
            resolve.await;
            let _ = workbench.update_in(cx, |workbench, window, cx| {
                let Some(tree) = workbench.tree_views.trees.get(id) else { return };
                let Some(item) = tree.items.get(&handle).filter(|item| item.resolved) else { return };
                let content = workbench.tree_item_hover(id, tree, item);
                workbench.replace_shown_hover(&target, content, window);
                cx.notify();
            });
        })
        .detach();
    }

    /// treeView.ts `getHover`: the tooltip, else the label unless the item has a resource; an item the host
    /// resolves and has not yet asks for its tooltip when the hover shows.
    fn tree_item_hover(&self, id: &'static str, tree: &CustomTree, item: &TreeItem) -> Option<HoverContent> {
        let tooltip = &item.dto["tooltip"];
        if tree.has_resolve && !item.resolved && !tooltip.is_string() {
            return Some(HoverContent::TreeItem { view: id, handle: item.handle.clone() });
        }
        match tooltip {
            Value::Null if item.dto["resourceUri"].is_null() => Some(HoverContent::Text(item.label())),
            Value::Null => None,
            Value::String(text) if text.is_empty() => None,
            Value::String(text) => Some(HoverContent::Text(text.clone())),
            markdown => Some(HoverContent::Markdown(markdown.clone())),
        }
    }

    /// checkbox.ts `TreeItemCheckbox`: a 15px toggle (`size: 15`) in views.css's checkbox box.
    fn tree_item_checkbox(&self, id: &'static str, handle: &str, checked: bool, selected: bool, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let (background, border) = match selected {
            true => (self.color("checkbox.selectBackground"), self.color("checkbox.selectBorder")),
            false => (self.color("checkbox.background"), self.color("checkbox.border")),
        };
        let selector = format!("tree-checkbox-{handle}");
        let toggled = handle.to_owned();
        div()
            .id(gpui::SharedString::from(selector.clone()))
            .debug_selector(move || selector)
            .size(px(16.))
            .flex_none()
            .ml(px(3.))
            .mt(px(3.))
            .mb(px(3.))
            .mr(px(6.))
            .flex()
            .items_center()
            .justify_center()
            .rounded(px(3.))
            .border_1()
            .border_color(border)
            .bg(background)
            .when(checked, |checkbox| checkbox.child(self.icon("check", 13., 13., self.color("checkbox.foreground"))))
            .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                cx.stop_propagation();
                workbench.tree_checkbox_clicked(id, &toggled, window, cx);
            }))
    }

    /// checkbox.ts `setCheckbox` then mainThreadTreeViews.ts `$changeCheckboxState`; the list still selects the row,
    /// while `onDidOpen` skips the command of a click on the checkbox.
    fn tree_checkbox_clicked(&mut self, id: &'static str, handle: &str, window: &mut Window, cx: &mut Context<Self>) {
        let tree = self.tree_views.trees.get_mut(id).expect("a drawn checkbox's tree");
        let checked = tree.items[handle].checked() != Some(true);
        let changed = tree.set_checked(handle, checked);
        self.send_checkbox_states(id, &changed);
        self.select_clicked_tree_item(id, handle, window, cx);
    }

    fn send_checkbox_states(&self, id: &str, handles: &[String]) {
        let tree = &self.tree_views.trees[id];
        let updates: Vec<Value> = handles.iter().map(|handle| json!({ "treeItemHandle": handle, "newState": tree.items[handle].checked() == Some(true) })).collect();
        self.host.send("ExtHostTreeViews", "$changeCheckboxState", vec![json!(id), json!(updates)]);
    }

    /// `onDragStart`: the selection when it holds the item, else the item, from a view whose extension handles drags
    /// or drops (`getDragURI`); the drag image shows `getDragLabel`.
    fn tree_items_drag(&self, id: &'static str, tree: &CustomTree, item: &TreeItem) -> Option<DraggedTreeItems> {
        let controller = tree.drag_and_drop.as_ref()?;
        let handles = match tree.selection.contains(&item.handle) {
            true => tree.selection.clone(),
            false => vec![item.handle.clone()],
        };
        let label = match handles.len() {
            1 => item.label(),
            count => count.to_string(),
        };
        let colors = (self.color("list.activeSelectionBackground"), self.foreground_or("list.activeSelectionForeground"), self.theme.color("list.focusOutline").or(self.theme.color("focusBorder")));
        Some(DraggedTreeItems { view: id, handles, drag_mime_types: controller.drag_mime_types.clone(), uuid: crate::debug::generate_uuid(), label, colors })
    }

    /// `addExtensionProvidedTransferTypes`: the view's previous drag is released, and an extension that handles
    /// drags is asked for this one's data transfer (`$handleDrag`).
    fn start_tree_drag(&mut self, dragged: &DraggedTreeItems, cx: &mut Context<Self>) {
        if let Some(previous) = self.tree_views.drag_operations.insert(dragged.view, dragged.uuid.clone()) {
            self.tree_views.drag_transfers.remove(&previous);
            self.host.send("ExtHostTreeViews", "$releaseDragOperation", vec![json!(previous)]);
        }
        if !self.tree_views.trees.get(dragged.view).and_then(|tree| tree.drag_and_drop.as_ref()).is_some_and(|controller| controller.has_handle_drag) {
            return;
        }
        let reply = self.host.call_cancellable("ExtHostTreeViews", "$handleDrag", vec![json!(dragged.view), json!(dragged.handles), json!(dragged.uuid)]);
        let transfer = cx.background_executor().spawn(async move { reply.await.ok().and_then(Result::ok).unwrap_or_default() }).shared();
        self.tree_views.drag_transfers.insert(dragged.uuid.clone(), transfer);
    }

    /// `CustomTreeViewDragAndDrop.drop`: the drag's types the view takes (its own tree's with the source items),
    /// then the host's data transfer of the drag, go to `$handleDrop` with the target item, if any.
    fn drop_tree_items(&mut self, id: &'static str, target: Option<String>, dragged: &DraggedTreeItems, cx: &mut Context<Self>) {
        self.tree_views.drag_operations.remove(dragged.view);
        let Some(controller) = self.tree_views.trees.get(id).and_then(|tree| tree.drag_and_drop.clone()) else { return };
        let own = tree_mime_type(id);
        let mut items = Vec::new();
        let mut source = None;
        for mime in dragged.mime_types() {
            let value = if mime == own {
                source = Some(dragged);
                json!({ "id": dragged.view, "itemHandles": dragged.handles }).to_string()
            } else if controller.drop_mime_types.contains(&mime) {
                String::new()
            } else {
                continue;
            };
            items.push(json!([mime, { "id": crate::debug::generate_uuid(), "asString": value }]));
        }
        let request = self.tree_views.drop_requests;
        self.tree_views.drop_requests += 1;
        let transfer = self.tree_views.drag_transfers.remove(&dragged.uuid);
        let (source_view, source_handles) = (source.map(|source| source.view), source.map(|source| source.handles.clone()));
        let uuid = dragged.uuid.clone();
        cx.spawn(async move |workbench, cx| {
            if let Some(transfer) = transfer {
                items.extend(transfer.await["items"].as_array().cloned().unwrap_or_default());
            }
            // The main thread passes `CancellationToken.None` mid-arguments, which reaches the host as plain data.
            let args = vec![json!(id), json!(request), json!({ "items": items }), json!(target), json!({ "isCancellationRequested": false }), json!(uuid), json!(source_view), json!(source_handles)];
            let _ = workbench.update(cx, |workbench, _| workbench.host.send("ExtHostTreeViews", "$handleDrop", args));
        })
        .detach();
    }

    fn toggle_tree_item(&mut self, id: &'static str, handle: &str, cx: &mut Context<Self>) {
        let tree = self.tree_views.trees.get_mut(id).expect("a drawn row's tree");
        let expanded = !tree.expanded.remove(handle);
        if expanded {
            tree.expanded.insert(handle.to_owned());
        }
        self.host.send("ExtHostTreeViews", "$setExpanded", vec![json!(id), json!(handle), json!(expanded)]);
        self.fetch_missing_children(cx);
        cx.notify();
    }
}