Skip to content

Visual Studio Code, rebuilt in Rust

Rust
249 KB
Raw Blame
//! The editor part with open files: the connected tab strip (connectedEditorTabs.css), the breadcrumbs,
//! and the code editor's view parts (margin, current line, word highlights, indent guides, text, cursor,
//! decorationsOverviewRuler.ts). Sizes are the reference's CSS pixels with editor.fontSize 12 and lineHeight 18.

use std::cell::Cell;
use std::collections::HashMap;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::rc::Rc;

use std::time::{Duration, Instant};

use gpui::{
    Axis, Bounds, Context, DispatchPhase, Div, DragMoveEvent, ElementInputHandler, ExternalPaths, Hitbox, HitboxBehavior, MouseButton, MouseDownEvent, MouseMoveEvent,
    MouseUpEvent, Pixels, Point,
    PathBuilder, Rgba, ScrollDelta, ScrollWheelEvent, Stateful, StyledText, Task, Window, canvas, div, fill, font, point, prelude::*, px, rgb, size,
};

pub(super) mod diff_editor_view;
pub(super) mod diff_gutter;
pub(super) mod drag_and_drop;
pub(super) mod injected_text_view;
pub(super) mod merge_editor_view;
pub(super) mod multi_diff_editor_view;
mod comment_glyph;
pub(super) mod cursor_blink;
pub(super) mod quick_diff;
pub(super) mod quick_diff_widget;
pub(super) mod sticky_scroll_view;
pub(super) mod tab_scroll;
pub(super) mod text_decorations;
pub(super) mod unchanged_regions_view;

use files::encoding::SUPPORTED_ENCODINGS;
use serde_json::{Value, json};

use super::Workbench;
use super::minimap_view::minimap_info;
use super::search_editor_view::SEARCH_EDITOR_SCHEME;
use super::terminal_editor::TERMINAL_EDITOR_SCHEME;
use super::webview_panels::WEBVIEW_PANEL_SCHEME;
use super::model_events::Cursor;
use crate::brackets::BracketRange;
use crate::editor::minimap::MinimapLayoutInfo;
use crate::editor::{
    HORIZONTAL_SCROLLBAR_HEIGHT, Indentation, LINE_HEIGHT, OpenEditor, Position, Reveal, Scrollbar, Selection, VERTICAL_SCROLLBAR_WIDTH, VerticalReveal, Viewport, column_at_visible, commands,
    expand_tabs, line_overflow, show_more_width, column_x,
};
use crate::editor::folding::FoldDecoration;
use crate::editor::whitespace::whitespace_marks;
use crate::multi_diff_editor::MULTI_DIFF_EDITOR_SCHEME;
use crate::theme::ThemeKind;
use crate::workbench::editor_options::{COLUMN_SELECTION, CURSOR_STYLE, DOUBLE_CLICK_SELECTS_BLOCK, GUIDES_BRACKET_PAIRS, GUIDES_BRACKET_PAIRS_HORIZONTAL, GUIDES_HIGHLIGHT_ACTIVE_BRACKET_PAIR, GUIDES_HIGHLIGHT_ACTIVE_INDENTATION, GUIDES_INDENTATION, MOUSE_WHEEL_ZOOM, MULTI_CURSOR_MODIFIER, OVERTYPE_CURSOR_STYLE, RENDER_CONTROL_CHARACTERS, RENDER_WHITESPACE, ROUNDED_SELECTION};

pub(super) const EDITOR_FONT: &str = "Menlo";
/// `editor.fontSize` at zoom level 0.
pub(super) const EDITOR_FONT_SIZE: f32 = 12.;
/// lineDecorationsWidth 10 plus 16 for the folding controls (editorOptions.ts layout).
const DECORATIONS_WIDTH: f32 = 26.;
/// The workbench text editor sets lineNumbersMinChars to 3 (textEditor.ts).
const LINE_NUMBERS_MIN_CHARS: usize = 3;
const OVERVIEW_RULER_WIDTH: f32 = 14.;
const TAB_STRIP_HEIGHT: f32 = 32.;
/// editorTabsControl.ts `EDITOR_TAB_HEIGHT.normal`: the single tab's title, which has no modern UI tab row.
const SINGLE_TAB_TITLE_HEIGHT: f32 = 35.;
/// The sticky tabs' own bar above the strip (`pinnedTabsOnSeparateRow`), measured in the reference.
const UPPER_TAB_BAR_HEIGHT: f32 = 30.;
/// multiEditorTabsControl.ts `createTab`: each tab's ActionBar with its close action, one tab stop per tab.
pub(super) const TAB_ACTIONS: &str = "editor-tab-actions";
/// The group title's editor actions toolbar (editorTabsControl.ts `createEditorActionsToolBar`).
pub(super) const EDITOR_ACTIONS: &str = "editor-actions";

#[derive(Clone, Copy, PartialEq)]
enum TabRow {
    /// The strip connected to the editor; its first tab meets the part's rounded corner. The active tab's fill is
    /// cut where the bar scrolled it out (`clip`), with no left border at the edge of sticky tabs (`after_sticky`).
    Main { first: bool, clip: tab_scroll::TabClip, after_sticky: bool },
    /// The sticky tabs' bar above it (`pinnedTabsOnSeparateRow`).
    Upper,
}
pub(super) const BREADCRUMBS_HEIGHT: f32 = 22.;
/// scrollableElement.ts `HIDE_TIMEOUT`; scrollbars.css fades in over 100ms and out over 800ms.
const SCROLLBAR_HIDE_TIMEOUT: Duration = Duration::from_millis(500);
const SCROLLBAR_FADE_IN: Duration = Duration::from_millis(100);
const SCROLLBAR_FADE_OUT: Duration = Duration::from_millis(800);
const SCROLL_SHADOW_HEIGHT: f32 = 6.;
const FOLD_CONTROLS_FADE: Duration = Duration::from_millis(500);

impl Workbench {
    /// `secondary`: the drawn secondary side when the active editor is a side by side editor; `preferences`: the drawn
    /// Settings or Keyboard Shortcuts editor when the active editor is one.
    pub(super) fn text_editor_part(&self, secondary: Option<gpui::AnyElement>, preferences: Option<gpui::AnyElement>, window: &mut Window, cx: &mut Context<Self>) -> Div {
        let editor = self.editors.pane_editor().expect("text editor part is drawn only with an editor open");
        if !self.editor_groups.drawing_inactive {
            self.schedule_unusual_line_terminators_check(editor, window, cx);
            self.forget_action_bar_items(TAB_ACTIONS);
            self.forget_action_bar_items(EDITOR_ACTIONS);
        }
        // A compact part has NoEditorTabsControl as `showTabs: none` has.
        let show_tabs = if self.drawing_compact_part() { "none" } else { self.editor_show_tabs() };
        let breadcrumbs = self.setting("breadcrumbs.enabled") != json!(false) && self.editor_has_breadcrumbs(editor);
        div()
            .flex_1()
            .min_w_0()
            .min_h_0()
            .relative()
            .flex()
            .flex_col()
            .map(|part| match show_tabs {
                "multiple" => part.child(self.tab_strip(window, cx)),
                "single" => part.child(self.single_editor_tab_title(self.active_text_editor_control().unwrap_or(editor), breadcrumbs, window, cx)),
                _ => part,
            })
            .map(|part| match editor.document().scheme.as_str() {
                // The playground's focused snippet is the active editor; the page draws it with the others.
                _ if self.playground_active() => part.child(self.playground_body(window, cx)),
                // A webview panel's resource has no file system provider, a custom editor's has.
                WEBVIEW_PANEL_SCHEME if self.custom_editor_resource(&editor.document().path).is_none() => part,
                _ if self.active_notebook_resource().is_some_and(|(scheme, _)| scheme == "untitled") => part,
                super::modal_editor_group::PREFERENCES_EDITOR_SCHEME => part,
                super::extension_editor::EXTENSION_EDITOR_SCHEME => part.child(self.extension_editor_body(&editor.document().path, cx)),
                super::welcome_page::WALKTHROUGH_SCHEME => part.child(self.walkthrough_editor_body(&editor.document().path, window, cx)),
                super::disassembly_view::DISASSEMBLY_SCHEME => part.child(self.disassembly_editor_body(cx)),
                // searchEditor.ts draws its query widget where a text editor has its breadcrumbs.
                SEARCH_EDITOR_SCHEME if editor.document().open_error.is_some() => part,
                SEARCH_EDITOR_SCHEME => part.child(self.search_editor_query(window, cx)),
                _ if self.editors.active_multi_diff().is_some() => part.child(self.multi_diff_editor_body(window, cx)),
                // The single tab draws them in its title; a compact part has none.
                _ if !breadcrumbs || show_tabs == "single" || self.drawing_compact_part() => part,
                _ => part.child(self.breadcrumbs(self.active_text_editor_control().unwrap_or(editor), cx).opacity(self.unfocused_editor_opacity(window))),
            })
            .map(|part| match self.editors.active_diff() {
                Some(crate::diff_editor::DiffInput { custom: Some(custom), .. }) => part.child(self.custom_editor_diff_body(custom.inline, cx)),
                Some(diff) => part.child(self.diff_editor_body(diff, diff.modified_editor.as_ref().unwrap_or(editor), window, cx)),
                None if self.playground_active() => part,
                None if editor.document().scheme == super::modal_editor_group::PREFERENCES_EDITOR_SCHEME => part.children(preferences),
                None if matches!(editor.document().scheme.as_str(), super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | super::disassembly_view::DISASSEMBLY_SCHEME) => part,
                None if self.shows_webview(editor) => part.child(self.webview_editor_body(editor)),
                None if self.editors.active_tab().is_some_and(|tab| tab.document().scheme == crate::notebook::NOTEBOOK_EDITOR_SCHEME) => part.child(self.notebook_editor_body(window, cx)),
                None if self.editors.active_multi_diff().is_some() => part,
                None if editor.document().scheme == TERMINAL_EDITOR_SCHEME => part.child(self.terminal_editor_body(editor, window, cx)),
                None if editor.document().open_error.is_some() => part.child(self.editor_placeholder(cx)),
                None => match (self.editors.active_merge(), secondary) {
                    (Some(merge), _) => part.child(self.merge_editor_body(merge, window, cx)),
                    (None, Some(secondary)) => part.child(self.side_by_side_body(secondary, editor, window, cx)),
                    // The comment editor in it has the focus: it drew before the part, unfocused.
                    (None, None) if self.editors.active().is_some_and(|active| !std::ptr::eq(active, editor)) => part.children(self.unicode_banner(editor, cx)).children(self.code_editor_area(editor, window, cx)),
                    (None, None) => part.children(self.unicode_banner(editor, cx)).child(self.text_area(editor, window, cx).opacity(self.unfocused_editor_opacity(window))),
                },
            })
    }

    /// breadcrumbsControl.ts `update`: no breadcrumbs for a resource without a file system provider (untitled, a
    /// terminal), nor where another editor draws its own row (search editor, output).
    fn editor_has_breadcrumbs(&self, editor: &OpenEditor) -> bool {
        let document = editor.document();
        let scheme = document.scheme.as_str();
        !self.playground_active()
            && !(scheme == WEBVIEW_PANEL_SCHEME && self.custom_editor_resource(&document.path).is_none())
            && !self.active_notebook_resource().is_some_and(|(scheme, _)| scheme == "untitled")
            && !matches!(scheme, super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | super::disassembly_view::DISASSEMBLY_SCHEME | SEARCH_EDITOR_SCHEME | crate::output::OUTPUT_SCHEME | "untitled" | TERMINAL_EDITOR_SCHEME)
            && self.editors.active_multi_diff().is_none()
    }

    /// The active tab reaches into the part's top border, which Chrome still draws over it. A compact editor paints
    /// its right and bottom strokes, and its left one at the window's left edge (editorBorder.css).
    pub(super) fn part_top_border(&self) -> Div {
        if self.compact_density() {
            let outer_left = self.part_at_left_edge(super::layout::Part::Editor);
            return self.compact_card_strokes("editor.border", [false, true, true, outer_left], outer_left);
        }
        div().absolute().inset(px(-1.)).border_1().rounded(px(8.)).border_color(self.editor_part_border())
    }

    /// editorBorder.css `.floating-panels .part.editor`; connectedEditorTabs.css takes `modernPanel.border` in high contrast.
    pub(super) fn editor_part_border(&self) -> Rgba {
        if self.theme.kind.is_high_contrast() {
            return self.color("modernPanel.border");
        }
        let theme = &self.theme;
        theme.color("editor.border").or(theme.color("surface.border")).or(theme.color("widget.border")).unwrap_or(gpui::transparent_black().into())
    }

    /// One strip behind every tab; the active tab is an editor-colored fill whose bottom shoulders curve
    /// into the strip, so the active tab and the editor below read as one surface.
    fn tab_strip(&self, window: &Window, cx: &mut Context<Self>) -> Div {
        // multieditortabscontrol.css: .editor-actions is cursor default, its action items pointer (actionbar.css).
        // Centered above the strip's bottom border, as the tabs are.
        let actions = self.editor_title_toolbar(window, cx).map(|actions| actions.cursor_default().h(px(TAB_STRIP_HEIGHT - 1.)).px(px(4.)).gap(px(4.)));
        // The line under the strip (tabs-border-bottom) runs below the shoulders; the active fill covers it. Pills
        // float without it (modernUI tabs.css `--modern-ui-editor-tabs-border: transparent`).
        let connected = self.connected_editor_tabs();
        let bottom_line = connected.then(|| div().absolute().bottom_0().left_0().right_0().h(px(1.)).bg(self.connected_tab_border()));
        // multiRowEditorTabsControl.ts: with `workbench.editor.pinnedTabsOnSeparateRow` the sticky tabs get a bar of
        // their own above the others while the group has both (`two-tab-bars`); only the lower bar has the actions.
        let count = self.editors.editors.len();
        let sticky_count = self.editors.sticky_count();
        let two_bars = self.two_tab_bars();
        let lower_tabs = if two_bars { sticky_count..count } else { 0..count };
        // editortabscontrol.css: the whole title, tabs and their close buttons included, is cursor pointer.
        let lower = div()
            .debug_selector(|| "editor-tab-strip".into())
            .relative()
            .h(px(TAB_STRIP_HEIGHT))
            .flex_none()
            .cursor_pointer()
            .flex()
            .map(|lower| match connected {
                true => lower.bg(self.tab_strip_background()),
                // tabs.css: the pills' strip is editorGroupHeader.tabsBackground over the editor's, 2px in from the start.
                false => lower.bg(self.pill_tab_strip_background()).pl(px(2.)),
            })
            .when(!two_bars, |lower| self.clip_to_part_corners(lower))
            .children(bottom_line)
            .child(self.tab_bar_tabs(lower_tabs, false, TAB_STRIP_HEIGHT, window, cx))
            .children(actions);
        if !two_bars {
            return lower;
        }
        // connectedEditorTabs.css `.connected-tab-upper-bar`: 2px above and before its tabs, none of them connected.
        // tabs.css: pills keep both bars 32px high and shift their fills instead.
        let upper = div().flex_none().cursor_pointer().pl(px(2.)).flex();
        let upper = match connected {
            true => upper.h(px(UPPER_TAB_BAR_HEIGHT)).pt(px(2.)).bg(self.tab_strip_background()).child(self.tab_bar_tabs(0..sticky_count, true, UPPER_TAB_BAR_HEIGHT - 2., window, cx)),
            false => upper.h(px(TAB_STRIP_HEIGHT)).bg(self.pill_tab_strip_background()).child(self.tab_bar_tabs(0..sticky_count, true, TAB_STRIP_HEIGHT, window, cx)),
        };
        div().flex_none().flex().flex_col().child(self.clip_to_part_corners(upper)).child(lower)
    }

    /// The editor actions toolbar of a group title (`MenuId.EditorTitle`, Split Editor, lock, more), drawn only with
    /// `workbench.editor.editorActionsLocation: default` and tabs (editorTabsControl.ts `editorActionsEnabled`). The
    /// active group's is a tab stop.
    fn editor_title_toolbar(&self, window: &Window, cx: &mut Context<Self>) -> Option<Div> {
        if self.editor_actions_location() != "default" {
            return None;
        }
        let icon_color = self.color("icon.foreground");
        let bar = (!self.editor_groups.drawing_inactive).then_some(EDITOR_ACTIONS);
        let more = self.title_action(bar, "more", self.editor_title_more_button(icon_color, false, cx), cx);
        let toolbar = div().flex_none().flex().items_center().children(self.editor_title_primary_actions(bar, icon_color, window, cx)).child(more);
        Some(match bar {
            Some(bar) => self.action_bar(bar, false, toolbar, cx),
            None => toolbar,
        })
    }

    /// An editor title action, an item of `bar` when the toolbar is one.
    pub(super) fn title_action(&self, bar: Option<&'static str>, key: &str, action: gpui::Stateful<Div>, cx: &gpui::App) -> gpui::AnyElement {
        match bar {
            Some(bar) => self.action_bar_item(bar, key, action, cx).into_any_element(),
            None => action.into_any_element(),
        }
    }

    /// The editor title toolbar's primary actions; the title bar shows them in `color` when the editor actions are there.
    pub(super) fn editor_title_primary_actions(&self, bar: Option<&'static str>, color: gpui::Rgba, window: &Window, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
        let mut actions = Vec::new();
        // searchEditor.contribution.ts: Rerun Search sits in the editor title of a search editor.
        if self.active_search_editor().is_some() {
            let rerun = self.icon("refresh", 22., 16., color).id("rerun-search").cursor_pointer().on_click(cx.listener(|workbench, _, window, cx| {
                workbench.execute_command("rerunSearchEditorSearch", Vec::new(), window, cx);
            }));
            actions.push(self.title_action(bar, "rerun", rerun, cx));
        }
        // A group that is not active shows only the overflow menu.
        if self.editor_groups.drawing_inactive {
            return actions;
        }
        actions.extend(self.editor_title_actions(bar, window, cx));
        let split = self.icon("split-horizontal", 22., 16., color).id("split-editor").cursor_pointer().on_click(cx.listener(|workbench, _, window, cx| {
            workbench.execute_command("workbench.action.splitEditor", Vec::new(), window, cx);
        }));
        actions.push(self.title_action(bar, "split", split, cx));
        actions.extend(self.lock_group_action(self.editors.id, cx).map(|lock| self.title_action(bar, "lock", lock, cx)));
        actions.extend(self.editor_title_close_action(color, cx).map(|close| self.title_action(bar, "close", close, cx)));
        actions
    }

    /// editor.ts `editorActionsLocation`: `default`, `titleBar` or `hidden`.
    pub(super) fn editor_actions_location(&self) -> &'static str {
        match self.setting("workbench.editor.editorActionsLocation").as_str() {
            Some("titleBar") => "titleBar",
            Some("hidden") => "hidden",
            _ => "default",
        }
    }

    /// titlebarPart.ts `editorActionsEnabled`: the editor actions are in the title bar at `titleBar`, and at `default`
    /// while the drawn group's part has no tabs.
    pub(super) fn title_bar_has_editor_actions(&self) -> bool {
        match self.editor_actions_location() {
            "titleBar" => true,
            "default" => self.editor_show_tabs() == "none",
            _ => false,
        }
    }

    /// editor.contribution.ts: without tabs (`!editorTabsVisible`) the title closes the active editor, `close-dirty`
    /// while it is dirty, and unpins a sticky one (`pinned`, `pinned-dirty`).
    fn editor_title_close_action(&self, icon_color: gpui::Rgba, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
        if self.editor_show_tabs() == "multiple" || self.drawing_compact_part() {
            return None;
        }
        let index = self.editors.active_index()?;
        let sticky = index < self.editors.sticky_count();
        let (codicon, command) = match (sticky, self.tab_shows_dirty(index)) {
            (false, false) => ("close", "workbench.action.closeActiveEditor"),
            (false, true) => ("close-dirty", "workbench.action.closeActiveEditor"),
            (true, false) => ("pinned", "workbench.action.unpinEditor"),
            (true, true) => ("pinned-dirty", "workbench.action.unpinEditor"),
        };
        Some(self.icon(codicon, 22., 16., icon_color).id("close-editor-title").debug_selector(move || format!("editor-title-{codicon}")).cursor_pointer().on_click(cx.listener(move |workbench, _, window, cx| {
            workbench.execute_command(command, Vec::new(), window, cx);
        })))
    }

    /// singleEditorTabsControl.ts with `workbench.editor.showTabs: single`: the active editor's label, its breadcrumbs
    /// inline while the group is active (else its description), and the actions at half opacity in an inactive group.
    fn single_editor_tab_title(&self, editor: &OpenEditor, breadcrumbs: bool, window: &Window, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let active_group = !self.editor_groups.drawing_inactive;
        let title = div().id("single-tab-title").debug_selector(|| "single-tab-title".into()).h(px(SINGLE_TAB_TITLE_HEIGHT)).flex_none().flex().bg(self.color("editorGroupHeader.noTabsBackground"));
        let Some(index) = self.editors.active_index() else { return title };
        let tab = &self.editors.editors[index];
        let foreground = match active_group {
            true => self.foreground_or("tab.activeForeground"),
            false => self.foreground_or("tab.unfocusedActiveForeground"),
        };
        let breadcrumbs = (breadcrumbs && active_group).then(|| self.inline_breadcrumbs(editor, cx));
        let description = breadcrumbs.is_none().then(|| self.single_tab_description(tab)).flatten();
        let icon = match matches!(tab.document().scheme.as_str(), crate::notebook::NOTEBOOK_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME) {
            true => self.document_icon(tab, SINGLE_TAB_TITLE_HEIGHT, foreground),
            false => self.document_icon(self.editors.tab_model(index), SINGLE_TAB_TITLE_HEIGHT, foreground),
        };
        let opacity = if self.theme.kind == ThemeKind::Light { 0.95 } else { 0.7 };
        // singleeditortabscontrol.css: the label starts 20px in.
        let label = div()
            .id("single-tab-label")
            .flex_none()
            .max_w_full()
            .pl(px(20.))
            .flex()
            .items_center()
            .whitespace_nowrap()
            .text_color(foreground)
            .children(icon)
            .child(div().ml(px(6.)).when(tab.preview, |name| name.italic()).child(self.editor_name(tab)))
            .children(description.map(|description| super::icon_label::label_description().opacity(opacity).child(description)))
            .child(self.tab_hover(index))
            .on_click(cx.listener(|workbench, event: &gpui::ClickEvent, window, cx| {
                if event.click_count() == 1 {
                    workbench.execute_command("workbench.action.quickOpen", Vec::new(), window, cx);
                }
            }));
        title
            .cursor_pointer()
            .child(div().flex_1().min_w_0().h_full().flex().items_center().overflow_hidden().child(label).children(breadcrumbs))
            .children(self.editor_title_toolbar(window, cx).map(|actions| actions.cursor_default().pr(px(8.)).gap(px(4.)).when(!active_group, |actions| actions.opacity(0.5))))
            .on_click(cx.listener(|workbench, event: &gpui::ClickEvent, window, cx| {
                if event.click_count() == 2 {
                    workbench.execute_command("workbench.action.keepEditor", Vec::new(), window, cx);
                }
            }))
            .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| workbench.show_tab_context_menu(index, super::editor_menus::point_anchor(event.position), window, cx)))
            .on_mouse_up(MouseButton::Middle, cx.listener(move |workbench, _: &gpui::MouseUpEvent, window, cx| {
                if !workbench.prevents_mouse_close(&workbench.editors.editors[index]) {
                    drop(workbench.close_editors(vec![index], window, cx));
                }
            }))
    }

    /// singleEditorTabsControl.ts `getVerbosity` over `workbench.editor.labelFormat`: the folder of a file, short as
    /// its name, medium as the workspace relative path, long as the whole path; an untitled editor's path.
    fn single_tab_description(&self, tab: &OpenEditor) -> Option<String> {
        if tab.document().scheme != "file" || self.editors.diffs.contains_key(&tab.model_id) {
            return self.untitled_description(tab);
        }
        let document = tab.document();
        let parent = document.path.parent()?;
        let folders = self.workspace_folders();
        let description = match self.setting("workbench.editor.labelFormat").as_str() {
            Some("short") => parent.file_name()?.to_string_lossy().into_owned(),
            Some("long") => self.tildify(parent),
            _ => match folders.iter().find(|folder| parent.starts_with(folder)) {
                Some(folder) => {
                    let relative = parent.strip_prefix(folder).ok()?.to_string_lossy().into_owned();
                    match (folders.len() > 1, relative.is_empty()) {
                        (true, true) => folder.file_name()?.to_string_lossy().into_owned(),
                        (true, false) => format!("{} \u{2022} {relative}", folder.file_name()?.to_string_lossy()),
                        (false, _) => relative,
                    }
                }
                None => self.tildify(parent),
            },
        };
        Some(description).filter(|description| !description.is_empty())
    }

    /// floatingPanels.css: the floating part's `.content` clips the strip to its 8px corners (overflow hidden). GPUI
    /// clips to rectangles only, so the strip rounds the corners it reaches itself.
    fn clip_to_part_corners(&self, strip: Div) -> Div {
        if self.editor_groups.part != super::editor_groups::MAIN_PART || self.compact_density() {
            return strip;
        }
        let [inner_left, inner_right] = self.editor_groups.drawing_inner_corners;
        strip.when(!inner_left, |strip| strip.rounded_tl(px(PART_CONTENT_RADIUS))).when(!inner_right, |strip| strip.rounded_tr(px(PART_CONTENT_RADIUS)))
    }

    /// The `navigation` group of `MenuId.EditorTitle` by order: the diff editor's built-in actions and the
    /// extensions' `editor/title` items, run with the active editor's resource.
    fn editor_title_actions(&self, bar: Option<&'static str>, window: &Window, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
        let mut items = self.diff_title_actions(cx);
        let mut context = self.key_context(window);
        // A notebook's cell editors keep `editorLangId` in their own scoped context, which the title does not see.
        if self.active_notebook_editor().is_some() {
            context.remove("editorLangId");
        }
        // A focused comment editor's or peek preview's language is in its own scoped context; the title sees the pane's editor.
        if let Some(editor) = self.editors.pane_editor().filter(|_| self.editors.focused_zone_editor().is_some()) {
            context.insert("editorLangId".into(), json!(editor.document().language_id));
        }
        items.extend(self.multi_diff_title_actions(&context, cx));
        items.extend(self.merge_title_actions(cx));
        // Keyed by their place: actionbar.ts keeps the focused item's index when the actions change.
        let mut actions: Vec<_> = items.into_iter().enumerate().map(|(key, (order, action))| (order, self.title_action(bar, &key.to_string(), action, cx))).collect();
        actions.extend(self.terminal_editor_title_action(bar, cx).map(|action| (0., action)));
        let resource = self.editors.pane_editor().map(|editor| editor.document().uri()).into_iter().collect::<Vec<_>>();
        let foreground = self.color("icon.foreground");
        // preferences.contribution.ts Open Settings (UI) (order 1) on a user, workspace or folder settings file outside a
        // diff editor, and editor.contribution.ts Toggle Layout of a side by side editor, left of Split Editor.
        let settings_ui = self.editors.pane_editor().filter(|_| self.editors.active_diff().is_none()).and_then(|editor| {
            let document = editor.document();
            match self.is_user_settings_file(&document.path) {
                true => Some(("workbench.action.openSettings2", Vec::new())),
                false => self.open_workspace_settings_ui_action(&document.scheme, &document.path),
            }
        });
        let toggle_layout = self.editors.side_group().is_some().then(|| ("workbench.action.toggleSplitEditorInGroupLayout", Vec::new()));
        for (order, icon, title, action) in [(1., "go-to-file", "Open Settings (UI)", settings_ui), (f64::MAX, "editor-layout", "Toggle Layout", toggle_layout)] {
            if let Some((command, args)) = action {
                let button = self.icon(icon, 22., 16., foreground).id(title).debug_selector(move || command.into()).cursor_pointer().on_click(cx.listener(move |workbench, _, window, cx| drop(workbench.execute_command(command, args.clone(), window, cx))));
                actions.push((order, self.title_action(bar, &actions.len().to_string(), button, cx)));
            }
        }
        let mut navigation: Vec<_> = self.menus.iter().filter(|item| item.menu == crate::menus::MenuId::EditorTitle && item.group == "navigation" && item.when.as_ref().is_none_or(|when| when.evaluate(&context))).collect();
        // `MenuInfo.compareMenuItems`: equal orders sort by title (the stable sort by order below keeps it).
        navigation.sort_by(|a, b| crate::command_palette::locale_compare(&a.title, &b.title));
        for item in navigation {
            match &item.entry {
                crate::menus::Entry::Command { id, toggled, .. } => {
                    // menuEntryActionViewItem.ts: a checked item shows its toggled title and icon, on `actionBar.toggledBackground`.
                    let toggled = toggled.as_ref().filter(|toggled| toggled.condition.evaluate(&context));
                    let title = toggled.and_then(|toggled| toggled.title.clone()).unwrap_or_else(|| item.title.clone());
                    let toggled_icon = toggled.and_then(|toggled| toggled.icon.clone()).map(crate::menus::CommandIcon::Codicon);
                    let icon = toggled_icon.as_ref().or(self.command_icons.get(id));
                    let toggled_background = self.theme.color("actionBar.toggledBackground").unwrap_or(self.color("inputOption.activeBackground"));
                    let button = self.command_button_with_icon(id, icon, title, resource.clone(), foreground, cx).when(toggled.is_some(), |button| button.bg(toggled_background));
                    actions.push((item.order, self.title_action(bar, &actions.len().to_string(), button, cx)));
                }
                // layoutActions.ts: the only workbench submenu here, with its `Codicon.gear` icon.
                crate::menus::Entry::Submenu { submenu: submenu @ crate::menus::MenuId::NotebookEditorLayoutConfigure, .. } => {
                    let button = self.submenu_button(*submenu, Some(&crate::menus::CommandIcon::Codicon("gear".into())), item.title.clone(), context.clone(), Vec::new(), foreground, cx);
                    actions.push((item.order, self.title_action(bar, &actions.len().to_string(), button, cx)));
                }
                crate::menus::Entry::Submenu { submenu: submenu @ crate::menus::MenuId::EditorTitleRun, .. } => {
                    if let Some(button) = self.split_button(*submenu, item.title.clone(), &context, resource.clone(), foreground, cx) {
                        actions.push((item.order, self.title_action(bar, &actions.len().to_string(), button, cx)));
                    }
                }
                crate::menus::Entry::Submenu { .. } => {}
            }
        }
        actions.sort_by(|a, b| a.0.total_cmp(&b.0));
        actions.into_iter().map(|(_, element)| element).collect()
    }

    /// `--modern-ui-connected-tab-strip-background` (connectedEditorTabs.ts): the connected tabs background,
    /// else the tabs background, else the editor's.
    pub(super) fn tab_strip_background(&self) -> Rgba {
        ["editorGroupHeader.connectedTabsBackground", "editorGroupHeader.tabsBackground", "editor.background"]
            .into_iter()
            .find_map(|key| self.theme.color(key))
            .expect("editor.background has a registry default")
    }

    /// modernUI.contribution.ts `useConnectedEditorTabs`: `workbench.experimental.modernUIEditorTabStyle` is `connected`,
    /// else the tabs are tabs.css pills.
    pub(super) fn connected_editor_tabs(&self) -> bool {
        self.setting("workbench.experimental.modernUIEditorTabStyle") == json!("connected")
    }

    /// multiRowEditorTabsControl.ts `two-tab-bars`: `workbench.editor.pinnedTabsOnSeparateRow` with both sticky and
    /// other tabs in the group.
    fn two_tab_bars(&self) -> bool {
        let sticky_count = self.editors.sticky_count();
        sticky_count > 0 && sticky_count < self.editors.editors.len() && self.setting("workbench.editor.pinnedTabsOnSeparateRow") == json!(true)
    }

    fn pill_tab_strip_background(&self) -> Rgba {
        let editor = self.color("editor.background");
        self.theme.color("editorGroupHeader.tabsBackground").map_or(editor, |tabs| crate::theme::make_opaque(tabs, editor))
    }

    /// `--modern-ui-connected-tab-border`: a customized tab border, else the header's tabs border; in high contrast the
    /// focus border of the active group.
    fn connected_tab_border(&self) -> Rgba {
        match self.theme.kind {
            ThemeKind::HighContrastDark | ThemeKind::HighContrastLight => self.color("focusBorder"),
            _ => self.theme.custom_tab_border().unwrap_or_else(|| {
                ["editorGroupHeader.tabsBorder", "tab.border", "editor.background"]
                    .into_iter()
                    .find_map(|key| self.theme.color(key))
                    .expect("editor.background has a registry default")
            }),
        }
    }

    /// editorTabsControl.ts `getHoverTitle`: the long title, with a preview note on a preview editor's tab.
    fn tab_hover(&self, index: usize) -> impl IntoElement {
        self.editor_title_hover(self.tab_hover_id(index), &self.editors.editors[index])
    }

    /// Each group's tabs paint their own targets: `showHover` finds the focused tab's by its id.
    pub(super) fn tab_hover_id(&self, index: usize) -> gpui::ElementId {
        gpui::ElementId::NamedInteger(format!("tab-hover-{}", self.editors.id).into(), index as u64)
    }

    /// The focused tab's hover target, the active group's active tab's.
    pub(super) fn focused_editor_tab_hover(&self, window: &Window) -> Option<gpui::ElementId> {
        let index = self.editors.active_index().filter(|_| self.editor_tab_focus.is_focused(window))?;
        Some(self.tab_hover_id(index))
    }

    /// The active tab takes the focus with workbench.css's 1px `focusBorder` outline; handleClickOrTouch blurs the
    /// tab, so a press leaves the focus where it is.
    fn focusable_editor_tab(&self, tab: Stateful<Div>, cx: &mut Context<Self>) -> Stateful<Div> {
        let focus = self.editor_tab_focus.clone();
        let border = self.theme.color("focusBorder");
        let outline = canvas(|_, _, _| {}, move |bounds, _, window, _| {
            if let Some(border) = border.filter(|_| focus.is_focused(window)) {
                window.paint_quad(gpui::outline(bounds, border, gpui::BorderStyle::Solid));
            }
        });
        tab.track_focus(&self.editor_tab_focus)
            .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
            .on_key_down(cx.listener(Self::editor_tab_key_down))
            .child(outline.absolute().size_full())
    }

    /// multiEditorTabsControl.ts keyboard accessibility: Shift+F10 shows the tab's context menu at the tab; Left and Up
    /// open the previous editor, Right and Down the next, Home and End the first and last, keeping the focus on their
    /// tab (`focusTabControl`).
    fn editor_tab_key_down(&mut self, event: &gpui::KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        let Some(active) = self.editors.active_index() else { return };
        let modifiers = event.keystroke.modifiers;
        if event.keystroke.key == "f10" && modifiers.shift && !(modifiers.control || modifiers.alt || modifiers.platform) {
            let Some(tab) = self.painted_hover_bounds(&self.tab_hover_id(active)) else { return };
            cx.stop_propagation();
            return self.show_tab_context_menu(active, tab, window, cx);
        }
        if modifiers.modified() {
            return;
        }
        let last = self.editors.editors.len() - 1;
        let target = match event.keystroke.key.as_str() {
            "left" | "up" => active.checked_sub(1),
            "right" | "down" => Some(active + 1).filter(|next| *next <= last),
            "home" => Some(0),
            "end" => Some(last),
            _ => None,
        };
        let Some(target) = target else { return };
        cx.stop_propagation();
        self.editors.activate(target);
        self.editors_changed(cx);
    }

    /// A tab's or an Open Editors row's hover: the editor's `getTitle(Verbosity.LONG)`.
    pub(super) fn editor_title_hover(&self, id: impl Into<gpui::ElementId>, editor: &OpenEditor) -> impl IntoElement {
        // `getTitle(Verbosity.LONG)`: a search editor's and a webview's is its name.
        let title = match (self.editors.diffs.get(&editor.model_id), editor.document().scheme.as_str()) {
            (Some(diff), _) => diff.title(|side| crate::quick_input::path_label(crate::editor::split_query(&side.scheme, &side.path).0, None)),
            (None, SEARCH_EDITOR_SCHEME | WEBVIEW_PANEL_SCHEME | super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | super::disassembly_view::DISASSEMBLY_SCHEME | MULTI_DIFF_EDITOR_SCHEME | TERMINAL_EDITOR_SCHEME) => self.editor_name(editor),
            // labels.ts: an untitled label's title is its name and its path.
            (None, "untitled") if !editor.text_model().associated_file => match self.untitled_description(editor) {
                Some(path) => format!("{} \u{2022} {path}", self.editor_name(editor)),
                None => self.editor_name(editor),
            },
            // `MergeEditorInput` keeps `getTitle` of its result.
            (None, _) => match self.editors.merges.get(&editor.model_id) {
                Some(merge) => crate::quick_input::path_label(&merge.result.path, None),
                // fileEditorInput.ts `getTitle`: a preferred name goes before the path.
                None => match editor.text_model().preferred_name.clone() {
                    Some(name) => format!("{name} ({})", crate::quick_input::path_label(&editor.document().path, None)),
                    None => crate::quick_input::path_label(&editor.document().path, None),
                },
            },
        };
        let content = if editor.preview { super::hover::HoverContent::Preview(title) } else { super::hover::HoverContent::Text(title) };
        self.hover_target(id, content, super::hover::HoverOptions::mouse())
    }

    /// A diff editor's tab is its modified side's (`DiffEditorInput.isDirty`); an auto saved one shows no dirty mark.
    pub(super) fn tab_shows_dirty(&self, index: usize) -> bool {
        self.editor_shows_dirty(&self.editors.editors[index])
    }

    pub(super) fn editor_shows_dirty(&self, tab: &OpenEditor) -> bool {
        // A notebook tab is its notebook's working copy, not its focused cell's text model.
        if tab.document().scheme == crate::notebook::NOTEBOOK_EDITOR_SCHEME {
            return self.host.notebooks.model(&tab.document().path.to_string_lossy()).is_some_and(|model| model.dirty);
        }
        if let Some(input) = self.editors.multi_diffs.get(&tab.model_id) {
            return self.multi_diff_dirty(input);
        }
        let model = self.editors.editor_model(tab);
        model.is_dirty() && !self.editor_is_saving(model)
    }

    /// A tab sized to its label (tab.sizing fit): 8px before the label, 30.5px after it for the close action.
    fn tab(&self, index: usize, active: bool, row: TabRow, window: &Window, cx: &mut Context<Self>) -> Div {
        let editor = &self.editors.editors[index];
        let upper = row == TabRow::Upper;
        // tabs.css: a pill's 24px content sits in the tab's transparent border-block, 4px above it, 6px in the pinned
        // tabs' own bar and 2px in the bar below it (`two-tab-bars`).
        let pill_top = (!self.connected_editor_tabs()).then(|| match row {
            TabRow::Upper => 6.,
            TabRow::Main { .. } if self.two_tab_bars() => 2.,
            TabRow::Main { .. } => 4.,
        });
        let pill = pill_top.is_some();
        // connectedEditorTabs.css: the upper bar's tabs are 28px high, their label and icon 2px from the top.
        let content_top = match (pill_top, upper) {
            (Some(top), _) => top,
            (None, true) => 2.,
            (None, false) => 3.5,
        };
        // Compact sticky tabs show only the icon and no actions, shrink ones cut the label.
        let sticky_sizing = self.sticky_tab_width(index);
        let compact = sticky_sizing == Some(28.);
        let readonly = self.readonly(&editor.document().scheme, &editor.document().path).is_some();
        let action_foreground = match active {
            true => self.foreground_or("modernEditorTab.activeForeground"),
            // modernUI tabs.css: `color-mix(foreground 50%, transparent)`, which connected tabs outside high contrast
            // replace with tab.inactiveForeground.
            false if pill || self.theme.kind.is_high_contrast() => crate::theme::color_mix(self.color("foreground"), 0.5, gpui::transparent_black().into()),
            false => self.foreground_or("tab.inactiveForeground"),
        };
        // modernUI tabs.css `.tab:hover:not(.active)`: the label and the action in modernEditorTab.hoverForeground.
        let hover_foreground = self.foreground_or("modernEditorTab.hoverForeground");
        let tab_group = gpui::SharedString::from(format!("tab-{index}"));
        // tabs.css colors `.tab-label:not(.monaco-decoration-itemColor)`: a decorated label (read-only, no color of its
        // own) inherits the tab's color from multieditortabscontrol.css, `tab.activeForeground` when active.
        let foreground = if active && readonly { self.foreground_or("tab.activeForeground") } else { action_foreground };
        // textFileService.ts decorations: a deleted file's label is struck through in `list.errorForeground`.
        let orphaned = editor.document().scheme == "file" && self.text_files.orphaned.contains(&editor.document().path);
        // multiEditorTabsControl.ts: the label takes the decorations of the input's resource per `workbench.editor.decorations`;
        // a merge editor's resource is its result.
        let (scheme, path) = match self.editors.merges.get(&editor.model_id) {
            Some(merge) => (&merge.result.scheme, &merge.result.path),
            None => (&editor.document().scheme, &editor.document().path),
        };
        let decoration = (scheme == "file").then(|| self.file_decoration(path, false)).flatten();
        let decoration_color = self.decoration_color(decoration.as_ref(), self.setting("workbench.editor.decorations.colors") != json!(false));
        // multiEditorTabsControl.ts: no badges in compact sticky tabs, for lack of room.
        let badge = self.decoration_badge(decoration.as_ref(), foreground).filter(|_| !compact && self.setting("workbench.editor.decorations.badges") != json!(false));
        let label = div()
            .mt(px(content_top))
            .h(px(24.))
            .line_height(px(24.))
            .whitespace_nowrap()
            .flex()
            .items_baseline()
            .debug_selector(move || format!("tab-name-{index}"))
            .when(editor.preview, |label| label.italic())
            .when_some(decoration_color, |label, color| label.text_color(color))
            .when(orphaned, |label| label.line_through().text_color(self.foreground_or("list.errorForeground")))
            // A flex item's text never shrinks, so the cut name gets its own box for the ellipsis.
            .map(|label| match sticky_sizing {
                // Chrome's `text-overflow: ellipsis` keeps the first character and clips the ellipsis after it, where
                // GPUI would draw the ellipsis alone; with no room at all the name is clipped away.
                Some(_) => {
                    let name = self.editor_name(editor);
                    let (first, rest) = name.split_at(name.chars().next().map_or(0, char::len_utf8));
                    let rest = div().min_w_0().overflow_hidden().text_ellipsis().child(rest.to_string());
                    label.min_w_0().overflow_hidden().child(div().min_w_0().overflow_hidden().flex().child(div().flex_none().child(first.to_string())).child(rest))
                }
                None => label.child(self.editor_name(editor)),
            })
            .children(self.untitled_description(editor).map(|description| {
                // iconlabel.css `.label-description`: 0.9em at 0.7 opacity (0.95 in light themes), 0.5em after the name.
                let opacity = if self.theme.kind == ThemeKind::Light { 0.95 } else { 0.7 };
                super::icon_label::label_description().opacity(opacity).child(description)
            }));
        let tab_scheme = self.editors.editors[index].document().scheme.clone();
        let file_icon = match matches!(tab_scheme.as_str(), crate::notebook::NOTEBOOK_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME) {
            // A notebook tab's icon is its notebook file's, not the focused cell's; the playground's is its page's.
            true => self.document_icon(&self.editors.editors[index], 24., foreground),
            false => self.document_icon(self.editors.tab_model(index), 24., foreground),
        };
        // textFileService.ts decorations: a read-only file's label ends in the lockSmall badge at 0.75 opacity. The
        // iconlabel.css `::after` font-size 90% (11.7px) wins over the decoration rule's 16px, which loads first.
        let lock = readonly.then(|| self.icon("lock-small", 11.7, 11.7, foreground).mt(px(9.5)).ml(px(5.)).opacity(0.75));
        // In a tab the badge sits right before the action's padding, without the list rows' 16px end margin.
        let badge = badge.map(|badge| badge.debug_selector(move || format!("tab-badge-{index}")).mt(px(3.5)).mr(px(0.)).line_height(px(24.)));
        // A sticky shrink tab's `.monaco-icon-label` holds the name, lock and badge with 5px after them and clips them, so the
        // name gives way to the badge first (the reference shows "1, U" alone in an 80px tab).
        let (label, lock, badge) = match sticky_sizing {
            Some(_) => (div().debug_selector(move || format!("tab-label-{index}")).flex().min_w_0().overflow_hidden().pr(px(5.)).child(label).children(lock).children(badge), None, None),
            None => (label, lock, badge),
        };
        // A dirty tab shows a filled circle where the close action goes, also when inactive, and the action itself
        // while hovered (multieditortabscontrol.css `.dirty .action-label:not(:hover)`); a sticky tab always shows its
        // unpin action (`pinned`, `pinned-dirty` while dirty).
        let dirty = self.tab_shows_dirty(index);
        let sticky = editor.sticky;
        let action_icon = if sticky { "pinned" } else { "close-small" };
        let rest_icon = match (sticky, dirty) {
            (true, true) => "pinned-dirty",
            (false, true) => "circle-filled",
            _ => action_icon,
        };
        let action_group = gpui::SharedString::from(format!("tab-action-{index}"));
        let action_icon_of = |name: &str| self.styled_icon(name, 20., 16., |icon| icon.text_color(action_foreground).when(!active, |icon| icon.group_hover(tab_group.clone(), |icon| icon.text_color(hover_foreground))));
        let close = div()
            .id(("close", index))
            .debug_selector(move || format!("tab-action-{index}"))
            .group(action_group.clone())
            .relative()
            .rounded(px(4.))
            .hover(|action| action.bg(self.color("toolbar.hoverBackground")))
            .child(action_icon_of(rest_icon).group_hover(action_group.clone(), |icon| icon.invisible()))
            .child(action_icon_of(action_icon).absolute().top_0().left_0().invisible().group_hover(action_group, |icon| icon.visible()))
            // The tab's ActionBar has no hover delegate, so it makes an instant one (actionbar.ts).
            .when(sticky, |close| close.child(self.hover_target(("tab-unpin-hover", index), super::hover::HoverContent::Text("Unpin Editor".into()), super::hover::HoverOptions::managed())))
            .on_click(cx.listener(move |workbench, _, window, cx| {
                cx.stop_propagation();
                match sticky {
                    true => drop(workbench.execute_command("workbench.action.unpinEditor", vec![json!({ "editorIndex": index })], window, cx)),
                    false => drop(workbench.close_editors(vec![index], window, cx)),
                }
            }));
        // Each tab's ActionBar is a tab stop of the active group, its action shown while focused.
        let action_bar = !self.editor_groups.drawing_inactive;
        let close = if action_bar { self.action_bar_item_with_tab_stop(TAB_ACTIONS, &index.to_string(), true, close, cx) } else { close };
        let close_focused = action_bar && self.action_bar_focus(TAB_ACTIONS, &index.to_string(), cx).is_focused(window);
        // tabs.css: a pill reserves 28px for its action; multiEditorTabsControl.ts `getFitTabWidth` keeps that width
        // when the action hides, as for connected tabs.
        let trailing = if pill { 28. } else { 30.5 };
        let tab = div()
            .id(("tab", index))
            .relative()
            .h_full()
            .flex_none()
            .flex()
            .text_color(foreground)
            // GPUI lays text out before group hitboxes exist, so the label's hover color is the tab's own hover style.
            .when(!active && decoration_color.is_none() && !orphaned, |tab| tab.hover(move |tab| tab.text_color(hover_foreground)))
            .when(!active && !upper && !pill, |tab| tab.child(self.inactive_tab_hover_fill(tab_group.clone())))
            .when_some(pill_top, |tab, top| tab.child(self.pill_tab_fill(active, top, tab_group.clone()).debug_selector(move || format!("tab-pill-{index}"))))
            .when(self.shows_tab_divider(index, active, row), |tab| {
                // A pill's divider centers on its content box, inside the border-block.
                let divider = self.tab_divider().when_some(pill_top, |divider, top| divider.top(px(top + 4.)).mt_0());
                tab.child(divider.debug_selector(move || format!("tab-divider-{index}")))
            })
            .when_some(sticky_sizing, |tab, width| tab.w(px(width)))
            .map(|tab| match (file_icon, compact) {
                (Some(icon), true) => tab.pl(px(5.)).child(icon.mt(px(content_top))),
                (None, true) => tab.px(px(4.)).child(label.flex_1().justify_center()),
                (Some(icon), false) => tab.pl(px(6.)).pr(px(trailing)).child(icon.mt(px(content_top))).child(label.ml(px(6.))),
                (None, false) => tab.pl(px(8.)).pr(px(trailing)).child(label),
            })
            .children(lock)
            .children(badge)
            .map(|tab| self.tab_drag_and_drop(tab, self.editors.id, index, cx))
            .on_click(cx.listener(move |workbench, event: &gpui::ClickEvent, window, cx| {
                // Enter or Space on the focused tab opens its editor with the focus.
                if event.is_keyboard() {
                    return workbench.focus_group(workbench.editors.id, window, cx);
                }
                workbench.editors.activate(index);
                if event.click_count() == 2 {
                    workbench.editors.pin(index);
                }
                workbench.editors_changed(cx);
            }))
            .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                cx.stop_propagation();
                workbench.show_tab_context_menu(index, super::editor_menus::point_anchor(event.position), window, cx);
            }))
            // multiEditorTabsControl.ts: a middle click closes the tab unless `preventPinnedEditorClose` keeps it.
            .on_mouse_up(MouseButton::Middle, cx.listener(move |workbench, _: &gpui::MouseUpEvent, window, cx| {
                if !workbench.prevents_mouse_close(&workbench.editors.editors[index]) {
                    drop(workbench.close_editors(vec![index], window, cx));
                }
            }))
            .child(self.tab_hover(index))
            .when(active && !self.editor_groups.drawing_inactive, |tab| self.focusable_editor_tab(tab, cx))
            // connectedEditorTabs.css: an inactive tab's close action is `opacity: 0` until the tab is hovered, still a tab stop.
            .group(tab_group.clone())
            .when(!compact, |tab| {
                // tabs.css: a pill's `.tab-actions` is 24px wide, 2px from the tab's end, inside its border-block.
                let (close_top, close_right) = match (pill_top, upper) {
                    (Some(top), _) => (top + 2., 4.),
                    (None, true) => (4., 6.5),
                    (None, false) => (5.5, 6.5),
                };
                tab.child(div().absolute().top(px(close_top)).right(px(close_right)).when(!(active || dirty || sticky || close_focused), |close| close.opacity(0.).group_hover(tab_group, |close| close.opacity(1.))).child(close))
            });
        if !active || pill {
            return div().h_full().flex_none().child(tab);
        }
        // connectedEditorTabs.css: an active tab in the upper bar is not connected to the editor, only a 24px fill inset 2px.
        if upper {
            let fill = div().absolute().inset(px(2.)).rounded(px(4.)).bg(self.color("editor.background"));
            return div().h_full().flex_none().relative().child(fill).child(tab);
        }
        // The fill starts in the part's top border row; its caps and shoulders are cornerRadius-medium plus the stroke.
        let surface = self.color("editor.background");
        let border = self.connected_tab_border();
        let radius = px(7.);
        let shoulder = |piece: Div| piece.absolute().bottom_0().size(radius).bg(surface);
        let strip_corner = || div().size_full().bg(self.tab_strip_background()).border_b_1().border_color(border);
        let TabRow::Main { first, clip, after_sticky } = row else { unreachable!("the upper bar's tab returned above") };
        // connectedEditorTabs.css: the first tab's top left corner is the part's, square in compact density.
        let square_corner = first && self.compact_density();
        // connectedTabClipping.ts: a fill scrolled almost out of the bar is not drawn.
        if clip.hidden {
            return div().h_full().flex_none().child(tab);
        }
        // A fill cut by the bar ends in a cap at the bar's edge, drawn over the label: at the start without its border
        // beside sticky tabs (`.connected-tab-left-clipped::before`), at the end 7px inside the bar before its shoulder
        // (`.tab-connected-overflow-edge.connected-tab-right-clipped`).
        let fill = || div().absolute().top(px(-1.)).h(px(TAB_STRIP_HEIGHT + 1.)).bg(surface).border_t_1().border_color(border);
        // The part's `.content` clips the first tab's square top left corner to its 8px radius (connectedEditorTabs.css
        // rounds only the fill's top right). GPUI clips to rectangles only: the fill starts past the corner and a piece
        // of the clipped shape fills it.
        let part_corner = first && !square_corner && clip.left == 0. && self.editor_groups.part == super::editor_groups::MAIN_PART && !self.editor_groups.drawing_inner_corners[0];
        let content_radius = px(PART_CONTENT_RADIUS);
        div()
            .h_full()
            .flex_none()
            .relative()
            .when(part_corner, |tab| tab.child(div().absolute().left_0().top_0().w(content_radius).h(px(TAB_STRIP_HEIGHT)).bg(surface).rounded_tl(content_radius)))
            .child(
                fill()
                    .left(px(if part_corner { PART_CONTENT_RADIUS } else { clip.left }))
                    .right(px(clip.right))
                    .border_r_1()
                    .rounded_tr(radius)
                    .when(!square_corner && !part_corner, |fill| fill.rounded_tl(radius)),
            )
            .when_some(self.theme.color("tab.activeBorder"), |tab, color| tab.child(div().absolute().bottom_0().left_0().right_0().h(px(1.)).bg(color)))
            // The first tab meets the part's own rounded corner, so it has no left shoulder; nor has one at the bar's start.
            .when(!first && !clip.left_edge, |tab| tab.child(shoulder(div().left(-radius)).child(strip_corner().border_r_1().rounded_br(radius))))
            .child(tab)
            .when(clip.left > 0., |tab| tab.child(fill().left(px(clip.left)).w(radius).when(!after_sticky, |cap| cap.border_l_1()).rounded_tl(radius)))
            .when(clip.right > 0., |tab| {
                tab.child(div().absolute().top_0().bottom_0().right(px(clip.right) - radius).w(radius).bg(self.tab_strip_background()))
                    .child(fill().right(px(clip.right)).w(radius).border_r_1().rounded_tr(radius))
            })
            .child(shoulder(div().right(px(clip.right) - radius)).child(strip_corner().border_l_1().rounded_bl(radius)))
    }

    /// connectedEditorTabs.css: a hovered inactive tab's `.tab-fill` is inset 2px at the sides, reaches 1px below the
    /// tab and takes `color-mix(foreground 6%, strip background)`.
    fn inactive_tab_hover_fill(&self, tab_group: gpui::SharedString) -> Div {
        let background = crate::theme::color_mix(self.color("foreground"), 0.06, self.tab_strip_background());
        // shortcut: a theme's own tab hover colors (modernTabColorCustomizations.ts) are not read; port that module when a theme needs them.
        div().absolute().left(px(2.)).right(px(2.)).top_0().bottom(px(-1.)).rounded(px(4.)).group_hover(tab_group, move |fill| fill.bg(background))
    }

    /// modernUI tabs.css `.tab-fill`: a 24px pill inset 2px at the sides, `top` below the tab's top, in the
    /// modernEditorTab colors; high contrast strokes it instead, dashed while an inactive tab is hovered.
    fn pill_tab_fill(&self, active: bool, top: f32, tab_group: gpui::SharedString) -> Div {
        let fill = div().absolute().left(px(2.)).right(px(2.)).top(px(top)).h(px(24.)).rounded(px(4.));
        if self.theme.kind.is_high_contrast() {
            let contrast = self.color("contrastActiveBorder");
            return match active {
                true => fill.border_1().border_color(contrast),
                false => fill.border_1().border_color(self.color("tab.border")).group_hover(tab_group, move |fill| fill.border_dashed().border_color(contrast)),
            };
        }
        let (rest, hover) = match active {
            true => ("modernEditorTab.activeBackground", "modernEditorTab.activeHoverBackground"),
            false => ("modernEditorTab.inactiveBackground", "modernEditorTab.hoverBackground"),
        };
        let hover = self.color(hover);
        fill.bg(self.color(rest)).group_hover(tab_group, move |fill| fill.bg(hover))
    }

    /// connectedEditorTabs.css `.tab:not(.active) + .tab:not(.active) > .tab-divider`: 1x16px of tab.divider at the
    /// tab's start, vertically centered; high contrast hides it in the upper bar. Pills have it before every tab but
    /// the first, none in high contrast (tabs.css).
    fn shows_tab_divider(&self, index: usize, active: bool, row: TabRow) -> bool {
        if !self.connected_editor_tabs() {
            let first = match row {
                TabRow::Main { first, .. } => first,
                TabRow::Upper => index == 0,
            };
            return !first && !self.theme.kind.is_high_contrast();
        }
        let first = match row {
            TabRow::Main { first, .. } => first,
            TabRow::Upper if self.theme.kind.is_high_contrast() => return false,
            TabRow::Upper => index == 0,
        };
        !active && !first && self.editors.active_index() != Some(index - 1)
    }

    fn tab_divider(&self) -> Div {
        div().absolute().left_0().top(gpui::relative(0.5)).mt(px(-8.)).w(px(1.)).h(px(16.)).bg(self.theme.tab_divider().unwrap_or(gpui::transparent_black().into()))
    }

    pub(super) fn document_icon(&self, editor: &OpenEditor, line_height: f32, foreground: Rgba) -> Option<Div> {
        let document = &editor.document();
        // `SearchEditorInput.getIcon`.
        if document.scheme == SEARCH_EDITOR_SCHEME {
            return self.predefined_file_icon("search", line_height, foreground);
        }
        // `MultiDiffEditorInput.getIcon`.
        if document.scheme == MULTI_DIFF_EDITOR_SCHEME {
            return self.predefined_file_icon("diff-multiple", line_height, foreground);
        }
        // `ReplEditorInput.getIcon`.
        if document.scheme == crate::notebook::NOTEBOOK_EDITOR_SCHEME && self.host.notebooks.interactives.iter().any(|interactive| interactive.repl && interactive.notebook == document.path.to_string_lossy()) {
            return self.predefined_file_icon("debug-line-by-line", line_height, foreground);
        }
        // walkThroughPart.css: the playground's `vs_code_editor_walkthrough.md` file icon is code-icon.svg.
        if document.scheme == super::welcome_page::WALKTHROUGH_SCHEME && self.is_playground(editor) {
            let icon = self.app_root.join("src/vs/workbench/browser/media/code-icon.svg");
            return Some(div().flex().items_center().h(px(line_height)).child(gpui::img(icon).size(px(16.))));
        }
        // `DisassemblyViewInput.getIcon`.
        if document.scheme == super::disassembly_view::DISASSEMBLY_SCHEME {
            return self.predefined_file_icon("debug", line_height, foreground);
        }
        // `ExtensionsInput.getIcon`.
        if document.scheme == super::extension_editor::EXTENSION_EDITOR_SCHEME {
            return self.predefined_file_icon("extensions", line_height, foreground);
        }
        // releaseNotesEditor.ts opens its webview with `Codicon.vscode`.
        if self.is_release_notes(&document.path) {
            return Some(self.icon("vscode", 16., 16., foreground).h(px(line_height)));
        }
        if document.scheme == TERMINAL_EDITOR_SCHEME {
            return self.terminal_editor_icon(editor, line_height, foreground);
        }
        if let Some(icon) = self.webview_icon(&document.path) {
            return Some(div().flex().items_center().h(px(line_height)).child(gpui::img(icon.to_path_buf()).size(px(16.))));
        }
        // A custom editor or media preview tab is labeled by its resource (CustomEditorInput), with the file's icon.
        if let Some(resource) = self.webview_resource(&document.path) {
            return self.file_icons.as_ref()?.file_icon(&resource, self.languages.language_of(&resource, ""), self.theme.kind, 13., line_height, foreground);
        }
        self.file_icons.as_ref()?.file_icon(&document.path, &document.language_id, self.theme.kind, 13., line_height, foreground)
    }

    /// getIconClasses.ts gives an editor's ThemeIcon `predefined-file-icon`: style.css draws it in the 13px label font, 3px
    /// into its 16px box, and only with a file icon theme. Chrome centers the 1em ascent in the line, floored.
    pub(super) fn predefined_file_icon(&self, name: &str, line_height: f32, color: Rgba) -> Option<Div> {
        self.file_icons.as_ref()?;
        Some(div().debug_selector(|| "predefined-file-icon".into()).w(px(16.)).h(px(line_height)).flex_none().pl(px(3.)).pt(px(((line_height - 13.) / 2.).floor())).child(self.icon(name, 13., 13., color)))
    }

    /// The file's path below its workspace folder, one item per segment (breadcrumbs.filePath relative), after the
    /// folder's name in a workspace (`BreadcrumbsModel._initFilePathInfo`).
    pub(super) fn breadcrumbs(&self, editor: &OpenEditor, cx: &mut Context<Self>) -> Div {
        let foreground = self.color("breadcrumb.foreground");
        // editorGroupView.ts: the title's bottom border, drawn over the breadcrumbs' last row.
        let title_border = ["editorGroupHeader.border", "contrastBorder"].into_iter().find_map(|key| self.theme.color(key));
        div()
            .relative()
            .h(px(BREADCRUMBS_HEIGHT))
            .flex_none()
            .overflow_hidden()
            .flex()
            .bg(self.color("breadcrumb.background"))
            .text_color(foreground)
            .child(self.breadcrumbs_widget(editor, false, cx))
            .children(self.editor_type_picker(cx))
            .when_some(title_border, |crumbs, color| crumbs.child(div().absolute().bottom_0().left_0().right_0().h(px(1.)).bg(color)))
    }

    /// singleeditortabscontrol.css `.title.breadcrumbs`: the breadcrumbs after the single tab's label, .45em after it,
    /// `/` between the items in place of the chevrons, ` • ` after a workspace folder, and no file icon.
    fn inline_breadcrumbs(&self, editor: &OpenEditor, cx: &mut Context<Self>) -> Div {
        self.breadcrumbs_widget(editor, true, cx).ml(px(13. * 0.45)).h_full().text_color(self.color("breadcrumb.foreground")).when(editor.preview, |crumbs| crumbs.italic())
    }

    /// A notebook editor's breadcrumbs are its notebook's resource and the notebook outline (notebookOutline.ts).
    pub(super) fn notebook_breadcrumbs_of(&self, editor: &OpenEditor, foreground: Rgba, line_height: f32) -> Option<(PathBuf, Vec<(Option<Div>, String)>)> {
        let is_notebook = matches!(editor.document().scheme.as_str(), crate::notebook::CELL_SCHEME | crate::notebook::NOTEBOOK_EDITOR_SCHEME);
        self.notebook_breadcrumbs(foreground, line_height).filter(|_| is_notebook)
    }

    /// The resource the breadcrumbs show: a custom editor's is its resource's (`EditorResourceAccessor.getOriginalUri`).
    pub(super) fn breadcrumbs_resource(&self, editor: &OpenEditor, notebook_path: Option<PathBuf>) -> (String, PathBuf) {
        // customEditorDiffInput.ts: a custom editor diff's resource is its modified side.
        let custom_diff = self.editors.active_diff().filter(|diff| diff.custom.is_some()).map(|diff| diff.modified.path.clone());
        // shortcut: a notebook's or custom editor diff's resource opens as a file, upgrade when they keep the URI.
        if let Some(path) = notebook_path.or(custom_diff) {
            return ("file".into(), path);
        }
        let document = editor.document();
        self.custom_editor_resource(&document.path).unwrap_or_else(|| (document.scheme.clone(), document.path.clone()))
    }

    /// breadcrumbsModel.ts `_initFilePathInfo`: the path's items as labels, whether the first is relative to a folder or
    /// the home, and whether the first is a root folder.
    pub(super) fn breadcrumb_file_segments(&self, scheme: &str, path: &Path) -> (Vec<String>, bool, bool) {
        let workspace = self.workspace();
        // A folder or the home of another scheme never holds the resource: `vscode-debug-memory:/3/memory.bin` is `3 > memory.bin`.
        let local = crate::editor::on_disk(scheme);
        let folder = workspace.filter(|_| local).and_then(|workspace| workspace.folder_of(path));
        let home = std::env::home_dir().filter(|home| local && folder.is_none() && path.starts_with(home));
        // breadcrumbsModel.ts `_initFilePathInfo`: the path below the workspace folder, else below the user home as
        // `~` (`getUriHome`), else below the root, which has no item.
        let (relative, root): (PathBuf, Option<String>) = match (folder, &home) {
            (Some(folder), _) => (path.iter().skip(folder.path.iter().count()).collect(), None),
            (None, Some(home)) => (path.iter().skip(home.iter().count()).collect(), Some("~".into())),
            // On Windows the walk ends at `/c:/`, an item of its own: the drive, without the root separator.
            (None, None) if cfg!(windows) => (path.components().filter(|component| !matches!(component, std::path::Component::RootDir)).collect(), None),
            (None, None) => (path.iter().skip(1).collect(), None),
        };
        let is_relative = root.is_some() || folder.is_some();
        let mut segments: Vec<String> = root.into_iter().chain(relative.iter().map(|segment| segment.to_string_lossy().into_owned())).collect();
        if let Some(folder) = folder.filter(|_| workspace.is_some_and(|workspace| workspace.file.is_some())) {
            segments.insert(0, folder.name.clone());
        }
        // The `~` and a workspace's folder are FileKind.ROOT_FOLDER items.
        let has_root_folder = home.is_some() || folder.is_some_and(|_| workspace.is_some_and(|workspace| workspace.file.is_some()));
        (segments, is_relative, has_root_folder)
    }

    fn breadcrumbs_widget(&self, editor: &OpenEditor, inline: bool, cx: &mut Context<Self>) -> Div {
        let foreground = self.color("breadcrumb.foreground");
        let line_height = if inline { SINGLE_TAB_TITLE_HEIGHT } else { BREADCRUMBS_HEIGHT };
        let (notebook_path, notebook_items) = self.notebook_breadcrumbs_of(editor, foreground, line_height).unzip();
        let (scheme, path) = self.breadcrumbs_resource(editor, notebook_path.clone());
        let (segments, is_relative, has_root_folder) = self.breadcrumb_file_segments(&scheme, &path);
        let file = segments.len() - 1;
        let symbol_items: Vec<(Option<Div>, String)> = match notebook_items {
            Some(items) => items,
            None => self
                .breadcrumb_symbols(editor)
                .into_iter()
                .map(|(kind, name)| {
                    let codicon = kind.map(crate::symbol_icons::codicon);
                    let color = codicon.and_then(crate::symbol_icons::color_key).and_then(|key| self.theme.color(key)).unwrap_or(foreground);
                    // `.outline-element-icon`: 3px after the symbol icon, where a file icon's `::before` has 6px; none
                    // inline, measured against the reference with ui-pair.
                    let icon = codicon.filter(|_| self.setting("breadcrumbs.icons") != false).map(|codicon| self.icon(codicon, 16., 16., color).when(!inline, |icon| icon.mr(px(3.))));
                    (icon, name)
                })
                .collect(),
        };
        let last = file + symbol_items.len();
        let file_items = segments.into_iter().enumerate().map(|(index, segment)| {
            // The 16px before each item is the item's own ::before; folders have no icon in Seti, the file does.
            let file_icon = match (index == file && !inline, &notebook_path) {
                (false, _) => None,
                (true, Some(path)) => self.file_icons.as_ref().and_then(|icons| icons.file_icon(path, self.languages.language_of(path, ""), self.theme.kind, 13., line_height, foreground)),
                (true, None) => self.document_icon(editor, line_height, foreground),
            };
            (file_icon.map(|icon| icon.mr(px(6.))), segment)
        });
        // breadcrumbsWidget.css: an item is its icon, its label and the 16px separator codicon, without gaps; the
        // first one starts 16px in, measured against the reference with ui-pair.
        let focused = self.breadcrumbs_focused();
        let selected = self.breadcrumbs_selected();
        // breadcrumbsWidget.ts `_style`: the focused item and a hovered other one in `breadcrumb.focusForeground`, the
        // focused and selected one in `breadcrumb.activeSelectionForeground`; the separator inherits the item's color.
        let focus_foreground = self.color("breadcrumb.focusForeground");
        let selection_foreground = self.color("breadcrumb.activeSelectionForeground");
        let group = self.editors.id;
        let item_bounds = self.breadcrumbs.item_bounds.clone();
        let items = file_items.chain(symbol_items).enumerate().map(|(index, (icon, segment))| {
            let root_folder = has_root_folder && index == 0;
            let slash = !root_folder && !(index == 0 && is_relative) && !(index == 1 && has_root_folder);
            let is_focused = focused == Some(index);
            let is_selected = selected == Some(index);
            // breadcrumbscontrol.css: the focused or selected item's label is underlined.
            let segment = div().debug_selector(move || format!("breadcrumb-label-{index}")).when(is_focused || is_selected, |label| label.underline()).child(segment);
            let foreground = match (is_focused, is_selected) {
                (true, true) => selection_foreground,
                (true, false) => focus_foreground,
                (false, _) => foreground,
            };
            let hoverable = !is_focused && !is_selected;
            let item_bounds = item_bounds.clone();
            // breadcrumbsWidget.ts `_focus` gives the item DOM focus: workbench.css's 1px `focusBorder` outline.
            let outline = self.theme.color("focusBorder").filter(|_| is_focused);
            let widget_focus = self.breadcrumbs.focus.clone();
            div()
                .id(("breadcrumb-item", index))
                .debug_selector(move || format!("breadcrumb-item-{index}"))
                .relative()
                .group("breadcrumb-item")
                .child(
                    canvas(
                        move |bounds, _, _| {
                            item_bounds.borrow_mut().insert((group, index), bounds);
                        },
                        move |bounds, _, window, _| {
                            if let Some(outline) = outline.filter(|_| widget_focus.is_focused(window)) {
                                window.paint_quad(gpui::outline(bounds, outline, gpui::BorderStyle::Solid));
                            }
                        },
                    )
                    // Pinned to the padding box: without an inset, an absolute child starts after the first item's 16px.
                    .absolute()
                    .inset_0(),
                )
                .on_click(cx.listener(move |workbench, event: &gpui::ClickEvent, window, cx| {
                    if workbench.editors.id != group {
                        workbench.focus_group(group, window, cx);
                    }
                    workbench.breadcrumb_clicked(index, f32::from(event.position().x), window, cx);
                }))
                .flex()
                .items_center()
                .whitespace_nowrap()
                .text_color(foreground)
                .when(hoverable, |item| item.hover(|item| item.text_color(focus_foreground)))
                .map(|item| match inline {
                    true => item.when(slash, |item| item.child(div().text_size(px(13. * 0.9)).child("/"))),
                    false => item.when(index == 0, |item| item.pl(px(16.))),
                })
                .when_some(icon, |item, icon| item.child(icon))
                .child(segment)
                .map(|item| match inline {
                    true => item.when(root_folder, |item| item.child(div().text_size(px(13. * 0.9)).child("\u{a0}\u{2022}\u{a0}"))).when(index == last, |item| item.pr(px(4.))),
                    // editortitlecontrol.css: the last item hides its separator and ends in 8px of padding.
                    false => item.when(index < last, |item| item.child(self.breadcrumb_separator(foreground, hoverable.then_some(focus_foreground)))).when(index == last, |item| item.pr(px(8.))),
                })
        });
        div()
            .flex_1()
            .min_w_0()
            .h_full()
            .overflow_hidden()
            .when(focused.is_some(), |widget| widget.track_focus(&self.breadcrumbs.focus))
            // The breadcrumbs sit in the title (editortabscontrol.css) and each item is pointer (breadcrumbsWidget.css).
            .cursor_pointer()
            .flex()
            // breadcrumbsWidget.ts `revealLast`: a path wider than the widget shows its end; the row is at least as
            // wide as the widget, so a short one starts at the left.
            .justify_end()
            .child(div().flex_none().min_w_full().flex().children(items))
    }

    /// The chevron after an item, in the item's color, and in `hover_color` while the item is hovered: the svg's
    /// color is its own, so the hovered one is a second chevron shown over it.
    fn breadcrumb_separator(&self, color: Rgba, hover_color: Option<Rgba>) -> Div {
        let chevron = self.icon("chevron-right", 16., 16., color);
        let Some(hover_color) = hover_color else { return chevron };
        div()
            .relative()
            .child(chevron.group_hover("breadcrumb-item", |chevron| chevron.invisible()))
            .child(div().absolute().inset_0().invisible().group_hover("breadcrumb-item", |chevron| chevron.visible()).child(self.icon("chevron-right", 16., 16., hover_color)))
    }

    pub(super) fn editor_metrics(&self, editor: &OpenEditor, window: &mut Window) -> EditorMetrics {
        if self.editors.multi_diff_side(editor.model_id).is_some() {
            return self.multi_diff_editor_metrics(editor, window);
        }
        let test_data = editor.document().scheme == crate::testing::TEST_DATA_SCHEME;
        // testResultsOutput.ts and callStackWidget.ts build their editors outside a text editor part: the default lineNumbersMinChars 5.
        let min_chars = if test_data || self.call_stack_frame(editor).is_some() { 5 } else { LINE_NUMBERS_MIN_CHARS };
        let mut metrics = EditorMetrics::measure_with_min_chars(window, editor.document().lines.len(), self.line_numbers(editor), self.editor_zoom.multiplier(), min_chars);
        // diffEditorEditors.ts `_adjustOptionsForSubEditor`: no folding and no minimap in either side.
        if self.quick_diff_editor_diff(editor).is_some() {
            // The quick diff peek's embedded diff editor keeps the default `lineDecorationsWidth` (10), not '2ch'.
            metrics.decorations_width = self.diff_side_decorations_width(editor, DECORATIONS_WIDTH - 16.);
        } else if let Some(diff) = self.editors.active_diff() {
            metrics.decorations_width = self.diff_side_decorations_width(editor, diff_editor_view::diff_decorations_width(metrics.char_width));
            // `_adjustOptionsForLeftHandSide` turns the glyph margin on; the modified side keeps
            // testResultsOutput.ts `commonEditorOptions` glyphMargin false.
            if test_data {
                metrics.glyph_margin = diff.original_editor.as_ref().is_some_and(|original| original.model_id == editor.model_id);
            }
        } else if self.editors.active_merge().is_some() {
            // mergeEditor.ts `applyOptions`: glyphMargin false and lineNumbersMinChars 2 in the inputs and the result.
            metrics = EditorMetrics::measure_with_min_chars(window, editor.document().lines.len(), self.line_numbers(editor), self.editor_zoom.multiplier(), 2);
            metrics.glyph_margin = false;
        } else if self.is_interactive_input(editor) || is_comment_input(editor) {
            // simpleEditorOptions.ts, simpleCommentEditor.ts: lineDecorationsWidth 0 and no folding; the comment
            // editor also has no glyph margin (ui-pair steps-comment-reply-editor.json).
            metrics.decorations_width = 0.;
            metrics.glyph_margin = !is_comment_input(editor);
        } else if test_data {
            // testResultsOutput.ts `commonEditorOptions`: glyphMargin false.
            metrics.glyph_margin = false;
        } else if editor.document().scheme == crate::notebook::CELL_SCHEME {
            // cellEditorOptions.ts: lineDecorationsWidth 0, only the folding controls.
            metrics.decorations_width = DECORATIONS_WIDTH - 10.;
        } else if self.editor_has_comment_threads(editor) {
            metrics.decorations_width += comment_glyph::reserved_width(true);
        }
        // walkThroughPart.ts `getEditorOptions`: lineNumbersMinChars 1.
        if editor.document().scheme == super::walkthrough_part::SNIPPET_SCHEME && metrics.line_numbers != LineNumbers::Off {
            let digits = editor.document().lines.len().to_string().len();
            metrics.line_numbers_width = (metrics.line_numbers_width / LINE_NUMBERS_MIN_CHARS.max(digits) as f32 * digits as f32).round();
        }
        metrics
    }

    /// contextmenu.ts `_doShowContextMenu` without a mouse event: below the cursor (`getScrolledVisiblePosition`).
    pub(super) fn cursor_anchor(&self, window: &mut Window) -> Option<gpui::Point<Pixels>> {
        let editor = self.editors.active()?;
        let metrics = self.editor_metrics(editor, window);
        let head = editor.selection().head;
        let viewport = self.editors.viewport;
        let view_line = editor.head_view_line(0);
        let left = metrics.content_left() + editor.segment_visible_column(editor.segment(view_line), head.column) * metrics.char_width - editor.scroll.left;
        let top = editor.line_top(view_line, viewport) - editor.scroll.top + metrics.line_height;
        let origin = self.text_area_bounds.get().origin;
        Some(point(px(origin.x + left), px(origin.y + top)))
    }

    /// `editor.lineNumbers` of `editor`.
    pub(super) fn line_numbers(&self, editor: &OpenEditor) -> LineNumbers {
        let overrides = config::configuration::Overrides { resource: Some(&editor.document().path), override_identifier: Some(&editor.document().language_id) };
        let setting = self.settings.lock().unwrap().get_value(Some("editor.lineNumbers"), &overrides);
        match editor.line_numbers_override.or_else(|| setting.as_ref().and_then(|value| value.as_str())) {
            // outputView.ts `OutputEditor.getConfigurationOverrides`: the Output view's editor hides line numbers.
            _ if self.editors.id == crate::editor::PANEL_GROUP && editor.document().scheme == crate::output::OUTPUT_SCHEME => LineNumbers::Off,
            // testResultsOutput.ts `commonEditorOptions`: lineNumbers off in a result message's editor; a multiline
            // diff's side editors override it.
            _ if editor.document().scheme == crate::testing::TEST_DATA_SCHEME && editor.line_numbers_override.is_none() => LineNumbers::Off,
            _ if self.zen_mode_hides_line_numbers() => LineNumbers::Off,
            // simpleEditorOptions.ts: an interactive window's or REPL editor's input has none.
            _ if self.is_interactive_input(editor) || is_comment_input(editor) => LineNumbers::Off,
            // cellEditorOptions.ts: a cell editor's line numbers follow its own `lineNumbers`, else `notebook.lineNumbers`.
            _ if editor.document().scheme == crate::notebook::CELL_SCHEME => match self.cell_line_numbers(&editor.document().uri_string()) {
                true => LineNumbers::On,
                false => LineNumbers::Off,
            },
            Some("off") => LineNumbers::Off,
            // gotoLineQuickAccess.ts: relative numbers switch to "on" while the picker previews in this editor.
            Some("relative") if self.quick_access.goto_line.as_ref().is_some_and(|state| state.previews(editor.model_id)) => LineNumbers::On,
            Some("relative") => LineNumbers::Relative,
            Some("interval") => LineNumbers::Interval,
            _ => LineNumbers::On,
        }
    }

    /// host_sync.rs `options` of `editor`, with the `RenderLineNumbersType` it draws.
    pub(super) fn host_editor_options(&self, editor: &OpenEditor) -> Value {
        let line_numbers = match self.line_numbers(editor) {
            LineNumbers::Off => 0,
            LineNumbers::On => 1,
            LineNumbers::Relative => 2,
            LineNumbers::Interval => 3,
        };
        crate::host_sync::options(editor, &self.settings.lock().unwrap(), line_numbers)
    }

    /// `HostSync::send_changes` with the options each text editor draws.
    pub(super) fn send_host_changes(&mut self) {
        let options: HashMap<String, Value> = self.host.text_editors(&self.editors).into_iter().map(|(_, editor, _)| (crate::host_sync::snapshot_id(editor), self.host_editor_options(editor))).collect();
        self.host.send_changes(&self.editors, &|editor| options[&crate::host_sync::snapshot_id(editor)].clone());
    }

    /// One of several live code editors stacked in one scrolling view (`EditorGroup::stacked_editors`, a notebook's
    /// cells): the group's code editor for the model it edits, the lines of the others; sized by its caller.
    pub(super) fn embedded_code_editor(&self, editor: &OpenEditor, window: &mut Window, cx: &mut Context<Self>) -> Div {
        if let Some(area) = self.code_editor_area(editor, window, cx) {
            return div().flex_1().flex().child(area);
        }
        let metrics = self.editor_metrics(editor, window);
        let rows = self.editor_lines(editor, 0..editor.view_line_count(), metrics, window, cx);
        div().flex_1().flex().flex_col().font_family(EDITOR_FONT).text_size(px(metrics.font_size)).line_height(px(metrics.line_height)).children(rows)
    }

    pub(super) fn text_area(&self, editor: &OpenEditor, window: &mut Window, cx: &mut Context<Self>) -> Stateful<Div> {
        let metrics = self.editor_metrics(editor, window);
        let area_left = self.text_area_left.clone();
        let area_bounds = self.text_area_bounds.clone();
        let focus = self.editor_focus.clone();
        let workbench = cx.entity();
        let laid_out = cx.entity();
        let view_line_count = editor.view_line_count();
        // quickDiffWidget.ts `_fillBody`: `stickyScroll: { enabled: false }`.
        let sticky_scroll_lines = if self.quick_diff_editor_diff(editor).is_some() { 0 } else { self.sticky_scroll_lines(editor) };
        let top_whitespace = self.editors.viewport.top_whitespace;
        let stop_rendering_line_after = self.stop_rendering_line_after;
        let minimap_settings = self.minimap_settings(editor);
        let in_cell = self.in_cell_editor(editor);
        let minimap_enabled = self.minimap_enabled(editor);
        let viewport = self.editors.viewport;
        let lines = editor.visible_lines(viewport);
        let zones = editor.zones_between(lines.clone());
        let zones_above: f32 = zones.iter().filter(|zone| zone.0 == lines.start).map(|zone| zone.1).sum();
        let lines_top = editor.line_top(lines.start, viewport) - zones_above - editor.scroll.top;
        let first_line = lines.start;
        let mut rows = Vec::new();
        for (index, row) in self.editor_lines(editor, lines, metrics, window, cx).into_iter().enumerate() {
            // mouseHandler.ts: a press on a view zone (CONTENT_VIEW_ZONE) leaves the cursor and, not prevented, blurs the textarea.
            rows.extend(zones.iter().filter(|zone| zone.0 == first_line + index).map(|zone| {
                let body = self.view_zone_body(editor, zone.2, zone.1, metrics.content_left(), cx);
                if self.suppresses_mouse_down(editor, zone.2) {
                    // mouseTarget.ts `_getZoneAtCoord`: the upper half presses the end of the line above, the lower half the start of the line below.
                    let line_below = zone.0;
                    let (upper, lower) = if line_below > 0 { ((line_below - 1, f32::MAX), (line_below, 0.)) } else { ((line_below, 0.), (line_below, 0.)) };
                    return body.child(self.zone_press_half(upper, cx).top_0()).child(self.zone_press_half(lower, cx).bottom_0());
                }
                body.on_mouse_down(MouseButton::Left, |_, window, cx| {
                    cx.stop_propagation();
                    window.blur(cx);
                })
            }));
            rows.push(row);
        }
        let minimap_width = self.minimap.info.as_ref().map_or(0., |(info, _)| info.width as f32);
        let margin_shift = self.minimap.info.as_ref().map_or(0., |(info, _)| info.margin_shift() as f32);
        let shifted = || div().absolute().top_0().bottom_0().left(px(margin_shift)).right_0();
        let now = Instant::now();
        if self.scrollbars.in_transition(now) || self.fold_controls.in_transition(now) || self.minimap.in_transition(now) {
            window.request_animation_frame();
        }
        let editor_origin = self.text_area_bounds.get().origin;
        let middle_scroll_dot = self.middle_scroll_dot(point(px(editor_origin.x), px(editor_origin.y)));
        let middle_scrolling = middle_scroll_dot.is_some();
        let selecting = self.selecting_text.is_some() && self.text_drag.is_none();
        let drag_scrolling = self.drag_scrolling.is_some();
        let content_right = metrics.content_left() + self.editors.viewport.width - if minimap_width > 0. && margin_shift == 0. { 0. } else { VERTICAL_SCROLLBAR_WIDTH };
        let scrolled = cx.entity();
        let group = self.editors.id;
        let inactive = self.editor_groups.drawing_inactive;
        // A code editor of the tab without the focus (code_editors.rs) lays out, scrolls and takes presses as itself.
        let drawn = self.editors.drawn;
        let model_id = editor.model_id;
        // diffEditorItemTemplate.ts: a multi diff file's editor has no scrollbars or shadow, only the decorations
        // ruler (`handleMouseWheel: false`), the list scrolls it.
        let in_multi_diff = self.editors.multi_diff_side(model_id).is_some();
        self.editor_accessibility(div().id(("text-area", editor.model_id as usize)), editor, window)
            .debug_selector(move || format!("text-area-{model_id}"))
            .flex_1()
            .relative()
            .overflow_hidden()
            .font_family(EDITOR_FONT)
            .text_size(px(metrics.font_size))
            .line_height(px(metrics.line_height))
            .when(!inactive, |area| area.track_focus(&self.editor_focus))
            .on_key_down(cx.listener(Self::editor_key_down))
            .on_key_up(cx.listener(Self::inspect_tokens_key_up))
            .when(!in_multi_diff, |area| {
                area.on_scroll_wheel(cx.listener(move |workbench, event: &ScrollWheelEvent, window, cx| match drawn {
                    Some(id) => workbench.with_code_editor(id, |workbench| workbench.editor_wheel(event, window, cx)),
                    None => workbench.editor_wheel(event, window, cx),
                }))
            })
            .on_drag_move(cx.listener(|workbench, event: &DragMoveEvent<ExternalPaths>, _, cx| {
                if !event.bounds.contains(&event.event.position) {
                    workbench.drag_files_over_text(None, false, cx);
                }
            }))
            .on_modifiers_changed(cx.listener(Self::sticky_modifiers_changed))
            .on_modifiers_changed(cx.listener(|workbench, event: &gpui::ModifiersChangedEvent, window, cx| {
                workbench.debug_hover_modifiers_changed(event.modifiers, window, cx);
                workbench.text_drag_modifiers_changed(event.modifiers, cx);
                workbench.content_hover_modifiers_changed(event.modifiers, cx);
                workbench.inline_completions_modifiers_changed(event.modifiers.shift, cx);
                workbench.links_modifiers_changed(event.modifiers, cx);
                workbench.definition_link_modifiers_changed(event.modifiers, cx);
                workbench.inlay_hints_modifiers_changed(event.modifiers, cx);
            }))
            .on_hover(cx.listener(|workbench, hovered: &bool, window, cx| {
                if !*hovered {
                    workbench.debug_hover_mouse_left(window.mouse_position(), window, cx);
                    workbench.content_hover_mouse_left(window.mouse_position(), window, cx);
                    workbench.definition_link_mouse_left();
                    workbench.commenting_hover_moved(None, cx);
                    workbench.coverage_mouse_moved(false, None, cx);
                }
            }))
            // The line's row sets `row_target` first: moves bubble from the row up to the text area.
            .on_mouse_move(cx.listener(|workbench, event: &MouseMoveEvent, window, cx| {
                let row_target = workbench.content_hover.row_target.take();
                let line_numbers = workbench.testing.coverage.line_numbers_target.take().is_some_and(|model_id| workbench.row_editor_active(model_id));
                workbench.coverage_mouse_moved(line_numbers, row_target, cx);
                workbench.links_mouse_moved(row_target, event.modifiers, cx);
                let target = match row_target {
                    Some((line, visible)) => super::content_hover::MouseTarget::Text { line, visible },
                    None => super::content_hover::MouseTarget::Other,
                };
                workbench.debug_hover_mouse_moved(target, event.position, event.modifiers, event.pressed_button.is_some(), window, cx);
                workbench.content_hover_mouse_moved(target, event.position, event.modifiers, event.pressed_button.is_some(), window, cx);
            }))
            .capture_any_mouse_down(cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                if let Some(id) = drawn {
                    workbench.focus_code_editor(id, window, cx);
                }
                workbench.hide_content_hover(cx);
                workbench.debug_hover_mouse_down(event.position, window, cx);
                if workbench.middle_scroll_mouse_down(event.button == MouseButton::Middle, event.position, cx) {
                    cx.stop_propagation();
                }
            }))
            .capture_any_mouse_up(cx.listener(|workbench, _, _, cx| workbench.middle_scroll_mouse_up(cx)))
            .capture_key_down(cx.listener(|workbench, event: &gpui::KeyDownEvent, _, cx| {
                workbench.definition_link_key_down(event.keystroke.modifiers, cx);
                workbench.end_middle_scroll(cx);
                workbench.cancel_text_drag(cx);
            }))
            .on_mouse_up(MouseButton::Left, cx.listener(|workbench, _, _, cx| {
                workbench.selecting_text = None;
                workbench.cancel_text_drag(cx);
            }))
            .on_mouse_up_out(MouseButton::Left, cx.listener(|workbench, _, _, cx| {
                workbench.selecting_text = None;
                workbench.cancel_text_drag(cx);
            }))
            .child(
                canvas(
                    move |bounds, window, cx| {
                        let (width, height) = (f32::from(bounds.size.width), f32::from(bounds.size.height));
                        let pixel_ratio = window.scale_factor();
                        let minimap = minimap_enabled.then(|| minimap_info(width, height, metrics.content_left(), metrics.char_width, metrics.line_height, view_line_count, pixel_ratio, minimap_settings.layout));
                        // The margin and content right of a left minimap: pointer positions count from there.
                        let shift = px(minimap.as_ref().map_or(0., |minimap| minimap.margin_shift() as f32));
                        area_left.set(f32::from(bounds.left() + shift));
                        area_bounds.set(Bounds::from_corners(point(bounds.left() + shift, bounds.top()), bounds.bottom_right()).map(f32::from));
                        // editorOptions.ts: contentWidth = remainingWidth - minimapWidth.
                        let minimap_width = minimap.as_ref().map_or(0., |minimap| minimap.width as f32);
                        let viewport = Viewport { width: width - metrics.content_left() - minimap_width, height, char_width: metrics.char_width, line_height: metrics.line_height, sticky_scroll_lines, top_whitespace, stop_rendering_line_after };
                        let minimap = minimap.map(|minimap| (minimap, pixel_ratio as f64));
                        laid_out.update(cx, |workbench, cx| {
                            workbench.group_laid_out(group, |workbench| match drawn {
                                Some(id) => workbench.with_code_editor(id, |workbench| workbench.editor_laid_out(viewport, minimap, cx)),
                                None => workbench.editor_laid_out(viewport, minimap, cx),
                            })
                        });
                    },
                    move |bounds, _, window, cx| {
                        if !inactive {
                            window.handle_input(&focus, ElementInputHandler::new(bounds, workbench), cx);
                        }
                        // Moves over an unfocused code editor or another group's do not reach the focused one; they go to
                        // its own hover (contentHoverController.ts runs per editor).
                        if inactive {
                            let (hovered, id) = (scrolled.clone(), drawn.unwrap_or(model_id));
                            window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
                                if phase != DispatchPhase::Capture || event.pressed_button.is_some() {
                                    return;
                                }
                                if !bounds.contains(&event.position) {
                                    hovered.update(cx, |workbench, cx| workbench.code_editor_mouse_moved(id, None, event, window, cx));
                                    return;
                                }
                                hovered.update(cx, |workbench, cx| workbench.group_laid_out(group, |workbench| workbench.code_editor_mouse_moved(id, Some(bounds.origin), event, window, cx)));
                                cx.stop_propagation();
                            });
                        }
                        // The focused group's own editor only: mouseHandler.ts watches the drag from the editor pressed.
                        if selecting && !inactive && drawn.is_none() {
                            let (dragged, origin, height) = (scrolled.clone(), point(bounds.left() + px(margin_shift), bounds.top()), f32::from(bounds.size.height));
                            // Capture runs before the lines' bubble listeners, so they see whether this move scrolls.
                            window.on_mouse_event(move |event: &MouseMoveEvent, phase, _, cx| {
                                if phase == DispatchPhase::Capture && event.pressed_button == Some(MouseButton::Left) {
                                    dragged.update(cx, |workbench, cx| workbench.drag_select_moved(origin, height, (metrics.content_left(), content_right), event.position, event.modifiers, cx));
                                }
                            });
                        }
                        if drag_scrolling && !inactive && drawn.is_none() && scrolled.update(cx, |workbench, cx| workbench.drag_scroll_frame(cx)) {
                            window.request_animation_frame();
                        }
                        if middle_scrolling && scrolled.update(cx, |workbench, cx| workbench.middle_scroll_frame(cx)) {
                            // observeWindowMousePos: the pointer anywhere in the window steers the session.
                            window.on_mouse_event(move |event: &MouseMoveEvent, phase, _, cx| {
                                if phase == DispatchPhase::Bubble {
                                    scrolled.update(cx, |workbench, _| workbench.middle_scroll_mouse_moved(event.position));
                                }
                            });
                            window.request_animation_frame();
                        }
                    },
                )
                .absolute()
                .inset_0(),
            )
            .child(
                shifted()
                    // .view-lines is monaco-mouse-cursor-text; the line numbers, glyph margin and the overview ruler over the
                    // vertical scrollbar keep the default cursor.
                    .child(div().debug_selector(|| "editor-view-lines".into()).absolute().top_0().bottom_0().left(px(metrics.content_left())).right(px(OVERVIEW_RULER_WIDTH)).cursor(self.text_cursor_style()).on_mouse_down(
                        MouseButton::Right,
                        // Below the last line (MouseTargetType.CONTENT_EMPTY): the position is the end of the last line.
                        cx.listener(|workbench, event: &MouseDownEvent, window, cx| {
                            let last = workbench.editors.active().expect("the text area shows an editor").document().lines.len() - 1;
                            workbench.show_editor_context_menu(last, f32::MAX, event.position, window, cx);
                        }),
                    ).on_mouse_down(
                        MouseButton::Left,
                        cx.listener(|workbench, event: &MouseDownEvent, window, cx| {
                            window.focus(&workbench.editor_focus, cx);
                            let last = workbench.editors.active().expect("the text area shows an editor").document().lines.len() - 1;
                            workbench.selecting_text = Some(MouseDown { count: event.click_count, on_gutter: false });
                            workbench.click_text(last, f32::MAX, event.modifiers, event.modifiers.shift, event.click_count, cx);
                        }),
                    ))
                    // editorScrollbar.ts clips the lines at contentWidth: the column right of the minimap stays empty.
                    .child(div().absolute().left_0().right(px(minimap_width - margin_shift)).top_0().bottom_0().overflow_hidden().child(div().absolute().left_0().right_0().top(px(lines_top)).children(rows)))
                    .children(self.marker_navigation_widget(editor, metrics.content_left(), metrics.char_width, cx))
                    .children(self.quick_diff_widget(editor, metrics, window, cx))
                    .children(self.references_peek_widget(editor, metrics.content_left(), metrics.char_width, window, cx))
                    .children(self.hierarchy_peek_widget(editor, metrics.content_left(), metrics.char_width, window, cx))
                    .children(self.testing_peek_widget(editor, metrics.content_left(), metrics.char_width, cx))
                    .child(
                        div().id("margin").absolute().top_0().bottom_0().left_0().w(px(metrics.content_left())).on_hover(cx.listener(|workbench, hovered: &bool, _, cx| {
                            let animate = !workbench.is_motion_reduced();
                            workbench.fold_controls.set_shown(*hovered, Instant::now(), animate);
                            cx.notify();
                        })),
                    )
                    // testResultsOutput.ts `commonEditorOptions`: `overviewRulerLanes: 0` in a result message's editor.
                    .when(!in_cell && editor.document().scheme != crate::testing::TEST_DATA_SCHEME && self.call_stack_frame(editor).is_none(), |area| area.child(div().debug_selector(move || format!("overview-ruler-{model_id}")).absolute().top_0().right_0().h_full().child(self.overview_ruler(editor).h_full())))
                    .when(!in_multi_diff, |area| area.child(self.scrollbars_canvas(editor, metrics, cx).absolute().inset_0()))
                    // contextmenu.ts: a right press on the scrollbar (MouseTargetType.SCROLLBAR) shows the minimap menu.
                    .child(div().absolute().top_0().bottom_0().right_0().w(px(VERTICAL_SCROLLBAR_WIDTH)).on_mouse_down(
                        MouseButton::Right,
                        cx.listener(|workbench, event: &MouseDownEvent, window, cx| workbench.show_scrollbar_context_menu(event.position, window, cx)),
                    )),
            )
            .when(editor.scroll.top > 0. && !in_multi_diff, |area| area.child(div().absolute().top_0().left_0().right(px(VERTICAL_SCROLLBAR_WIDTH)).h(px(SCROLL_SHADOW_HEIGHT)).cursor_default().child(self.scroll_shadow().size_full())))
            // minimap.css: the sticky scroll and the minimap share z-index 4, so the minimap, later in the DOM, paints over it.
            // testing.css: the coverage toolbar's z-index 1 is under the sticky scroll and the minimap.
            .children(self.coverage_toolbar(editor, window, cx))
            .child(shifted().children(self.sticky_scroll_widget(editor, metrics, window, cx)))
            .children(self.minimap(editor, cx))
            .child(
                shifted()
                    .children(middle_scroll_dot)
                    .children(self.empty_editor_hint(editor, metrics.content_left(), self.editors.viewport.width + metrics.content_left() + minimap_width, window, cx))
                    // Messages and the overlay widgets are the focused editor's; the hover is any code editor's.
                    .children(self.content_hover_widget(editor, metrics.content_left(), metrics.char_width, window, cx))
                    .children(self.debug_hover_widget(editor, metrics.content_left(), metrics.char_width, window, cx))
                    .when(!inactive, |shifted| {
                        shifted
                            .children(self.editor_message_widget(editor, metrics.content_left(), metrics.char_width, window, cx))
                            .children(self.standalone_color_picker_widget(editor, metrics.content_left(), metrics.char_width, cx))
                            .children(self.ghost_text_lines(editor, metrics.content_left()))
                            .children(self.inline_completions_hints_widget(editor, metrics.content_left(), metrics.char_width, window, cx))
                            .children(self.inspect_tokens_widget(editor, metrics.content_left(), metrics.char_width, window))
                    }),
            )
            // Thread widgets are view zones: they show in an editor without the focus too (a diff's other side).
            .children(self.comment_thread_widgets(editor, metrics.content_left(), metrics.char_width, window, cx))
            // Overlay widgets: placed from the editor's right edge whichever side the minimap is on. Each code editor
            // keeps its own find widget open (findController.ts); the other overlays are the focused editor's.
            .children(self.find_widget(self.editors.viewport.width + metrics.content_left() + minimap_width, metrics.content_left(), minimap_width, window, cx))
            .when(!inactive, |area| {
                area.children(self.parameter_hints_widget(editor, metrics.content_left(), metrics.char_width, window, cx))
                    .children(self.lightbulb_widget(editor, metrics.content_left(), metrics.char_width, cx))
                    .children(self.paste_widget(editor, metrics.content_left(), metrics.char_width, cx))
                    .children(self.inline_progress_widget(editor, metrics.content_left(), metrics.char_width, cx))
                    .children(self.code_lens_widgets(editor, metrics.content_left(), metrics.char_width, cx))
                    .children(self.rename_widget(editor, metrics.content_left(), metrics.char_width, window, cx))
                    .children(self.suggest_widget(editor, metrics.content_left(), metrics.char_width, window, cx))
                    .children(self.find_options_widget(minimap_width, cx))
                    .children(self.floating_menu(editor, viewport.height, minimap_width, window, cx))
                    .children(self.whitespace_hint_widget(minimap_width, cx))
                    .children(self.define_keybinding_overlay(editor, self.editors.viewport.width + metrics.content_left() + minimap_width, viewport.height, window, cx))
                    .children(self.breakpoint_widget_element(editor, metrics.content_left(), window, cx))
                    .children(self.exception_widget_element(editor, metrics.content_left(), cx))
            })
            .children(self.editor_inset_elements(editor, metrics.content_left()))
            // Last: its hitbox is over the editor's own children, under a workbench overlay.
            .child(self.scrollbars_mouse_over_listener((group, model_id), cx).absolute().inset_0())
    }

    /// wordHighlighter.ts: `onDidBlurEditorWidget` stops the highlights once no code editor has the focus,
    /// `onDidFocusEditorText` runs the query from the selection again. The find widget, sticky lines and the
    /// unicode banner are inside the widget.
    pub fn watch_editor_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let focus = self.editor_focus.clone();
        let blurred_at = Rc::new(Cell::new(None));
        let deactivated = Rc::new(Cell::new(false));
        let blur = cx.on_focus_out(&focus, window, {
            let (blurred_at, deactivated) = (blurred_at.clone(), deactivated.clone());
            move |workbench, _, window, cx| {
                // GPUI reports a window deactivation as focus out; the DOM keeps the focus there, so the
                // reactivation is no focus event either.
                if workbench.editor_focus.contains_focused(window, cx) {
                    return deactivated.set(true);
                }
                workbench.editor_message_text_blurred(cx);
                if !(workbench.unicode_banner_focus.is_focused(window) && workbench.unicode_banner_shown()) {
                    workbench.editor_widget_blurred(&blurred_at, cx);
                }
            }
        });
        // The banner holding the focus goes when its action disables the highlights: the focus leaves the editor.
        let banner_blur = cx.on_blur(&self.unicode_banner_focus, window, {
            let blurred_at = blurred_at.clone();
            move |workbench, window, cx| {
                if window.is_window_active() && !workbench.editor_focus.contains_focused(window, cx) {
                    workbench.editor_widget_blurred(&blurred_at, cx);
                }
            }
        });
        let text_blur = cx.on_blur(&focus, window, |workbench, window, cx| {
            if window.is_window_active() {
                workbench.multicursor_text_focus_changed(false, window, cx);
                workbench.code_lens_text_focus_changed(false, cx);
            }
        });
        let text_focus = cx.on_focus(&focus, window, move |workbench, window, cx| {
            workbench.empty_editor_hint_text_focused(window, cx);
            let Some(editor) = workbench.editors.active_mut() else { return };
            // A picked command runs before GPUI reports the restored focus; upstream's delayed query, started on
            // focus, is cancelled by that command's edit (`onDidChangeModelContent` stops it).
            let returned = blurred_at.take().is_none_or(|(model, version)| model != editor.model_id || version == editor.text_model().version_id);
            let reactivated = deactivated.take();
            if returned && !reactivated {
                editor.refresh_highlights();
            }
            if !reactivated {
                workbench.multicursor_text_focus_changed(true, window, cx);
                workbench.code_lens_text_focus_changed(true, cx);
                // viewCursors.ts `onFocusChanged`: the blinking starts again with the cursors shown.
                *workbench.cursor_blink.borrow_mut() = cursor_blink::CursorBlink::default();
            }
            cx.notify();
        });
        let window_deactivated = cx.observe_window_activation(window, |workbench, window, cx| {
            if !window.is_window_active() {
                workbench.window_lost_focus_auto_save(cx);
            }
            workbench.trigger_code_actions_on_focus_change(cx);
        });
        self.editor_focus_listeners = vec![blur, banner_blur, text_blur, text_focus, window_deactivated];
    }

    /// wordHighlighter.ts `onDidFocusEditorText` when a quick input gives the focus back: its query runs 50 ms
    /// later (`runDelayer`) even when the picked command showed another quick input meanwhile, which GPUI never
    /// reports as a focus of the editor; an edit by the command replaces it (`_onPositionChanged` stops).
    pub(super) fn editor_text_focus_returned(&mut self, cx: &mut Context<Self>) {
        let Some(editor) = self.editors.active() else { return };
        let at = (editor.model_id, editor.text_model().version_id);
        cx.spawn(async move |workbench, cx| {
            cx.background_executor().timer(Duration::from_millis(50)).await;
            let _ = workbench.update(cx, |workbench, cx| {
                let Some(editor) = workbench.editors.active_mut().filter(|editor| (editor.model_id, editor.text_model().version_id) == at) else { return };
                editor.refresh_highlights();
                cx.notify();
            });
        })
        .detach();
    }

    fn editor_widget_blurred(&mut self, blurred_at: &Cell<Option<(u32, u32)>>, cx: &mut Context<Self>) {
        self.text_drag = None;
        if let Some(editor) = self.editors.active_mut() {
            editor.highlights.clear();
            blurred_at.set(Some((editor.model_id, editor.text_model().version_id)));
        }
        self.editor_blurred_auto_save(cx);
        self.suggest_editor_blurred(cx);
        self.cancel_parameter_hints(cx);
        self.rename_editor_blurred();
        cx.notify();
    }

    /// The text area got its size: the group's viewport follows it, which can clamp the scroll position and
    /// change the visible lines; the lines drawn widen the scrollable content (`ViewLines._ensureMaxLineWidth`).
    pub(super) fn editor_laid_out(&mut self, viewport: Viewport, minimap: Option<(MinimapLayoutInfo, f64)>, cx: &mut Context<Self>) {
        let resized = self.editors.viewport != viewport;
        let font_changed = (self.editors.viewport.char_width, self.editors.viewport.line_height) != (viewport.char_width, viewport.line_height);
        let minimap_changed = self.minimap.info != minimap;
        self.editors.viewport = viewport;
        self.minimap.info = minimap;
        // A reveal waits for the focused editor's layout, not one an unfocused editor drawn before it.
        let reveal = if self.editors.drawn.is_none() { self.editors.reveal_after_layout.take() } else { None };
        let rewrapped = self.configure_word_wrap();
        let editor = self.editors.active_mut().expect("laid out only with an editor open");
        if let Some(line) = reveal {
            editor.reveal_range(line, line, VerticalReveal::CenterIfOutsideViewport, viewport);
        }
        let scroll_width = editor.scroll_width(viewport);
        let visible_lines = editor.visible_lines(viewport);
        // viewLines.ts `_updateLineWidths`: with every line drawn, their widest is the content width.
        if font_changed || visible_lines == (0..editor.view_line_count()) {
            editor.forget_line_widths();
        }
        for view_line in visible_lines {
            let document = editor.document();
            let text = &document.lines[editor.model_line(view_line)];
            let tab_size = editor.document().indentation.tab_size;
            let width = match line_overflow(text, self.stop_rendering_line_after) {
                _ if editor.wraps() => editor.wrapped_line_width(view_line).unwrap_or_default() * viewport.char_width,
                None => editor.line_layout(editor.model_line(view_line)).width() * viewport.char_width,
                Some((limit, _, label)) => column_x(text, limit, tab_size) * viewport.char_width + show_more_width(&label, viewport.char_width),
            };
            drop(document);
            editor.saw_line_width(width);
        }
        let moved = editor.set_scroll(editor.scroll.top, editor.scroll.left, viewport);
        let widened = editor.scroll_width(viewport) != scroll_width;
        if (resized || moved) && self.editors.drawn.is_none() {
            self.host.send_visible_ranges(&self.editors);
        }
        if resized || moved || widened || minimap_changed || rewrapped {
            cx.notify();
        }
    }

    /// The wheel scrolls the editor in `StandardWheelEvent` units: 40 browser pixels or one line per notch. With
    /// `editor.mouseWheelZoom`, Cmd or Ctrl without Shift and Alt zooms instead (mouseHandler.ts).
    pub(super) fn editor_wheel(&mut self, event: &ScrollWheelEvent, _: &mut Window, cx: &mut Context<Self>) {
        let (x, y) = match event.delta {
            ScrollDelta::Pixels(delta) => (f32::from(delta.x) / 40., f32::from(delta.y) / 40.),
            ScrollDelta::Lines(delta) => (delta.x, delta.y),
        };
        if self.active_editor_option(&MOUSE_WHEEL_ZOOM) {
            let modifiers = event.modifiers;
            let has_zoom_modifiers = (modifiers.platform || modifiers.control) && !modifiers.shift && !modifiers.alt;
            // ScrollDelta::Lines is AppKit's imprecise delta of a mouse wheel, `isPhysicalMouseWheel` upstream.
            let physical_wheel = matches!(event.delta, ScrollDelta::Lines(_));
            let level = self.editor_zoom.level();
            if self.editor_zoom.wheel(y, physical_wheel, has_zoom_modifiers, Instant::now()) {
                cx.stop_propagation();
                if self.editor_zoom.level() != level {
                    cx.notify();
                }
                return;
            }
        }
        let fast = event.modifiers.alt;
        let scrolled = match event.delta {
            // scrollableElement.ts: only a physical mouse wheel scrolls smoothly.
            ScrollDelta::Lines(_) => self.scroll_smoothly(cx, |editor, viewport| {
                editor.scroll_by_wheel(x, y, fast, viewport);
            }),
            ScrollDelta::Pixels(_) => {
                let viewport = self.editors.viewport;
                self.editors.active_mut().expect("the text area scrolls only with an editor open").scroll_by_wheel(x, y, fast, viewport)
            }
        };
        if scrolled {
            cx.stop_propagation();
            self.editor_scrolled(cx);
        }
    }

    /// scrollableElement.ts `_onDidScroll`: the scrollbars show, and the host hears of new visible lines.
    pub(super) fn editor_scrolled(&mut self, cx: &mut Context<Self>) {
        self.sync_locked_scroll();
        self.host.send_visible_ranges(&self.editors);
        self.reveal_scrollbars(cx);
        self.minimap_scrolled(cx);
        self.code_lens_scrolled(cx);
        self.inlay_hints_scrolled(cx);
        self.debug_inline_values_scrolled(cx);
        self.notify_editor_view(cx);
    }

    /// `_reveal`: the scrollbars fade in, and fade out 500ms later unless the pointer is over the editor.
    fn reveal_scrollbars(&mut self, cx: &mut Context<Self>) {
        self.scrollbars.set_shown(true, Instant::now());
        self.scrollbars.hide_timer = None;
        if !self.scrollbars.mouse_over && self.scrollbars.drag.is_none() {
            self.scrollbars.hide_timer = Some(cx.spawn(async move |workbench, cx| {
                cx.background_executor().timer(SCROLLBAR_HIDE_TIMEOUT).await;
                workbench.update(cx, |workbench, cx| workbench.hide_scrollbars(cx)).ok();
            }));
        }
        self.notify_editor_view(cx);
    }

    /// `_hide`: kept while the pointer is over the editor or drags a slider.
    fn hide_scrollbars(&mut self, cx: &mut Context<Self>) {
        if !self.scrollbars.mouse_over && self.scrollbars.drag.is_none() {
            self.scrollbars.set_shown(false, Instant::now());
            self.notify_editor_view(cx);
        }
    }

    /// editorScrollbar.ts `listenOnDomNode: viewDomNode`: mouseover and mouseleave of the whole editor, minimap, sticky
    /// scroll and scrollbars included; their hitboxes block the text area's `on_hover`.
    fn scrollbars_mouse_over_listener(&self, editor: (u32, u32), cx: &mut Context<Self>) -> gpui::Canvas<gpui::Hitbox> {
        let workbench = cx.entity();
        canvas(
            |bounds, window, _| window.insert_hitbox(bounds, gpui::HitboxBehavior::Normal),
            move |_, hitbox, window, _| {
                let moved = workbench.clone();
                window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
                    if phase == DispatchPhase::Bubble {
                        moved.update(cx, |workbench, cx| workbench.set_scrollbars_mouse_over(editor, hitbox.should_handle_scroll(window), cx));
                    }
                });
                window.on_mouse_event(move |_: &gpui::MouseExitEvent, phase, _, cx| {
                    if phase == DispatchPhase::Bubble {
                        workbench.update(cx, |workbench, cx| workbench.set_scrollbars_mouse_over(editor, false, cx));
                    }
                });
            },
        )
    }

    /// One state for every code editor: a leave counts only for the editor the pointer was over.
    fn set_scrollbars_mouse_over(&mut self, editor: (u32, u32), over: bool, cx: &mut Context<Self>) {
        match (over, self.scrollbars.pointer_editor) {
            (true, Some(current)) if current == editor => {}
            (true, _) => {
                self.scrollbars.pointer_editor = Some(editor);
                self.scrollbars.mouse_over = true;
                self.reveal_scrollbars(cx);
            }
            (false, Some(current)) if current == editor => {
                self.scrollbars.pointer_editor = None;
                self.scrollbars.mouse_over = false;
                self.hide_scrollbars(cx);
            }
            (false, _) => {}
        }
    }

    /// The sliders over the overview ruler and along the bottom (scrollbars.css, abstractScrollbar.ts): a press
    /// on a track centers the slider on the pointer, then the slider follows the pointer until release.
    fn scrollbars_canvas(&self, editor: &OpenEditor, metrics: EditorMetrics, cx: &mut Context<Self>) -> gpui::Canvas<Vec<(Hitbox, Bounds<Pixels>, Axis)>> {
        let viewport = self.editors.viewport;
        let mut vertical = editor.vertical_scrollbar(viewport);
        let mut horizontal = editor.horizontal_scrollbar(viewport);
        // testResultsOutput.ts `commonEditorOptions`: `scrollbar.vertical` hidden in a result message's editor;
        // callStackWidget.ts `editorOptions`: both hidden in a call stack frame's.
        vertical.needed &= editor.document().scheme != crate::testing::TEST_DATA_SCHEME;
        let call_stack_frame = self.call_stack_frame(editor).is_some();
        vertical.needed &= !call_stack_frame;
        horizontal.needed &= !call_stack_frame;
        let bars = [(Axis::Vertical, vertical), (Axis::Horizontal, horizontal)];
        let opacity = self.scrollbars.opacity(Instant::now());
        let shown = self.scrollbars.shown;
        let drag = self.scrollbars.drag;
        let faded = |key: &str| {
            let color = self.color(key);
            Rgba { a: color.a * opacity, ..color }
        };
        let colors = [faded("scrollbarSlider.background"), faded("scrollbarSlider.hoverBackground"), faded("scrollbarSlider.activeBackground")];
        let workbench = cx.entity();
        canvas(
            move |bounds, window, _| {
                let mut tracks = Vec::new();
                for (axis, bar) in bars {
                    let track = match axis {
                        Axis::Vertical => Bounds::new(point(bounds.right() - px(VERTICAL_SCROLLBAR_WIDTH), bounds.top()), size(px(VERTICAL_SCROLLBAR_WIDTH), px(bar.track))),
                        Axis::Horizontal => Bounds::new(point(bounds.left() + px(metrics.content_left()), bounds.bottom() - px(HORIZONTAL_SCROLLBAR_HEIGHT)), size(px(bar.track), px(HORIZONTAL_SCROLLBAR_HEIGHT))),
                    };
                    // An invisible scrollbar takes no pointer events (.invisible { pointer-events: none }).
                    if bar.needed && shown {
                        tracks.push((window.insert_hitbox(track, HitboxBehavior::BlockMouse), track, axis));
                    }
                }
                tracks
            },
            move |_, tracks, window, _| {
                let mut sliders = Vec::new();
                for (axis, bar) in bars {
                    let Some((_, track, _)) = tracks.iter().find(|(_, _, track_axis)| *track_axis == axis) else { continue };
                    let slider = slider_bounds(*track, axis, bar);
                    let color = match drag {
                        Some(drag) if drag.axis == axis => colors[2],
                        _ if slider.contains(&window.mouse_position()) => colors[1],
                        _ => colors[0],
                    };
                    // roundedCorners.css: Modern UI rounds the scrollbar sliders 4px.
                    window.paint_quad(fill(slider, color).corner_radii(px(super::list_scroll::SLIDER_RADIUS)));
                    sliders.push(slider);
                }
                let hovered_slider = move |window: &Window| sliders.iter().any(|slider| slider.contains(&window.mouse_position()));
                let painted_hover = hovered_slider(window);
                let workbench_moved = workbench.clone();
                window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
                    if phase != DispatchPhase::Bubble {
                        return;
                    }
                    if let Some(drag) = drag {
                        let along = if drag.axis == Axis::Vertical { event.position.y } else { event.position.x };
                        workbench_moved.update(cx, |workbench, cx| workbench.drag_slider(drag, f32::from(along), cx));
                    } else if hovered_slider(window) != painted_hover {
                        window.refresh();
                    }
                });
                let workbench_released = workbench.clone();
                window.on_mouse_event(move |event: &MouseUpEvent, phase, _, cx| {
                    if phase == DispatchPhase::Bubble && event.button == MouseButton::Left && drag.is_some() {
                        workbench_released.update(cx, |workbench, cx| {
                            workbench.scrollbars.drag = None;
                            workbench.hide_scrollbars(cx);
                        });
                    }
                });
                let workbench = workbench.clone();
                window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
                    if phase != DispatchPhase::Bubble {
                        return;
                    }
                    let Some((_, track, axis)) = tracks.iter().find(|(hitbox, _, _)| hitbox.is_hovered(window)) else { return };
                    let (track, axis) = (*track, *axis);
                    // The vertical scrollbar's column shows the menu itself, shown or not.
                    if event.button == MouseButton::Right && axis == Axis::Horizontal {
                        cx.stop_propagation();
                        workbench.update(cx, |workbench, cx| workbench.show_scrollbar_context_menu(event.position, window, cx));
                        return;
                    }
                    if event.button != MouseButton::Left {
                        return;
                    }
                    let along = |position: Point<Pixels>| f32::from(if axis == Axis::Vertical { position.y - track.top() } else { position.x - track.left() });
                    let offset = along(event.position);
                    cx.stop_propagation();
                    workbench.update(cx, |workbench, cx| workbench.press_scrollbar(axis, offset, f32::from(if axis == Axis::Vertical { event.position.y } else { event.position.x }), cx));
                });
            },
        )
    }

    /// A press on a track: outside the slider it jumps to center the slider there, then a drag starts.
    fn press_scrollbar(&mut self, axis: Axis, offset: f32, pointer: f32, cx: &mut Context<Self>) {
        let viewport = self.editors.viewport;
        let editor = self.editors.active_mut().expect("scrollbars show only with an editor open");
        let bar = scrollbar(editor, axis, viewport);
        let on_slider = (bar.slider_position..bar.slider_position + bar.slider_size).contains(&offset);
        if !on_slider {
            set_axis_scroll(editor, axis, bar.position_at(offset), viewport);
        }
        let state = scrollbar(editor, axis, viewport);
        self.scrollbars.drag = Some(SliderDrag { axis, pointer, state });
        self.editor_scrolled(cx);
    }

    fn drag_slider(&mut self, drag: SliderDrag, pointer: f32, cx: &mut Context<Self>) {
        let viewport = self.editors.viewport;
        let editor = self.editors.active_mut().expect("scrollbars show only with an editor open");
        if set_axis_scroll(editor, drag.axis, drag.state.position_dragged(pointer - drag.pointer), viewport) {
            self.editor_scrolled(cx);
        }
    }

    /// scrollDecoration.css: `box-shadow: var(--vscode-scrollbar-shadow) 0 6px 6px -6px inset` over a 6px strip,
    /// which leaves the blurred top edge only: alpha falls off as a Gaussian with sigma 3px, half strength at the edge.
    pub(super) fn scroll_shadow(&self) -> gpui::Canvas<()> {
        let shadow = self.theme.color("scrollbar.shadow");
        canvas(
            |_, _, _| {},
            move |bounds, _, window, _| {
                let Some(shadow) = shadow else { return };
                let scale = window.scale_factor();
                let rows = (SCROLL_SHADOW_HEIGHT * scale) as usize;
                for row in 0..rows {
                    let y = (row as f32 + 0.5) / scale;
                    let alpha = shadow.a * 0.5 * erfc(y / (3. * std::f32::consts::SQRT_2));
                    let origin = bounds.origin + point(px(0.), px(row as f32 / scale));
                    window.paint_quad(fill(Bounds::new(origin, size(bounds.size.width, px(1. / scale))), Rgba { a: alpha, ..shadow }));
                }
            },
        )
    }

    pub(super) fn editor_lines(&self, editor: &OpenEditor, range: Range<usize>, metrics: EditorMetrics, window: &mut Window, cx: &mut Context<Self>) -> Vec<Div> {
        // Of a notebook's cells, the playground's snippets, a (multi) diff's sides or a merge editor's inputs and result
        // only the focused one has the code editor's focus.
        let in_cell = editor.document().scheme == crate::notebook::CELL_SCHEME;
        let stacked = in_cell || editor.document().scheme == super::walkthrough_part::SNIPPET_SCHEME || self.editors.active_diff().is_some() || self.editors.active_multi_diff().is_some() || self.editors.active_merge().is_some();
        let focused = !self.editor_groups.drawing_inactive && self.editor_focus.is_focused(window) && (!stacked || self.editors.active().is_some_and(|active| std::ptr::eq(active, editor)));
        let layout = cursor_blink::Layout {
            width: self.editors.viewport.width,
            height: self.editors.viewport.height,
            content_left: metrics.content_left(),
            char_width: metrics.char_width,
            line_height: metrics.line_height,
            pixel_ratio: window.scale_factor(),
        };
        let cursor_look = if focused { self.focused_cursor_look(editor, layout, window, cx) } else { None };
        if !range.is_empty() {
            editor.document().tokens.tokenize_viewport(&editor.document().lines, editor.segment(range.start).line, editor.segment(range.end - 1).line);
        }
        let scroll_left = editor.scroll.left;
        let selections = &editor.selections;
        let tab_size = editor.document().indentation.tab_size;
        let primary_line = editor.selection().head.line;
        // currentLineHighlight.ts: every cursor's line, drawn only while all selections are empty.
        let all_empty = selections.iter().all(|selection| selection.is_empty());
        let bracket_matches = self.bracket_matches(editor);
        // Past the cap there are no marks, the banner shows instead.
        let unicode = self.unicode_highlights(editor).filter(|(_, highlights)| !highlights.has_more);
        let bracket_box = (self.theme.color("editorBracketMatch.background"), self.theme.color("editorBracketMatch.border"));
        // indentGuides.ts: the guide around the primary cursor with `editor.guides.highlightActiveIndentation`.
        let highlight_active_indentation = self.editor_option(editor, &GUIDES_HIGHLIGHT_ACTIVE_INDENTATION);
        let active_guide = (highlight_active_indentation != json!(false)).then(|| crate::editor::active_indent_guide(&editor.text_model().guides, editor.selections[0].head.line));
        let indentation = self.editor_option(editor, &GUIDES_INDENTATION);
        let (guides_start, bracket_guides) = self.bracket_guides(editor, range.clone());
        // indentGuides.ts `_maxIndentLeft`: with word wrap no guide starts past the wrapping column.
        let max_indent_left = editor.word_wrap.options().map(|options| options.column as f32 * metrics.char_width);
        let bracket_guide_colors = if bracket_guides.iter().all(Vec::is_empty) { Vec::new() } else { self.bracket_guide_colors() };
        let colors = LineColors {
            number: self.color("editorLineNumber.foreground"),
            active_number: self.color("editorLineNumber.activeForeground"),
            text: self.color("editor.foreground"),
            // currentLineHighlight.ts theming participant: the border only without a visible background, or when the theme sets it.
            line_background: self.theme.color(if focused { "editor.lineHighlightBackground" } else { "editor.inactiveLineHighlightBackground" }),
            line_border: match self.theme.color("editor.lineHighlightBackground").is_none_or(|color| color.a == 0.) || self.theme.defines("editor.lineHighlightBorder") {
                true => self.theme.color("editor.lineHighlightBorder"),
                false => None,
            },
            selection_highlight: self.theme.color("editor.selectionHighlightBackground"),
            selection_highlight_border: self.theme.color("editor.selectionHighlightBorder"),
            guide: self.color("editorIndentGuide.background1"),
            active_guide: self.color("editorIndentGuide.activeBackground1"),
            cursor: self.color("editorCursor.foreground"),
            primary_cursor: self.color("editorMultiCursor.primary.foreground"),
            secondary_cursor: self.color("editorMultiCursor.secondary.foreground"),
            selection: self.color(if focused { "editor.selectionBackground" } else { "editor.inactiveSelectionBackground" }),
        };
        // currentLineHighlight.css: high contrast draws the exact border 1px wide.
        let line_border_width = if self.theme.kind.is_high_contrast() { 1. } else { 2. };
        // editorOptions.ts: overtype input mode draws `overtypeCursorStyle`, else `cursorStyle`; only block and line are drawn.
        let cursor_style = match (self.overtype, editor.cursor_style_override) {
            (false, Some(style)) => json!(style),
            (overtype, _) => json!(self.editor_option(editor, if overtype { &OVERTYPE_CURSOR_STYLE } else { &CURSOR_STYLE })),
        };
        let block_cursor = cursor_style == json!("block");
        let cursor_background = self.theme.color("editorCursor.background");
        // outputView.ts `OutputEditor.getConfigurationOverrides`: renderLineHighlight none.
        // cellEditorOptions.ts: renderLineHighlightOnlyWhenFocus.
        // simpleEditorOptions.ts: an interactive input's is none.
        let line_highlight = editor.document().scheme != crate::output::OUTPUT_SCHEME && (!in_cell || focused) && !self.is_interactive_input(editor) && !is_comment_input(editor);
        let char_width = metrics.char_width;
        let fold_controls = self.fold_controls.opacity(Instant::now());
        let settings_file = self.edits_settings_file(editor);
        let edit_setting_line = settings_file.then(|| self.edit_setting_line(editor)).flatten();
        let fold_control_color = self.color("editorGutter.foldingControlForeground");
        let fold_background = self.color("editor.foldBackground");
        let coverage = self.coverage_lines(&editor.document().uri(), editor.document().lines.len(), cx);
        let fold_placeholder = self.color("editor.foldPlaceholderForeground");
        let rounded_selection = self.editor_option(editor, &ROUNDED_SELECTION);
        let render_whitespace = self.editor_option(editor, &RENDER_WHITESPACE);
        let render_control_characters = self.editor_option(editor, &RENDER_CONTROL_CHARACTERS);
        let whitespace_color = self.color("editorWhitespace.foreground");
        let line_height = metrics.line_height;
        // selections.css: high contrast themes square the corners.
        let selection_radius = if self.theme.kind.is_high_contrast() { 0. } else { 3. };
        let editor_background = self.color("editor.background");
        let view_line_count = editor.view_line_count();
        // viewLines.ts linesVisibleRangesForRange: a selected line break is one typicalHalfwidthCharacterWidth wide.
        // With word wrap each view line gets the part of the selection on its segment, in the view line's x.
        let selection_range = |index: usize, selection: Selection, view_line: usize| {
            let segment = editor.segment(view_line);
            let text = &editor.document().lines[segment.line];
            let (start, end, line_break) = selected_columns(selection, segment.line, text)?;
            let line_break = line_break && segment.last;
            let (start, end) = (start.max(segment.start), end.min(segment.end));
            if start > end || (start == end && !line_break && !segment.first) {
                return None;
            }
            let layout = editor.line_layout(segment.line);
            let (left, right) = editor.selection_x(index, &layout, segment.line, start, end);
            let segment_left = segment.indent as f32 - segment.start_x(&layout);
            Some(((segment_left + left) * char_width, (segment_left + right) * char_width + if line_break { char_width } else { 0. }))
        };
        let mut fold_starts = HashMap::new();
        for (range, decoration) in editor.folding.regions.ranges().iter().zip(editor.folding.decorations()) {
            if decoration != FoldDecoration::Hidden {
                fold_starts.insert(range.start - 1, decoration == FoldDecoration::Collapsed);
            }
        }
        let drawn = range
            .map(|view_line| {
                let segment = editor.segment(view_line);
                let index = segment.line;
                let model_id = editor.model_id;
                let text = &editor.document().lines[index];
                let layout = editor.line_layout(index);
                // The x of the segment's first char in the model line's x, which the line's decorations use.
                let shift = (segment.start_x(&layout) - segment.indent as f32) * char_width;
                let collapsed = fold_starts.get(&index).copied().filter(|_| segment.first);
                // lineNumbers.ts marks only the primary cursor's line active.
                let number = div()
                    .w(px(metrics.line_numbers_width))
                    .flex_none()
                    .text_right()
                    .text_color(if index == primary_line { colors.active_number } else { colors.number })
                    // lineNumbers.css `.relative-current-line-number`: the cursor's line number aligns left.
                    .when(metrics.line_numbers == LineNumbers::Relative && index == primary_line, |number| number.text_left())
                    // testing.css `.coverage-deco-gutter::before`: the fill sits under the number.
                    .when_some(coverage.get(&index).and_then(|line| self.coverage_gutter(*line)), |number, gutter| number.relative().child(gutter))
                    .on_mouse_move(cx.listener(move |workbench, _: &MouseMoveEvent, _, _| workbench.testing.coverage.line_numbers_target = Some(model_id)))
                    .children(line_number_label(metrics.line_numbers, index, primary_line, editor.document().lines.len()).filter(|_| segment.first));
                let mut current_line = div().absolute().inset_0();
                if line_highlight && all_empty && (0..selections.len()).any(|cursor_index| editor.head_view_line(cursor_index) == view_line) {
                    if let Some(background) = colors.line_background {
                        current_line = current_line.bg(background);
                    }
                    if let Some(border) = colors.line_border {
                        current_line = current_line.border(px(line_border_width)).border_color(border);
                    }
                }
                // The text scrolls left under the fixed margin and current line border.
                let mut content = div().absolute().top_0().bottom_0().right_0().left(px(-scroll_left - shift));
                // selections.ts: inner corner pieces of every selection go before the rest (issue #77777).
                let mut inner_corners = Vec::new();
                let mut pieces = Vec::new();
                for (index, selection) in selections.iter().enumerate() {
                    let in_line_x = |(left, right): (f32, f32)| (left + shift, right + shift);
                    let Some((left, right)) = selection_range(index, *selection, view_line).map(in_line_x) else { continue };
                    let above = view_line.checked_sub(1).and_then(|above| selection_range(index, *selection, above)).map(in_line_x);
                    let below = if view_line + 1 < view_line_count { selection_range(index, *selection, view_line + 1).map(in_line_x) } else { None };
                    // `hasMultipleSelections` insets the first line by 1px at the top, the last (not also first) at the bottom.
                    let multiple = selections.len() > 1;
                    let top = if multiple && above.is_none() { 1. } else { 0. };
                    let bottom = if multiple && above.is_some() && below.is_none() { 1. } else { 0. };
                    let piece = |left: f32, width: f32| div().absolute().top(px(top)).bottom(px(bottom)).left(px(left)).w(px(width));
                    let mut rest = piece(left, right - left).bg(colors.selection);
                    if rounded_selection {
                        let corners = selection_corners(above, (left, right), below, char_width / 4.);
                        let radius = px(selection_radius);
                        if corners.start_top == Corner::Intern || corners.start_bottom == Corner::Intern {
                            let mut background = piece(left - ROUNDED_PIECE_WIDTH, ROUNDED_PIECE_WIDTH).bg(editor_background);
                            if corners.start_top == Corner::Intern {
                                background = background.rounded_tr(radius);
                            }
                            if corners.start_bottom == Corner::Intern {
                                background = background.rounded_br(radius);
                            }
                            inner_corners.push(piece(left - ROUNDED_PIECE_WIDTH, ROUNDED_PIECE_WIDTH).bg(colors.selection));
                            inner_corners.push(background);
                        }
                        if corners.end_top == Corner::Intern || corners.end_bottom == Corner::Intern {
                            let mut background = piece(right, ROUNDED_PIECE_WIDTH).bg(editor_background);
                            if corners.end_top == Corner::Intern {
                                background = background.rounded_tl(radius);
                            }
                            if corners.end_bottom == Corner::Intern {
                                background = background.rounded_bl(radius);
                            }
                            inner_corners.push(piece(right, ROUNDED_PIECE_WIDTH).bg(colors.selection));
                            inner_corners.push(background);
                        }
                        if corners.start_top == Corner::Extern {
                            rest = rest.rounded_tl(radius);
                        }
                        if corners.start_bottom == Corner::Extern {
                            rest = rest.rounded_bl(radius);
                        }
                        if corners.end_top == Corner::Extern {
                            rest = rest.rounded_tr(radius);
                        }
                        if corners.end_bottom == Corner::Extern {
                            rest = rest.rounded_br(radius);
                        }
                    }
                    pieces.push(rest);
                }
                content = content.children(inner_corners).children(pieces);
                let line_bracket_guides = editor.view_bracket_guides(view_line, bracket_guides.get(index.wrapping_sub(guides_start)).map_or(&[][..], Vec::as_slice));
                // indentGuides.ts: a visible column counts from the view line's left, past a wrap too.
                for level in (0..editor.view_indent_guides(view_line)).filter(|_| indentation) {
                    let indent_column = level * editor.document().indentation.indent_size() + 1;
                    let x = (indent_column - 1) as f32 * char_width;
                    if max_indent_left.is_some_and(|max| x > max) {
                        break;
                    }
                    // `getGuidesByLine`: a vertical bracket pair guide at the indent's column takes its place.
                    let next_bracket_guide = line_bracket_guides.iter().find(|guide| guide.visible_column >= Some(indent_column));
                    if next_bracket_guide.is_some_and(|guide| guide.visible_column == Some(indent_column) && guide.horizontal.is_none()) {
                        continue;
                    }
                    let active = (highlight_active_indentation == json!("always") || line_bracket_guides.is_empty())
                        && active_guide.as_ref().is_some_and(|(lines, indent)| lines.contains(&index) && level + 1 == *indent);
                    let guide = div().absolute().top_0().left(px(x + shift)).w(px(1.)).h_full().bg(if active { colors.active_guide } else { colors.guide });
                    content = content.child(guide.debug_selector(|| format!("indent-guide-{model_id}-{view_line}-{level}")));
                }
                for guide in line_bracket_guides.iter().filter(|_| !bracket_guide_colors.is_empty()) {
                    let left = match guide.visible_column {
                        Some(column) => (column - 1) as f32 * char_width + shift,
                        None => layout.x(guide.column) * char_width,
                    };
                    if max_indent_left.is_some_and(|max| left - shift > max) {
                        break;
                    }
                    let (inactive_color, active_color) = bracket_guide_colors[guide.level % 30 % bracket_guide_colors.len()];
                    let color = if guide.active { active_color } else { inactive_color };
                    // indentGuides.ts theming: `.vertical` is a 1px inset box shadow, `.horizontal-top`/`-bottom` a 1px border.
                    let line = match guide.horizontal {
                        None => div().top_0().h_full().w(px(1.)),
                        Some((top, end)) => {
                            let width = (layout.x(end) * char_width - left).max(0.);
                            let line = div().h(px(1.)).w(px(width));
                            if top { line.top_0() } else { line.bottom_0() }
                        }
                    };
                    content = content.child(line.absolute().left(px(left)).bg(color).debug_selector(|| format!("bracket-pair-guide-{model_id}-{index}")));
                }
                // foldingDecorations.ts COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION: .folded-background over the whole line.
                if collapsed == Some(true) {
                    content = content.child(div().absolute().inset_0().left(px(scroll_left)).bg(fold_background));
                }
                let (find_whole_lines, find_matches, find_colors) = self.find_line_decorations(editor, index, char_width, scroll_left);
                content = content.children(find_whole_lines);
                content = content.children(self.diff_line_decorations(editor, index, char_width, scroll_left));
                content = content.children(self.merge_line_decorations(editor, index, char_width, scroll_left));
                content = content.children(self.text_decoration_boxes(editor, index, scroll_left, &layout, char_width));
                content = content.children(self.coverage_inline_boxes(editor, index, &layout, char_width));
                content = content.children(self.search_editor_line_decorations(editor, index, char_width));
                // anchorSelect.css: `.selection-anchor` is a 2px #007ACC bar in every theme, under the word highlights.
                if let Some(anchor) = editor.selection_anchor
                    && anchor.line == index
                {
                    let left = layout.x(anchor.column) * char_width;
                    content = content.child(div().absolute().top_0().h_full().left(px(left)).w(px(2.)).bg(rgb(0x007ACC)));
                }
                // highlightDecorations.css: `.focused .selectionHighlight`, drawn under the word highlights.
                let selection_highlights = self.find.selection_highlights.as_ref().filter(|_| focused).map_or(&[][..], |(_, ranges)| ranges);
                let first = selection_highlights.partition_point(|range| range.end.line < index);
                let on_line = selection_highlights[first..].iter().take_while(|range| range.start.line <= index);
                for (start, end, _) in on_line.filter_map(|range| selected_columns(Selection { anchor: range.start, head: range.end }, index, text)) {
                    let (start, end) = layout.range(start, end);
                    let (start, end) = (start * char_width, end * char_width);
                    let mut highlight = div().absolute().top_0().h_full().left(px(start)).w(px(end - start));
                    if let Some(background) = colors.selection_highlight {
                        highlight = highlight.bg(background);
                    }
                    // Accepted platform difference: GPUI has no dotted border, so the high contrast selection highlight is dashed.
                    if let Some(border) = colors.selection_highlight_border {
                        highlight = highlight.border_1().border_dashed().border_color(border);
                    }
                    content = content.child(highlight);
                }
                // wordHighlighter.ts stops on blur: a notebook cell or playground snippet without the focus has none.
                for (_, columns) in editor.highlights.iter().filter(|(line, _)| *line == index && (!stacked || focused)) {
                    let (start, end) = layout.range(columns.start, columns.end);
                    let (start, end) = (start * char_width, end * char_width);
                    let mut highlight = div().absolute().top_0().h_full().left(px(start)).w(px(end - start));
                    let (word_background, word_border) = self.word_highlight_colors(index, columns);
                    if let Some(background) = word_background {
                        highlight = highlight.bg(background);
                    }
                    // Accepted platform difference: GPUI has no dotted border, so the high contrast word highlight is dashed.
                    if let Some(border) = word_border {
                        highlight = highlight.border_1().border_dashed().border_color(border);
                    }
                    content = content.child(highlight);
                }
                content = content.children(self.content_hover_highlight(editor, index, char_width));
                content = content.children(self.debug_hover_highlight(editor, index, char_width));
                content = content.children(self.code_action_highlights(editor, index, char_width));
                content = content.children(self.snippet_placeholder_highlights(editor, index, char_width));
                content = content.children(self.symbol_highlight(editor, index, char_width));
                content = content.children(self.definition_link_cursor(editor, index, char_width));
                // bracketMatching.css .bracket-match: background and a 1px border inside the bracket's box.
                for (_, bytes) in bracket_matches.iter().flat_map(|(pair, _)| pair).filter(|(line, _)| *line == index) {
                    let (start, end) = layout.range(text[..bytes.start].chars().count(), text[..bytes.end].chars().count());
                    let (start, end) = (start * char_width, end * char_width);
                    let mut bracket = div().absolute().top_0().h_full().left(px(start)).w(px(end - start));
                    if let Some(background) = bracket_box.0 {
                        bracket = bracket.bg(background);
                    }
                    if let Some(border) = bracket_box.1 {
                        bracket = bracket.border_1().border_color(border);
                    }
                    content = content.child(bracket);
                }
                content = content.children(self.unicode_highlight_boxes(editor, index, unicode.as_ref(), char_width));
                content = content.children(self.keybinding_mark_boxes(editor, index, |column| layout.x(column) * char_width));
                content = content.children(self.marker_line_decorations(editor, index, char_width, |column| layout.x(column) * char_width));
                content = content.children(find_matches);
                content = content.children(self.linked_editing_empty_boxes(editor, index, |column| layout.x(column) * char_width));
                content = content.children(self.comment_range_highlights(editor, index, char_width, window));
                // inPlaceReplace.css: .valueSetReplacement only in the light theme (`.monaco-editor.vs`), a 2px outline.
                if let Some((_, line, columns)) = &editor.value_set_replacement
                    && *line == index
                    && self.theme.kind == ThemeKind::Light
                    && let Some(border) = bracket_box.1
                {
                    let (start, end) = layout.range(columns.start, columns.end);
                    let (start, end) = (start * char_width, end * char_width);
                    content = content.child(div().absolute().top(px(-2.)).bottom(px(-2.)).left(px(start - 2.)).w(px(end - start + 4.)).border_2().border_color(border));
                }
                let selected: Vec<_> = selections
                    .iter()
                    .filter_map(|selection| selected_columns(*selection, index, text))
                    .filter(|(start, end, _)| start < end)
                    .map(|(start, end, _)| start..end)
                    .collect();
                let rendered_len = line_overflow(text, self.stop_rendering_line_after).map_or(text.chars().count(), |(limit, _, _)| limit);
                let marks = whitespace_marks(text, render_whitespace, &selected, rendered_len);
                if !marks.is_empty() {
                    let marks: Vec<_> = marks.into_iter().map(|mark| (layout.char_x(mark) * char_width, text.chars().nth(mark) == Some('\t'))).collect();
                    content = content.child(whitespace_canvas(marks, char_width, line_height, whitespace_color));
                }
                let mut highlights = editor.document().tokens.highlights(&self.theme, &self.languages, &editor.document().lines, index, tab_size);
                // bracketMatching.ts theming participant: `editorBracketMatch.foreground` over the bracket pair colors.
                if let Some(color) = self.theme.color("editorBracketMatch.foreground") {
                    let expanded = |byte: usize| expand_tabs(&text[..byte], tab_size).len();
                    let matched = bracket_matches.iter().flat_map(|(pair, _)| pair).filter(|(line, _)| *line == index);
                    let colored: Vec<_> = matched.map(|(_, bytes)| (expanded(bytes.start)..expanded(bytes.end), gpui::Hsla::from(color))).collect();
                    highlights = crate::syntax::overlay_colors(highlights, &colored);
                }
                let highlights = super::semantic_tokens::overlay_semantic_styles(highlights, &self.semantic_token_styles(editor, index, tab_size));
                let highlights = gpui::combine_highlights(highlights, self.link_styles(editor, index, tab_size));
                let highlights = gpui::combine_highlights(highlights, self.linked_editing_styles(editor, index, tab_size));
                let runs = gpui::combine_highlights(gpui::combine_highlights(highlights, self.text_decoration_styles(editor, index, tab_size)), find_colors);
                let runs = gpui::combine_highlights(runs, self.marker_text_styles(editor, index, tab_size));
                let runs = gpui::combine_highlights(runs, self.definition_link_styles(editor, index, tab_size));
                let mut show_more = None;
                match line_overflow(text, self.stop_rendering_line_after) {
                    None => content = content.children(injected_text_view::line_text_pieces(runs.collect(), text, &layout, tab_size, char_width)),
                    Some((limit, byte, label)) => {
                        // viewLineRenderer.ts: the first `stopRenderingLineAfter` chars, then the .mtkoverflow "Show more" span.
                        let rendered = expand_tabs(&text[..byte], tab_size);
                        let len = rendered.len();
                        let runs: Vec<_> = runs.filter(|(range, _)| range.start < len).map(|(range, style)| (range.start..range.end.min(len), style)).collect();
                        content = content.child(div().absolute().top_0().left_0().whitespace_nowrap().child(StyledText::new(rendered).with_highlights(runs)));
                        let foreground = self.theme.color("button.foreground").unwrap_or(colors.text);
                        let span = div()
                            .absolute()
                            .left(px(layout.x(limit) * char_width - scroll_left))
                            .w(px(show_more_width(&label, char_width)))
                            .h_full()
                            .rounded(px(2.))
                            .border_1()
                            // An unset `--vscode-contrastBorder` leaves the border `currentColor`.
                            .border_color(self.theme.color("contrastBorder").unwrap_or(foreground))
                            .bg(self.theme.color("button.background").unwrap_or(editor_background))
                            .text_color(foreground)
                            .when_some(self.theme.color("button.hoverBackground"), |span, hover| span.hover(move |span| span.bg(hover)))
                            .cursor_pointer()
                            .child(div().absolute().top(px(2.)).left(px(4.)).line_height(px(metrics.line_height)).whitespace_nowrap().child(label));
                        // The inline span's box reaches 3px above the line and 2px below it (reference pixels), past the
                        // line's own clip, so it gets a clip of its own over the text area.
                        show_more = Some(div().absolute().left(px(metrics.content_left())).right_0().top(px(-3.)).h(px(24.)).overflow_hidden().child(span));
                    }
                }
                content = content.children(self.injected_text_elements(editor, index, &layout, &metrics, cx));
                if render_control_characters {
                    content = content.children(self.control_character_boxes(text, &layout, tab_size, char_width, rendered_len));
                }
                // folding.css .inline-folded:after: an ellipsis 0.2em after the line's last char.
                if collapsed == Some(true) && segment.last {
                    let end = layout.width() * char_width + 0.2 * metrics.font_size;
                    content = content.child(div().absolute().top_0().left(px(end)).text_color(fold_placeholder).cursor_pointer().child("\u{22EF}"));
                }
                for (cursor_index, selection) in selections.iter().enumerate().filter(|(cursor_index, _)| cursor_look.is_some() && editor.head_view_line(*cursor_index) == view_line) {
                    let look = cursor_look.expect("filtered above");
                    // viewCursors.css `.cursor-expand`: scaleY about the line's middle.
                    let (top, height) = (metrics.line_height * (1. - look.scale_y) / 2., metrics.line_height * look.scale_y);
                    let color = match (selections.len(), cursor_index) {
                        (1, _) => colors.cursor,
                        (_, 0) => colors.primary_cursor,
                        _ => colors.secondary_cursor,
                    };
                    // A cursor past the cut is not drawn.
                    if self.stop_rendering_line_after.is_some_and(|limit| selection.head.column > limit) {
                        continue;
                    }
                    let x = layout.cursor_x(selection.head.column, editor.head_past_injections(cursor_index)) * char_width;
                    if block_cursor {
                        // viewCursor.ts block: one char wide (a tab too), the char under it in `editorCursor.background`,
                        // else the caret color's opposite (viewCursors.ts).
                        let under = text.chars().nth(selection.head.column).filter(|ch| *ch != '\t').map(String::from).unwrap_or_default();
                        let text_color = cursor_background.unwrap_or(gpui::Rgba { r: 1. - color.r, g: 1. - color.g, b: 1. - color.b, a: color.a });
                        content = content.child(div().absolute().top(px(top)).left(px(x)).w(px(char_width)).h(px(height)).opacity(look.opacity).bg(color).text_color(text_color).child(under));
                        continue;
                    }
                    // viewCursor.ts: a 2px cursor sits 1px left, between the chars.
                    let left = if x >= 1. { x - 1. } else { x };
                    content = content.child(div().absolute().top(px(top)).left(px(left)).w(px(2.)).h(px(height)).opacity(look.opacity).bg(color));
                }
                if let Some(target) = self.text_drag.as_ref().and_then(|drag| drag.target).or(self.drop_target()).filter(|target| target.line == index) {
                    content = content.child(self.drop_target_marker(layout.x(target.column) * char_width));
                }
                let segment_columns = (segment.start_x(&layout), if segment.last { f32::MAX } else { segment.end_x(&layout) });
                // The click handlers take the model text's visible column; the injected text's x is left out here.
                let layout_x_at = move |workbench: &Workbench, x: gpui::Pixels| ((f32::from(x) - workbench.text_area_left.get() - metrics.content_left() + scroll_left + shift) / char_width).clamp(segment_columns.0, segment_columns.1);
                let visible_at = move |workbench: &Workbench, x: gpui::Pixels| {
                    let x = layout_x_at(workbench, x);
                    workbench.editors.active().map_or(x, |editor| editor.line_layout(index).model_visible(x))
                };
                let content = div()
                    .relative()
                    .flex_1()
                    .h_full()
                    .overflow_hidden()
                    .text_color(colors.text)
                    .children(self.stack_frame_line(editor, index))
                    .child(current_line)
                    .child(self.wrapped_segment_clip(content, segment, shift, scroll_left, char_width))
                    .children(self.word_wrap_indicator(editor, segment, scroll_left, char_width))
                    .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                        // The empty area under the lines (CONTENT_EMPTY) has its own press.
                        cx.stop_propagation();
                        window.focus(&workbench.editor_focus, cx);
                        let modifiers = event.modifiers;
                        let visible = visible_at(workbench, event.position.x);
                        workbench.definition_link_mouse_down(index, modifiers);
                        if workbench.start_text_drag(index, visible, modifiers, event.click_count) {
                            return;
                        }
                        workbench.selecting_text = Some(MouseDown { count: event.click_count, on_gutter: false });
                        workbench.fold_mouse_down = workbench.at_line_end(index, visible).then_some((index, false));
                        workbench.click_text(index, visible, modifiers, modifiers.shift, event.click_count, cx);
                        let layout_x = layout_x_at(workbench, event.position.x);
                        if let Some(editor) = workbench.editors.active_mut().filter(|_| event.click_count == 1) {
                            editor.click_past_injections(index, layout_x);
                        }
                        workbench.keep_click_at_row_end(view_line, visible);
                        workbench.show_long_line(index, visible, char_width, cx);
                    }))
                    .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                        cx.stop_propagation();
                        let visible = visible_at(workbench, event.position.x);
                        workbench.show_editor_context_menu(index, visible, event.position, window, cx);
                        workbench.show_long_line(index, visible, char_width, cx);
                    }))
                    .on_mouse_down(MouseButton::Middle, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                        window.focus(&workbench.editor_focus, cx);
                        workbench.selecting_text = Some(MouseDown { count: event.click_count, on_gutter: false });
                        let visible = visible_at(workbench, event.position.x);
                        workbench.fold_mouse_down = workbench.at_line_end(index, visible).then_some((index, false));
                        workbench.column_select_text(index, visible, event.modifiers.shift, cx);
                        workbench.show_long_line(index, visible, char_width, cx);
                    }))
                    .on_mouse_up(MouseButton::Left, cx.listener(move |workbench, event: &MouseUpEvent, window, cx| {
                        if !workbench.row_editor_active(model_id) {
                            return;
                        }
                        let visible = visible_at(workbench, event.position.x);
                        if workbench.text_drag.is_some() {
                            return workbench.drop_text(index, visible, event.modifiers, cx);
                        }
                        if workbench.links_mouse_up(index, visible, event.modifiers, false, window, cx) {
                            return;
                        }
                        if workbench.at_line_end(index, visible) {
                            workbench.release_fold_click(index, false, event.modifiers, false, cx);
                        }
                        workbench.search_editor_mouse_up(index, visible, event.click_count, window, cx);
                        workbench.definition_link_mouse_up(index, visible, event.modifiers, event.click_count, window, cx);
                    }))
                    .on_mouse_up(MouseButton::Middle, cx.listener(move |workbench, event: &MouseUpEvent, window, cx| {
                        if !workbench.row_editor_active(model_id) {
                            return;
                        }
                        if workbench.links_mouse_up(index, visible_at(workbench, event.position.x), event.modifiers, true, window, cx) {
                            return;
                        }
                        if workbench.at_line_end(index, visible_at(workbench, event.position.x)) {
                            workbench.release_fold_click(index, false, event.modifiers, true, cx);
                        }
                    }))
                    .on_drag_move(cx.listener(move |workbench, event: &DragMoveEvent<ExternalPaths>, _, cx| {
                        if event.bounds.contains(&event.event.position) && workbench.row_editor_active(model_id) {
                            workbench.drag_files_over_text(Some((index, visible_at(workbench, event.event.position.x))), event.event.modifiers.shift, cx);
                        }
                    }))
                    .on_drop(cx.listener(move |workbench, paths: &ExternalPaths, window, cx| {
                        if !workbench.row_editor_active(model_id) {
                            return;
                        }
                        let visible = visible_at(workbench, window.mouse_position().x);
                        workbench.drop_files_on_text(index, visible, paths.paths().to_vec(), window, cx);
                    }))
                    .on_mouse_move(cx.listener(move |workbench, event: &MouseMoveEvent, _, cx| {
                        workbench.commenting_hover_moved(Some((model_id, index)), cx);
                        if !workbench.row_editor_active(model_id) {
                            return;
                        }
                        workbench.editor_message_mouse_moved(index, cx);
                        let hover_x = layout_x_at(workbench, event.position.x);
                        let hovered = workbench.editors.active().map_or(hover_x, |editor| editor.line_layout(index).model_x(hover_x));
                        workbench.content_hover.row_target = Some((index, hovered));
                        workbench.definition_link_mouse_moved(index, visible_at(workbench, event.position.x), event.modifiers, event.pressed_button.is_some(), cx);
                        match event.pressed_button {
                            Some(MouseButton::Left) if workbench.text_drag.is_some() => workbench.drag_text(index, visible_at(workbench, event.position.x), event.modifiers.alt, cx),
                            Some(MouseButton::Left) if workbench.selecting_text.is_some() && workbench.drag_scrolling.is_none() => {
                                let visible = visible_at(workbench, event.position.x);
                                workbench.drag_select(index, visible, event.modifiers, cx);
                                workbench.keep_click_at_row_end(view_line, visible);
                            }
                            Some(MouseButton::Middle) if workbench.selecting_text.is_some() => workbench.column_select_text(index, visible_at(workbench, event.position.x), true, cx),
                            _ => {}
                        }
                    }));
                div()
                    .w_full()
                    .h(px(metrics.line_height))
                    .relative()
                    .flex()
                    .when(settings_file, |row| row.on_mouse_move(cx.listener(move |workbench, _: &MouseMoveEvent, window, cx| workbench.edit_setting_mouse_moved(model_id, index, window, cx))))
                    .children(self.diff_margin(editor, index, metrics))
                    .children(self.quick_diff_glyph(editor, index, metrics, cx))
                    .children(self.comment_glyph(editor, index, metrics, cx))
                    .child(
                        div()
                            .relative()
                            .flex_none()
                            .on_mouse_move(cx.listener(|workbench, _: &MouseMoveEvent, _, _| workbench.debug_hover_glyph_margin_moved()))
                            .child(self.breakpoint_glyph_margin(editor, index, metrics.glyph_margin_width(), metrics.line_height, cx))
                            .children(self.lightbulb_glyph(editor, index, metrics.line_height, cx).map(|lightbulb| lightbulb.absolute().top_0().left_0()))
                            .children(self.edit_setting_glyph(editor, index, metrics.glyph_margin_width(), metrics.line_height, edit_setting_line, cx)),
                    )
                    .child(self.gutter_mouse(number, index, cx))
                    .child(self.fold_control(index, collapsed, metrics, fold_control_color, fold_controls, cx))
                    .child(content)
                    .children(show_more)
            })
            .collect();
        schedule_background_tokenization(&editor.model, cx);
        drawn
    }

    /// The line decorations lane with the folding control of a region starting on `index`, collapsed or not
    /// (`folding-collapsed` stays visible, `folding-expanded` shows while the pointer is over the margin). A press
    /// 4px or more into the lane and a release on the same line toggle the region (folding.ts `onEditorMouseDown`).
    fn fold_control(&self, index: usize, collapsed: Option<bool>, metrics: EditorMetrics, color: Rgba, hover_opacity: f32, cx: &mut Context<Self>) -> Div {
        let lane_x = move |workbench: &Workbench, x: Pixels| f32::from(x) - workbench.text_area_left.get() - metrics.glyph_margin_width() - metrics.line_numbers_width;
        let press = move |workbench: &mut Workbench, event: &MouseDownEvent| {
            workbench.fold_mouse_down = (lane_x(workbench, event.position.x) >= 4.).then_some((index, true));
        };
        let mut lane = div()
            .w(px(metrics.decorations_width))
            .flex_none()
            .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, _, _| press(workbench, event)))
            .on_mouse_down(MouseButton::Middle, cx.listener(move |workbench, event: &MouseDownEvent, _, _| press(workbench, event)))
            .on_mouse_up(MouseButton::Left, cx.listener(move |workbench, event: &MouseUpEvent, _, cx| workbench.release_fold_click(index, true, event.modifiers, false, cx)))
            .on_mouse_up(MouseButton::Middle, cx.listener(move |workbench, event: &MouseUpEvent, _, cx| workbench.release_fold_click(index, true, event.modifiers, true, cx)));
        let Some(collapsed) = collapsed.filter(|_| self.editors.active_diff().is_none()) else { return lane };
        let (name, opacity) = if collapsed { ("chevron-right", 1.) } else { ("chevron-down", hover_opacity) };
        // folding.css: the icon box is the lane's width, 2px right, the glyph at 140% of the editor font size.
        let icon = self.icon(name, metrics.line_height, 1.4 * metrics.font_size, Rgba { a: color.a * opacity, ..color });
        // review.css `.inline-comment`: the folding icons move 11px right of the comment glyphs.
        let left = if metrics.decorations_width > DECORATIONS_WIDTH { 13. } else { 2. };
        lane = lane.child(div().w(px(DECORATIONS_WIDTH)).ml(px(left)).h(px(metrics.line_height)).flex().justify_center().cursor_pointer().child(icon));
        lane
    }

    /// Whether `visible` falls at or after the end of `line`, as a click on a collapsed region's ellipsis does.
    fn at_line_end(&self, line: usize, visible: f32) -> bool {
        let editor = self.editors.active().expect("text is clickable only with an editor open");
        let text = &editor.document().lines[line];
        editor.folding.has_hidden() && column_at_visible(text, visible, editor.document().indentation.tab_size) == text.chars().count()
    }

    /// folding.ts `onEditorMouseUp`: a release on the line pressed toggles its region, with Alt the regions around
    /// it, with Shift or the middle button the ones inside it first; then the line's start is revealed.
    fn release_fold_click(&mut self, line: usize, icon: bool, modifiers: gpui::Modifiers, middle: bool, cx: &mut Context<Self>) {
        if self.fold_mouse_down.take() != Some((line, icon)) {
            return;
        }
        let editor = self.editors.active_mut().expect("folding controls show only with an editor open");
        let before = (editor.selections.clone(), editor.folding.hidden().to_vec());
        if editor.click_fold_control(line, icon, modifiers.alt, middle || modifiers.shift) {
            let moved = editor.selections != before.0;
            self.cursor_position_changed(Cursor { moved, source: "mouse", reveal: Reveal::CenterIfOutside(Position::new(line, 0)) }, cx);
            self.folds_changed(&before.1);
        }
    }

    /// The view lines changed with the folds: the host hears the new visible ranges (`onDidScrollChange` fires
    /// for the new scroll height).
    fn folds_changed(&mut self, hidden_before: &[Range<usize>]) {
        let viewport = self.editors.viewport;
        let editor = self.editors.active_mut().expect("folds change in the active editor");
        if editor.folding.hidden() != hidden_before {
            editor.set_scroll(editor.scroll.top, editor.scroll.left, viewport);
            self.host.send_visible_ranges(&self.editors);
        }
    }

    /// indentGuides.ts `getGuidesByLine`: the bracket pair guides of the model lines of view lines `range`, from
    /// the first; none with `editor.guides.bracketPairs` false.
    fn bracket_guides(&self, editor: &OpenEditor, range: Range<usize>) -> (usize, Vec<Vec<crate::brackets::BracketGuide>>) {
        use crate::brackets::{BracketGuideOptions, HorizontalGuides};
        let bracket_pairs = self.editor_option(editor, &GUIDES_BRACKET_PAIRS);
        if bracket_pairs == json!(false) || range.is_empty() {
            return (0, Vec::new());
        }
        let horizontal = match self.editor_option(editor, &GUIDES_BRACKET_PAIRS_HORIZONTAL) {
            Value::Bool(true) => HorizontalGuides::Enabled,
            Value::String(value) if value == "active" => HorizontalGuides::EnabledForActive,
            _ => HorizontalGuides::Disabled,
        };
        let options = BracketGuideOptions { include_inactive: bracket_pairs == json!(true), highlight_active: self.editor_option(editor, &GUIDES_HIGHLIGHT_ACTIVE_BRACKET_PAIR), horizontal };
        let document = editor.document();
        let start = editor.segment(range.start).line;
        // indentGuides.ts asks for one line past the visible ones.
        let end = (editor.segment(range.end - 1).line + 2).min(document.lines.len());
        let cursor = editor.selections[0].head;
        let guides = document.tokens.bracket_guides(&self.theme, &self.languages, &document.lines, &document.language_id, document.indentation.tab_size, start..end, Some((cursor.line, cursor.column)), &options);
        (start, guides)
    }

    /// indentGuides.ts theming participant: per bracket color its guide color (`editorBracketPairGuide.background`,
    /// else the bracket color at 30%) and active guide color, the levels without both left out.
    fn bracket_guide_colors(&self) -> Vec<(Rgba, Rgba)> {
        let opaque = |color: Option<Rgba>| color.filter(|color| color.a > 0.);
        let mut colors = Vec::new();
        for n in 1..=6 {
            let bracket = self.theme.color(&format!("editorBracketHighlight.foreground{n}"));
            let guide = opaque(opaque(self.theme.color(&format!("editorBracketPairGuide.background{n}"))).or(bracket.map(|color| Rgba { a: color.a * 0.3, ..color })));
            let active = opaque(opaque(self.theme.color(&format!("editorBracketPairGuide.activeBackground{n}"))).or(bracket));
            if let (Some(guide), Some(active)) = (guide, active) {
                colors.push((guide, active));
            }
        }
        colors
    }

    /// bracketMatching.ts `_recomputeBrackets`: the brackets matched at each empty cursor, none past 100 selections;
    /// `editor.matchBrackets` "near" leaves out the enclosing pairs, "never" matches nothing.
    fn bracket_matches(&self, editor: &OpenEditor) -> Vec<([BracketRange; 2], bool)> {
        let overrides = config::configuration::Overrides { resource: Some(&editor.document().path), override_identifier: Some(&editor.document().language_id) };
        let match_brackets = self.settings.lock().unwrap().get_value(Some("editor.matchBrackets"), &overrides);
        if editor.selections.len() > 100 || match_brackets == Some(json!("never")) {
            return Vec::new();
        }
        let near = match_brackets == Some(json!("near"));
        let lines = &editor.document().lines;
        let mut matches = Vec::new();
        for selection in editor.selections.iter().filter(|selection| selection.is_empty()) {
            let found = editor.document().tokens.bracket_match(&self.theme, &self.languages, lines, (selection.head.line, selection.head.column));
            matches.extend(found.filter(|(_, touching)| *touching || !near));
        }
        matches
    }

    /// longLinesHelper.ts: a press on the text at or past the cut renders every line whole from then on.
    fn show_long_line(&mut self, line: usize, visible: f32, char_width: f32, cx: &mut Context<Self>) {
        let editor = self.editors.active().expect("text is clickable only with an editor open");
        let text = &editor.document().lines[line];
        let Some((limit, _, label)) = line_overflow(text, self.stop_rendering_line_after) else { return };
        let tab_size = editor.document().indentation.tab_size;
        // The "Show more" span is text too; a press right of it is empty content.
        let span_end = column_x(text, limit, tab_size) + show_more_width(&label, char_width) / char_width;
        if column_at_visible(text, visible, tab_size) + 1 >= limit && visible < span_end {
            self.stop_rendering_line_after = None;
            cx.notify();
        }
    }

    /// The model line and visible column under `position` in the active editor laid out with its text area at
    /// `origin`, as that line's row takes it (view zones and wrapped segments counted), kept inside the text; and
    /// whether `position` is on the text, not the margin or below the last line.
    pub(super) fn active_editor_text_at(&self, origin: gpui::Point<Pixels>, position: gpui::Point<Pixels>, window: &mut Window) -> (usize, f32, bool) {
        let editor = self.editors.active().expect("a laid out code editor is active");
        let metrics = self.editor_metrics(editor, window);
        let x = f32::from(position.x - origin.x) - metrics.content_left();
        let view_line = editor.view_line_at(f32::from(position.y - origin.y) + editor.scroll.top, self.editors.viewport);
        let last_line = editor.view_line_count() - 1;
        let segment = editor.segment(view_line.min(last_line));
        let layout = editor.line_layout(segment.line);
        let (start, end) = (segment.start_x(&layout), if segment.last { f32::MAX } else { segment.end_x(&layout) });
        let column = ((x + editor.scroll.left) / metrics.char_width + start - segment.indent as f32).clamp(start, end);
        (segment.line, layout.model_visible(column), x >= 0. && view_line <= last_line)
    }

    /// A press for the active editor drawn by `embedded_code_editor` with its text box at `origin`: the line and
    /// column under the pointer take it as the line's own press would.
    pub(super) fn click_active_editor_at(&mut self, origin: gpui::Point<Pixels>, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        self.code_editor_focus_moved();
        if self.editors.active().is_none() {
            return;
        }
        let (line, visible, _) = self.active_editor_text_at(origin, event.position, window);
        self.click_text(line, visible, event.modifiers, event.modifiers.shift, event.click_count, cx);
        cx.notify();
    }

    /// Whether a row of editor `model_id` belongs to the focused editor, the one its listeners act on. Another code
    /// editor's rows take a press only, which focuses it first; until then the gesture is the focused editor's.
    fn row_editor_active(&self, model_id: u32) -> bool {
        self.editors.active().is_some_and(|editor| editor.model_id == model_id)
    }

    /// A move over the lines with the button of a selecting press held.
    pub(super) fn drag_select(&mut self, line: usize, visible: f32, modifiers: gpui::Modifiers, cx: &mut Context<Self>) {
        let position = self.text_position(line, visible);
        self.drag_select_at(position, visible, modifiers, true, cx);
    }

    /// viewController.ts `dispatchMouse` in selection mode with the press's click count, by lines from a gutter press.
    pub(super) fn drag_select_at(&mut self, position: Position, visible: f32, modifiers: gpui::Modifiers, reveal: bool, cx: &mut Context<Self>) {
        let Some(down) = self.selecting_text else { return };
        match down.on_gutter {
            true => self.gutter_line_select(position.line, modifiers, true, reveal, cx),
            false => self.dispatch_mouse(position, visible, modifiers, true, down.count, reveal, cx),
        }
    }

    pub(super) fn click_text(&mut self, line: usize, visible: f32, modifiers: gpui::Modifiers, select: bool, click_count: usize, cx: &mut Context<Self>) {
        let position = self.text_position(line, visible);
        self.dispatch_mouse(position, visible, modifiers, select, click_count, true, cx);
    }

    /// Half of a `suppressMouseDown` view zone: a press there focuses the editor and starts a mouse-down operation at
    /// `(line, visible)` (mouseHandler.ts `_onMouseDown`).
    fn zone_press_half(&self, (line, visible): (usize, f32), cx: &mut Context<Self>) -> Div {
        div().absolute().left_0().right_0().h_1_2().on_mouse_down(
            MouseButton::Left,
            cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                cx.stop_propagation();
                window.focus(&workbench.editor_focus, cx);
                workbench.selecting_text = Some(MouseDown { count: event.click_count, on_gutter: false });
                workbench.click_text(line, visible, event.modifiers, event.modifiers.shift, event.click_count, cx);
            }),
        )
    }

    /// The position a press at visible column `visible` of `line` takes.
    pub(super) fn text_position(&self, line: usize, visible: f32) -> Position {
        let editor = self.editors.active().expect("text is clickable only with an editor open");
        let document = editor.document();
        let text = &document.lines[line];
        let tab_size = document.indentation.tab_size;
        let column = match line_overflow(text, self.stop_rendering_line_after) {
            // The reference puts a press on the "Show more" span before the last drawn char.
            Some((limit, _, _)) if visible >= column_x(text, limit, tab_size) => limit - 1,
            _ => column_at_visible(text, visible, tab_size),
        };
        Position::new(line, column)
    }

    /// viewController.ts `dispatchMouse` on the text, `select` being its selection mode (Shift, or a drag): a click
    /// places the cursor or extends the selection, a double click selects the word (with
    /// `editor.doubleClickSelectsBlock`, the inside of brackets or a string touching the press), a triple click the
    /// line, four clicks everything; their drags go on by words or lines. With Alt (`multiCursorModifier`) a click
    /// adds or removes a cursor, and a drag or a double or triple click works on the cursor added last; with Shift
    /// too it selects a column. `visible` is the pointer's visible column (`mouseColumn`).
    #[allow(clippy::too_many_arguments)]
    fn dispatch_mouse(&mut self, position: Position, visible: f32, modifiers: gpui::Modifiers, select: bool, click_count: usize, reveal: bool, cx: &mut Context<Self>) {
        let column_selection = self.active_editor_option(&COLUMN_SELECTION);
        let selects_block = self.active_editor_option(&DOUBLE_CLICK_SELECTS_BLOCK);
        let classifier = self.word_classifier(false).expect("text is clickable only with an editor open");
        // viewController.ts `_hasMulticursorModifier` and `_hasNonMulticursorModifier`; `ctrlCmd` is Cmd on macOS.
        let (multi_cursor, non_multi_cursor) = match self.multi_cursor_modifier_is_cmd() {
            true => (modifiers.platform, modifiers.control || modifiers.alt),
            false => (modifiers.alt, modifiers.control || modifiers.platform),
        };
        let editor = self.editors.active_mut().expect("text is clickable only with an editor open");
        let line = position.line;
        let before = editor.selections.clone();
        if multi_cursor && click_count < 4 {
            if click_count == 1 && non_multi_cursor {
                return;
            }
            // Only the column selection reveals; the other `_lastCursor*` commands and `createCursor` do not.
            let shown = match click_count {
                2 => {
                    editor.last_cursor_word_select(&classifier, position);
                    Reveal::Nothing
                }
                3 => {
                    editor.last_cursor_line_select(position, select);
                    Reveal::Nothing
                }
                _ if modifiers.shift => editor.column_select_to_pointer(line, mouse_column(visible), true),
                _ if select => {
                    editor.last_cursor_move_to_select(position);
                    Reveal::Nothing
                }
                _ => {
                    editor.toggle_cursor(position);
                    Reveal::Nothing
                }
            };
            let moved = editor.selections != before;
            self.cursor_position_changed(Cursor { moved, source: "mouse", reveal: if reveal { shown } else { Reveal::Nothing } }, cx);
            return;
        }
        match click_count {
            4.. => editor.select_all(),
            3 => editor.line_select(position, select),
            2 if select => editor.word_select(&classifier, position, true),
            2 => match selects_block.then(|| editor.double_click_block(&self.languages, position)).flatten() {
                Some(block) => editor.set_selections(vec![block]),
                None => editor.word_select(&classifier, position, false),
            },
            _ if select && (column_selection || modifiers.alt) => {
                let shown = editor.column_select_to_pointer(line, mouse_column(visible), true);
                let moved = editor.selections != before;
                self.cursor_position_changed(Cursor { moved, source: "mouse", reveal: if reveal { shown } else { Reveal::Nothing } }, cx);
                return;
            }
            _ if select => editor.move_to_select(position),
            _ => editor.move_to(position, false),
        }
        let moved = editor.selections != before;
        // `NavigationCommandRevealType.None` leaves the scroll.
        let reveal = if reveal { Reveal::All } else { Reveal::Nothing };
        self.cursor_position_changed(Cursor { moved, source: "mouse", reveal }, cx);
    }

    /// `editor.multiCursorModifier`: any value but `ctrlCmd` is Alt (editorOptions.ts `_multiCursorModifierFromString`).
    pub(super) fn multi_cursor_modifier_is_cmd(&self) -> bool {
        self.active_editor_option(&MULTI_CURSOR_MODIFIER) == "ctrlCmd"
    }

    /// The middle button selects a column (`editor.scrollOnMiddleClick` off): from the pointer, or with
    /// Shift or while dragging from where the last column selection started.
    fn column_select_text(&mut self, line: usize, visible: f32, extend: bool, cx: &mut Context<Self>) {
        let editor = self.editors.active_mut().expect("text is clickable only with an editor open");
        let before = editor.selections.clone();
        let reveal = editor.column_select_to_pointer(line, mouse_column(visible), extend);
        let moved = editor.selections != before;
        self.cursor_position_changed(Cursor { moved, source: "mouse", reveal }, cx);
    }

    /// Runs an editor command; false when its precondition does not hold.
    pub(super) fn run_editor_command(&mut self, command: &str, source: &str, cx: &mut Context<Self>) -> bool {
        let viewport = self.editors.viewport;
        let editor = self.editors.active_mut().expect("editor commands run on the active editor");
        let before = editor.selections.clone();
        let hidden_before = editor.folding.hidden().to_vec();
        let Some(reveal) = commands::run(editor, command, viewport) else {
            return false;
        };
        let moved = editor.selections != before;
        self.cursor_position_changed(Cursor { moved, source, reveal }, cx);
        self.folds_changed(&hidden_before);
        true
    }

    /// decorationsOverviewRuler.ts `_render`, in device pixels: word highlights, matched brackets and find matches in the center lane, the cursor
    /// across all lanes, then the 1px border on the left and top edges.
    /// cellEditorOptions.ts and simpleEditorOptions.ts: no minimap and no overview ruler lanes in a cell or input editor.
    fn in_cell_editor(&self, editor: &OpenEditor) -> bool {
        editor.document().scheme == crate::notebook::CELL_SCHEME || self.is_interactive_input(editor)
    }

    /// diffEditorEditors.ts `_adjustOptionsForSubEditor` turns the minimap off in a diff's sides, mergeEditor.ts
    /// `applyOptions` in a merge editor's, walkThroughPart.ts `getEditorOptions` in the playground's editors,
    /// simpleCommentEditor.ts in a comment's, referencesWidget.ts in the peek's, testResultsOutput.ts in a result message's.
    fn minimap_enabled(&self, editor: &OpenEditor) -> bool {
        let minimap_off_scheme = matches!(editor.document().scheme.as_str(), super::walkthrough_part::SNIPPET_SCHEME | crate::testing::TEST_DATA_SCHEME);
        self.editors.active_diff().is_none() && self.editors.active_multi_diff().is_none() && self.editors.active_merge().is_none() && !self.in_cell_editor(editor) && !minimap_off_scheme && !is_comment_input(editor) && editor.peek_preview.is_none() && self.minimap_settings(editor).enabled
    }

    /// `editorOverviewRuler.background`, else the tokens' default background while the minimap is on the right, so
    /// the ruler hides the minimap's line highlights under it.
    pub(super) fn overview_ruler_background(&self, editor: &OpenEditor) -> Option<Rgba> {
        self.theme.color("editorOverviewRuler.background").or_else(|| {
            (self.minimap_enabled(editor) && self.minimap_settings(editor).layout.side == crate::editor::minimap::MinimapSide::Right)
                .then(|| Rgba::try_from(self.theme.tokens.color_map()[2].as_str()).expect("the token color map holds hex colors"))
        })
    }

    fn overview_ruler(&self, editor: &OpenEditor) -> gpui::Canvas<()> {
        let line_count = editor.document().lines.len();
        let [(highlight_lines, highlight), (read_lines, read_color), (write_lines, write_color)] = self.word_highlight_ruler_lines(editor);
        let mut bracket_lines = Vec::new();
        for ([open, close], in_ruler) in self.bracket_matches(editor) {
            if in_ruler {
                bracket_lines.extend([(open.0, open.0), (close.0, close.0)]);
            }
        }
        let bracket_color = self.color("editorOverviewRuler.bracketMatchForeground");
        // decorationsOverviewRuler.ts onCursorStateChanged: the cursor colors, each at 70% opacity.
        let ruler_color = |key: &str| self.theme.color(key).map(|color| Rgba { a: color.a * 0.7, ..color });
        let mut cursors = Vec::new();
        for (index, selection) in editor.selections.iter().enumerate() {
            let key = match (editor.selections.len(), index) {
                (1, _) => "editorCursor.foreground",
                (_, 0) => "editorMultiCursor.primary.foreground",
                _ => "editorMultiCursor.secondary.foreground",
            };
            cursors.push((selection.head.line, ruler_color(key)));
        }
        cursors.sort_by_key(|(line, _)| *line);
        bracket_lines.sort();
        let find_color = self.color("editorOverviewRuler.findMatchForeground");
        let range_lines: Vec<(usize, usize)> = self.quick_access.goto_line.iter().filter_map(|state| state.highlight(editor.model_id)).collect();
        let range_color = self.color("editorOverviewRuler.rangeHighlightForeground");
        let (mut find_lines, mut current_find_lines) = (Vec::new(), Vec::new());
        for mark in self.find_marks(editor, self.editors.viewport.height) {
            let lines = if mark.current { &mut current_find_lines } else { &mut find_lines };
            lines.push((mark.range.start.line, mark.range.end.line));
        }
        let [(info_lines, info_color), (error_lines, error_color)] = self.keybinding_ruler_marks(editor);
        let [(marker_info_lines, marker_info), (marker_warning_lines, marker_warning), (marker_error_lines, marker_error)] = self.marker_ruler_lines(editor);
        let quick_diff = self.quick_diff_ruler_lines(editor);
        let [(resolved_lines, resolved), (unresolved_lines, unresolved), (draft_lines, draft)] = self.comment_ruler_lines(editor);
        let decoration_marks = self.text_decoration_ruler_marks(editor);
        // diffEditorItemTemplate.ts: a multi diff file's editor has `overviewRulerBorder: false` and `scrollBeyondLastLine: false`.
        let in_multi_diff = self.editors.multi_diff_side(editor.model_id).is_some();
        // simpleCommentEditor.ts, referencesWidget.ts and testResultsOutput.ts also set `scrollBeyondLastLine: false`.
        let scroll_beyond_last_line = !in_multi_diff && !is_comment_input(editor) && editor.peek_preview.is_none() && editor.document().scheme != crate::testing::TEST_DATA_SCHEME;
        let border = self.theme.color("editorOverviewRuler.border").filter(|_| !in_multi_diff);
        let background = self.overview_ruler_background(editor);
        let Viewport { top_whitespace, line_height, .. } = self.editors.viewport;
        let zones: Vec<(usize, f32)> = editor.view_zones.iter().map(|zone| (zone.anchor.map_or(0, |anchor| anchor.line + usize::from(!zone.before)), zone.height)).collect();
        let line_top = move |line: usize| top_whitespace + line as f32 * line_height + zones.iter().filter(|zone| zone.0 <= line).map(|zone| zone.1).sum::<f32>();
        canvas(
            |_, _, _| {},
            move |bounds, _, window, _| {
                let scale = window.scale_factor();
                let device = |value: f32| px(value / scale);
                let origin = bounds.origin;
                let paint = |window: &mut Window, x: f32, y: f32, width: f32, height: f32, color: Rgba| {
                    window.paint_quad(fill(Bounds::new(origin + point(device(x), device(y)), size(device(width), device(height))), color));
                };
                let canvas_width = (OVERVIEW_RULER_WIDTH * scale).floor();
                let canvas_height = (f32::from(bounds.size.height) * scale).floor();
                let viewport_height = f32::from(bounds.size.height);
                // scrollBeyondLastLine: the last line can scroll to the top of the viewport.
                let scroll_height = match scroll_beyond_last_line {
                    false => line_top(line_count).max(viewport_height),
                    true => line_top(line_count) + viewport_height - line_height,
                };
                let ratio = canvas_height / scroll_height;
                let lanes = RulerLanes::new(canvas_width);
                let min_height = (6. * scale).floor();
                if let Some(background) = background {
                    paint(window, 0., 0., canvas_width, canvas_height, background);
                }
                // In z-index order: Go to Line's range in all lanes, find matches at 10, the current match at 13.
                let center = (lanes.center_x, lanes.center_width);
                for (lines, color, (x, width)) in [
                    (&range_lines, range_color, (lanes.full_x, lanes.full_width)),
                    (&info_lines, info_color, (lanes.right_x, lanes.right_width)),
                    (&error_lines, error_color, (lanes.right_x, lanes.right_width)),
                    (&marker_info_lines, marker_info, (lanes.right_x, lanes.right_width)),
                    (&marker_warning_lines, marker_warning, (lanes.right_x, lanes.right_width)),
                    (&marker_error_lines, marker_error, (lanes.right_x, lanes.right_width)),
                    (&resolved_lines, resolved, center),
                    (&unresolved_lines, unresolved, center),
                    (&draft_lines, draft, center),
                    (&highlight_lines, highlight, center),
                    (&read_lines, read_color, center),
                    (&write_lines, write_color, center),
                    (&bracket_lines, bracket_color, center),
                    (&find_lines, find_color, center),
                    (&current_find_lines, find_color, center),
                ] {
                    let mut previous: Option<(f32, f32)> = None;
                    for (start_line, end_line) in lines {
                        let mut y1 = (line_top(*start_line) * ratio).floor();
                        let mut y2 = ((line_top(*end_line) + line_height) * ratio).floor();
                        if y2 - y1 < min_height {
                            let half = (min_height / 2.).floor();
                            // A multi diff side shorter than a mark (collapsed: 0px) still lays out its ruler.
                            let center = ((y1 + y2) / 2.).floor().clamp(half, (canvas_height - half).max(half));
                            (y1, y2) = (center - half, center + half);
                        }
                        previous = match previous {
                            Some((start, end)) if y1 <= end + 1. => Some((start, end.max(y2))),
                            Some((start, end)) => {
                                paint(window, x, start, width, end - start, color);
                                Some((y1, y2))
                            }
                            None => Some((y1, y2)),
                        };
                    }
                    if let Some((start, end)) = previous {
                        paint(window, x, start, width, end - start, color);
                    }
                }
                // Extension decorations' `overviewRulerColor` in their `OverviewRulerLane`.
                for (start, end, color, lane) in &decoration_marks {
                    let (x, width) = match lane {
                        1 => (lanes.full_x, lanes.center_x - lanes.full_x),
                        2 => center,
                        4 => (lanes.right_x, lanes.right_width),
                        _ => (lanes.full_x, lanes.full_width),
                    };
                    let y1 = (line_top(*start) * ratio).floor();
                    let y2 = ((line_top(*end) + line_height) * ratio).floor().max(y1 + min_height);
                    paint(window, x, y1, width, y2 - y1, *color);
                }
                // quickDiffDecorator.ts: `OverviewRulerLane.Left`, each change its own mark.
                for (start, end, color) in quick_diff.iter().filter_map(|(start, end, color)| Some((*start, *end, (*color)?))) {
                    let y1 = (line_top(start) * ratio).floor();
                    let y2 = ((line_top(end) + line_height) * ratio).floor().max(y1 + min_height);
                    paint(window, lanes.full_x, y1, lanes.center_x - lanes.full_x, y2 - y1, color);
                }
                // Cursors sorted by line; touching marks of one color paint as one.
                let height = (2. * scale).floor();
                let half = (height / 2.).floor();
                let mut previous: Option<(f32, f32, Rgba)> = None;
                for (line, color) in cursors.iter().filter_map(|(line, color)| Some((*line, (*color)?))) {
                    let y1 = (line_top(line) * ratio).floor().clamp(half, (canvas_height - half).max(half)) - half;
                    let y2 = y1 + height;
                    previous = match previous {
                        Some((start, end, previous_color)) if y1 <= end + 1. && previous_color == color => Some((start, end.max(y2), color)),
                        Some((start, end, previous_color)) => {
                            paint(window, lanes.full_x, start, lanes.full_width, end - start, previous_color);
                            Some((y1, y2, color))
                        }
                        None => Some((y1, y2, color)),
                    };
                }
                if let Some((start, end, color)) = previous {
                    paint(window, lanes.full_x, start, lanes.full_width, end - start, color);
                }
                // A 1px canvas stroke along x = 0 and y = 0 covers half of the first device column and row.
                if let Some(border) = border {
                    let half_covered = Rgba { a: border.a * 0.5, ..border };
                    paint(window, 0., 0., 1., canvas_height, half_covered);
                    paint(window, 1., 0., canvas_width - 1., 1., half_covered);
                }
            },
        )
        .w(px(OVERVIEW_RULER_WIDTH))
    }

    /// The column selection, tab focus and overtype mode items, then with an editor open its selection, indentation, encoding, end of line and
    /// language items (editorStatus.ts), right to left before the notifications bell.
    pub(super) fn editor_status_items(&self, foreground: Rgba, window: &Window, cx: &mut Context<Self>) -> Vec<(bool, gpui::AnyElement)> {
        // editorStatus.ts `updateColumnSelectionModeElement`, `updateTabFocusModeElement` and `updateInputModeElement`: prominent entries.
        let mut items = Vec::new();
        if self.editors.active().is_some() && self.active_editor_option(&COLUMN_SELECTION) {
            items.push(("Column Selection".to_string(), "Disable Column Selection Mode", "editor.action.toggleColumnSelection", "status.editor.columnSelectionMode"));
        }
        if self.tab_focus_mode() {
            items.push(("Tab Moves Focus".to_string(), "Disable Accessibility Mode", "editor.action.toggleTabFocusMode", "status.editor.tabFocusMode"));
        }
        if self.overtype {
            items.push(("OVR".to_string(), "Enable Insert Mode", "editor.action.toggleOvertypeInsertMode", "status.editor.inputMode"));
        }
        let prominent_items = items.len();
        // A webview, extension, walkthrough or multi diff editor shows no editor status entries.
        // editorStatusBar.ts `ActiveCellStatus`: a notebook editor shows its active cell (an interactive window's
        // focused input is its own editor).
        let interactive_input = self.editors.active().is_some_and(|active| self.is_interactive_input(active));
        // editorStatusBar.ts `NotebookIndentationStatus`: a notebook's indentation is an entry of its own.
        let notebook_indentation = |(label, tooltip, command, _)| (label, tooltip, command, "notebook.status.indentation");
        let notebook_cell = self.active_notebook_editor().filter(|_| !interactive_input).and_then(|editor| Some((editor.focus, self.host.notebooks.model(&editor.notebook)?.cells.len())));
        if let Some((input, cells)) = self.repl_input_status(window) {
            // Seen in the reference with the REPL input focused: its end of line only, between the indentation and
            // active cell entries of the list once it has a cell.
            let [_, _, _, eol, _] = Self::editor_status_entries(input, &self.languages);
            match cells {
                None => items.push(eol),
                Some((editor, index, count)) => {
                    if let Some(editor) = editor {
                        let [_, indentation, ..] = Self::editor_status_entries(editor, &self.languages);
                        items.push(notebook_indentation(indentation));
                    }
                    items.push(eol);
                    items.push((format!("Cell {} of {count}", index + 1), "", "notebook.centerActiveCell", "notebook.activeCellStatus"));
                }
            }
        } else if let Some((index, count)) = notebook_cell {
            // editorStatus.ts: the entries of the cell editor that was `activeCodeEditor` when the notebook editor
            // became active, then `NotebookIndentationStatus` of the active cell's editor, which a markdown preview
            // has not.
            let status_editor = self.notebook_status_editor().map(|editor| Self::editor_status_entries(editor, &self.languages));
            let [selection, indentation, encoding, eol, language] = match status_editor {
                Some(entries) => entries.map(Some),
                None => Default::default(),
            };
            items.extend(selection.into_iter().chain(indentation));
            if let Some(editor) = self.editors.active().filter(|editor| editor.document().scheme == crate::notebook::CELL_SCHEME && self.active_cell_has_editor()) {
                let [_, indentation, ..] = Self::editor_status_entries(editor, &self.languages);
                items.push(notebook_indentation(indentation));
            }
            items.extend(encoding.into_iter().chain(eol).chain(language));
            items.push((format!("Cell {} of {count}", index + 1), "", "notebook.centerActiveCell", "notebook.activeCellStatus"));
        } else if let Some((input, notebook)) = self.editors.active().filter(|_| interactive_input).zip(self.active_notebook_editor()) {
            // An interactive window with its input focused: the input's entries (its `activeCodeEditor`), with the
            // notebook's indentation and active cell entries once it has a cell.
            let [selection, indentation, encoding, eol, language] = Self::editor_status_entries(input, &self.languages);
            items.extend([selection, indentation]);
            let cells = self.host.notebooks.model(&notebook.notebook).map_or(0, |model| model.cells.len());
            let active_cell = self.host.notebooks.model(&notebook.notebook).and_then(|model| model.cells.get(notebook.focus)).and_then(|cell| self.cell_model(&cell.uri));
            if let Some(cell) = active_cell {
                let [_, cell_indentation, ..] = Self::editor_status_entries(cell, &self.languages);
                items.push(notebook_indentation(cell_indentation));
            }
            items.extend([encoding, eol, language]);
            if cells > 0 {
                items.push((format!("Cell {} of {cells}", notebook.focus.min(cells - 1) + 1), "", "notebook.centerActiveCell", "notebook.activeCellStatus"));
            }
        } else if let Some(editor) = self.editors.active().filter(|editor| editor.document().open_error.is_some()) {
            // editorStatus.ts `updateMetadataElement`: a binary editor's size; a placeholder has no text editor entries.
            if let Some(crate::editor::OpenError::Binary(size)) = editor.document().open_error {
                items.push((super::media_preview::format_size(size), "", "", "status.editor.info"));
            }
        } else if let Some(editor) = self.active_text_editor_control().filter(|editor| !self.shows_webview(editor) && !self.playground_active() && !matches!(editor.document().scheme.as_str(), super::extension_editor::EXTENSION_EDITOR_SCHEME | super::welcome_page::WALKTHROUGH_SCHEME | super::disassembly_view::DISASSEMBLY_SCHEME | MULTI_DIFF_EDITOR_SCHEME | TERMINAL_EDITOR_SCHEME)) {
            // WalkThroughPart has no `getControl`: its focused snippet gives the status bar no editor entries.
            let [selection, indentation, encoding, eol, language] = Self::editor_status_entries(editor, &self.languages);
            // `toEditorWithEncodingSupport` of a MultiDiffEditorInput or a MergeEditorInput is null: no encoding entry.
            let encoding = (self.editors.active_multi_diff().is_none() && self.editors.active_merge().is_none()).then_some(encoding);
            items.extend([selection, indentation].into_iter().chain(encoding).chain([eol, language]));
        }
        items.extend(self.media_preview_status_entries());
        let prominent = (self.theme.color("statusBarItem.prominentBackground"), self.color("statusBarItem.prominentForeground"));
        // A search editor's and a notebook editor's input support neither encodings nor language changes
        // (toEditorWithEncodingSupport, toEditorWithLanguageSupport).
        let fixed_input = self.editors.active().is_some_and(|editor| editor.document().scheme == SEARCH_EDITOR_SCHEME) || self.active_notebook_editor().is_some();
        let items: Vec<_> = items.into_iter().filter(|(_, _, command, _)| !fixed_input || !matches!(*command, "workbench.action.editor.changeEncoding" | "workbench.action.editor.changeLanguageMode")).collect();
        let language_index = items.iter().position(|(_, _, command, _)| *command == "workbench.action.editor.changeLanguageMode");
        // languageStatus.ts: the combined entry sits left of the language entry, the pinned ones right of it.
        let (combined, pinned) = match language_index {
            Some(_) => self.language_status_items(foreground, cx),
            None => (None, Vec::new()),
        };
        // statusbarpart.css `.compact-left`: the language entry next to the compact combined entry.
        let compact_language = combined.is_some();
        let (margin, padding) = self.status_item_spacing();
        // modernUI statusBar.css: in compact density a `.compact-left` label keeps the 4px padding and drops its left margin.
        let (compact_right_margin, compact_padding) = if self.compact_density() { (margin, padding) } else { (5., 3.) };
        let items = items.into_iter().enumerate().map(|(index, (label, tooltip, command, id))| {
            let compact = compact_language && Some(index) == language_index;
            // The media preview's dimensions and file size entries have neither tooltip nor command.
            let hover = (!tooltip.is_empty()).then(|| self.hover_target(tooltip, super::hover::HoverContent::Text(tooltip.into()), super::hover::HoverOptions::status_bar()));
            let item = div()
                .id(("editor-status", index))
                .debug_selector(move || format!("editor-status-{command}"))
                .relative()
                .h_full()
                .flex_none()
                .when(!compact && index >= prominent_items, |item| item.mx(px(margin)).px(px(padding)))
                .when(index < prominent_items, |item| item.px(px(self.status_label_spacing(true, false).1)))
                .when(compact, |item| item.mr(px(compact_right_margin)).px(px(compact_padding)))
                .flex()
                .items_center()
                .whitespace_nowrap()
                .child(label)
                .children(hover)
                // statusbarItem.ts executeCommand on click.
                .when(!command.is_empty(), |item| {
                    item.cursor_pointer().on_click(cx.listener(move |workbench, _, window, cx| {
                        let outcome = workbench.execute_command(command, Vec::new(), window, cx);
                        super::quick_access::show_failure(command.to_owned(), outcome, window, cx);
                    }))
                });
            let item = match (compact, command.is_empty()) {
                (true, _) => self.compact_status_hover(item, id, cx),
                (false, false) => self.status_item_hover(item, (index < prominent_items).then_some("prominent")),
                (false, true) => item,
            };
            let name = super::status_entries::editor_status_entry_name(id);
            if index >= prominent_items {
                return (id.to_owned(), name.to_owned(), false, item.into_any_element());
            }
            // `.prominent-kind` colors the container, a `has-background-color` one with no label margins, with
            // modernUI statusBar.css cornerRadius.small (4px).
            let item = div().h_full().flex_none().rounded(px(4.)).text_color(prominent.1).when_some(prominent.0, |container, background| container.bg(background)).child(item);
            (id.to_owned(), name.to_owned(), true, item.into_any_element())
        });
        let mut items: Vec<(String, String, bool, gpui::AnyElement)> = items.collect();
        if let Some(language_index) = language_index {
            let detection = self.language_detection_status_item(foreground, cx).map(|item| ("status.languageDetectionStatus".to_owned(), "Language Detection".to_owned(), false, item));
            items.splice(language_index + 1..language_index + 1, detection.into_iter().chain(pinned));
            if let Some(combined) = combined {
                items.insert(language_index, ("status.languageStatus".to_owned(), "Editor Language Status".to_owned(), false, combined));
            }
        }
        items.into_iter().filter_map(|(id, name, background, item)| self.status_bar_entry(&id, &name, None, background, item, cx)).collect()
    }

    /// `getCodeEditor(editorService.activeTextEditorControl)`, which the status bar and breadcrumbs follow: a diff
    /// editor's modified side, also while its original side has the focus.
    pub(super) fn active_text_editor_control(&self) -> Option<&OpenEditor> {
        if let Some(diff) = self.editors.active_diff() {
            // A custom editor diff shows webviews, no code editor.
            if diff.custom.is_some() {
                return None;
            }
            if let Some(modified) = &diff.modified_editor {
                return Some(modified);
            }
        }
        // mergeEditor.ts `getControl`: the result's editor, also while an input has the focus.
        if self.editors.active_merge().is_some() {
            return self.merge_result();
        }
        self.editors.pane_editor()
    }

    /// editorStatus.ts entries of the editor: text, tooltip, command and status bar id.
    fn editor_status_entries(editor: &OpenEditor, languages: &crate::languages::Languages) -> [(String, &'static str, &'static str, &'static str); 5] {
        let document = &editor.document();
        let Indentation { tab_size, insert_spaces, .. } = document.indentation;
        let indent_size = document.indentation.indent_size();
        let indentation = match (insert_spaces, tab_size == indent_size) {
            (true, true) => format!("Spaces: {indent_size}"),
            (true, false) => format!("Spaces: {indent_size} (Tab Size: {tab_size})"),
            (false, _) => format!("Tab Size: {tab_size}"),
        };
        let encoding = SUPPORTED_ENCODINGS.iter().find(|supported| supported.id == document.encoding).map_or(document.encoding.as_str(), |supported| supported.label_short);
        let eol = if document.eol == "\r\n" { "CRLF" } else { "LF" };
        [
            (selection_label(editor), "Go to Line/Column", "workbench.action.gotoLine", "status.editor.selection"),
            (indentation, "Select Indentation", super::editor_status::CHANGE_INDENTATION, "status.editor.indentation"),
            (encoding.into(), "Select Encoding", "workbench.action.editor.changeEncoding", "status.editor.encoding"),
            (eol.into(), "Select End of Line Sequence", "workbench.action.editor.changeEOL", "status.editor.eol"),
            (languages.name(&document.language_id).to_string(), "Select Language Mode", "workbench.action.editor.changeLanguageMode", "status.editor.mode"),
        ]
    }
}

#[derive(Clone, Copy)]
pub(super) struct EditorMetrics {
    pub(super) font_size: f32,
    pub(super) line_height: f32,
    pub(super) char_width: f32,
    line_numbers: LineNumbers,
    line_numbers_width: f32,
    /// The line decorations lane: lineDecorationsWidth plus the folding controls, without them in a diff editor.
    decorations_width: f32,
    glyph_margin: bool,
}

/// editorOptions.ts `RenderLineNumbersType` from `editor.lineNumbers`.
#[derive(Clone, Copy, PartialEq, Debug)]
pub(super) enum LineNumbers {
    Off,
    On,
    Relative,
    Interval,
}

/// A comment's reply or edit editor (simpleCommentEditor.ts).
fn is_comment_input(editor: &OpenEditor) -> bool {
    editor.document().scheme == super::comments::INPUT_SCHEME
}

/// lineNumbers.ts `_getLineRenderLineNumber` for the zero-based `line` with the primary cursor on `cursor_line`.
fn line_number_label(render: LineNumbers, line: usize, cursor_line: usize, line_count: usize) -> Option<String> {
    let number = line + 1;
    match render {
        LineNumbers::Off => None,
        LineNumbers::On => Some(number.to_string()),
        LineNumbers::Relative if line == cursor_line => Some(number.to_string()),
        LineNumbers::Relative => Some(line.abs_diff(cursor_line).to_string()),
        LineNumbers::Interval => (line == cursor_line || number % 10 == 0 || number == line_count).then(|| number.to_string()),
    }
}

impl EditorMetrics {
    /// One glyph lane as wide as a line is high (editorOptions.ts layout), none with `glyphMargin: false`.
    fn glyph_margin_width(&self) -> f32 {
        if self.glyph_margin { self.line_height } else { 0. }
    }

    pub(super) fn content_left(&self) -> f32 {
        self.glyph_margin_width() + self.line_numbers_width + self.decorations_width
    }

    /// fontInfo.ts `BareFontInfo._create`: the editor zoom scales the font size and line height; then
    /// `typicalHalfwidthCharacterWidth` and `maxDigitWidth` of that font. The line numbers are as wide as the
    /// longest number, at least lineNumbersMinChars digits, rounded, and 0 wide when off (editorOptions.ts).
    pub(super) fn measure(window: &Window, line_count: usize, line_numbers: LineNumbers, zoom: f32) -> Self {
        Self::measure_with_min_chars(window, line_count, line_numbers, zoom, LINE_NUMBERS_MIN_CHARS)
    }

    pub(super) fn measure_with_min_chars(window: &Window, line_count: usize, line_numbers: LineNumbers, zoom: f32, min_chars: usize) -> Self {
        let (font_size, line_height) = (EDITOR_FONT_SIZE * zoom, LINE_HEIGHT * zoom);
        let text_system = window.text_system();
        let font_id = text_system.resolve_font(&font(EDITOR_FONT));
        let advance = |c: char| f32::from(text_system.advance(font_id, px(font_size), c).expect("Menlo has ASCII glyphs").width);
        let max_digit_width = ('0'..='9').map(advance).fold(0., f32::max);
        // fontMeasurements.ts measures U+FF4D, which the editor font lacks: shaping picks the fallback font.
        let full_width = "\u{ff4d}";
        let run = gpui::TextRun { len: full_width.len(), font: font(EDITOR_FONT), color: gpui::black(), background_color: None, underline: None, strikethrough: None };
        let full_width_advance = f32::from(text_system.shape_line(full_width.into(), px(font_size), &[run], None).width);
        crate::editor::set_full_width_columns(full_width_advance / advance('x'));
        let digits = if line_numbers == LineNumbers::Off { 0 } else { line_count.to_string().len().max(min_chars) };
        EditorMetrics { font_size, line_height, char_width: advance('x'), line_numbers, line_numbers_width: (digits as f32 * max_digit_width).round(), decorations_width: DECORATIONS_WIDTH, glyph_margin: true }
    }
}

struct LineColors {
    number: Rgba,
    active_number: Rgba,
    text: Rgba,
    line_background: Option<Rgba>,
    line_border: Option<Rgba>,
    selection_highlight: Option<Rgba>,
    selection_highlight_border: Option<Rgba>,
    guide: Rgba,
    active_guide: Rgba,
    cursor: Rgba,
    primary_cursor: Rgba,
    secondary_cursor: Rgba,
    selection: Rgba,
}

/// editorStatus.ts `getSelectionLabel`: the primary cursor's line and visible column for one cursor, the
/// count for several, and the chars selected (`getCharacterCountInRange`: code points, a line break as the EOL's length).
fn selection_label(editor: &OpenEditor) -> String {
    let document = &editor.document();
    let mut selected = 0;
    for selection in &editor.selections {
        let (start, end) = (selection.start(), selection.end());
        for line in start.line..=end.line {
            let first = if line == start.line { start.column } else { 0 };
            let last = if line == end.line { end.column } else { document.lines[line].chars().count() };
            selected += last - first;
        }
        selected += document.eol.len() * (end.line - start.line);
    }
    if let [selection] = editor.selections.as_slice() {
        let Position { line, column } = selection.head;
        let visible = crate::editor::logical_visible_column(&document.lines[line], column, document.indentation.tab_size);
        return match selected {
            0 => format!("Ln {}, Col {}", line + 1, visible + 1),
            _ => format!("Ln {}, Col {} ({selected} selected)", line + 1, visible + 1),
        };
    }
    match selected {
        0 => format!("{} selections", editor.selections.len()),
        _ => format!("{} selections ({selected} characters selected)", editor.selections.len()),
    }
}

const ROUNDED_PIECE_WIDTH: f32 = 10.;
/// cornerRadius.large of the floating editor part's `.content`, the box that clips the tab strip.
const PART_CONTENT_RADIUS: f32 = 8.;

#[derive(Clone, Copy, PartialEq, Debug)]
enum Corner {
    Extern,
    Intern,
    Flat,
}

#[derive(PartialEq, Debug)]
struct SelectionCorners {
    start_top: Corner,
    start_bottom: Corner,
    end_top: Corner,
    end_bottom: Corner,
}

/// selections.ts `_enrichVisibleRangesWithStyle` for one line's range against the same selection's range on
/// the view lines above and below. Upstream keeps the previous frame's corners at the viewport edges; the
/// neighbor lines past the edge give the same corners.
fn selection_corners(above: Option<(f32, f32)>, (left, right): (f32, f32), below: Option<(f32, f32)>, epsilon: f32) -> SelectionCorners {
    let mut corners = SelectionCorners { start_top: Corner::Extern, start_bottom: Corner::Extern, end_top: Corner::Extern, end_bottom: Corner::Extern };
    if let Some((above_left, above_right)) = above {
        if (left - above_left).abs() < epsilon {
            corners.start_top = Corner::Flat;
        } else if left > above_left {
            corners.start_top = Corner::Intern;
        }
        if (right - above_right).abs() < epsilon {
            corners.end_top = Corner::Flat;
        } else if above_left < right && right < above_right {
            corners.end_top = Corner::Intern;
        }
    }
    if let Some((below_left, below_right)) = below {
        if (left - below_left).abs() < epsilon {
            corners.start_bottom = Corner::Flat;
        } else if below_left < left && left < below_right {
            corners.start_bottom = Corner::Intern;
        }
        if (right - below_right).abs() < epsilon {
            corners.end_bottom = Corner::Flat;
        } else if right < below_right {
            corners.end_bottom = Corner::Intern;
        }
    }
    corners
}

/// The selected chars of a line and whether its line break is selected too.
/// whitespace.ts with `experimentalWhitespaceRendering: svg`: a circle for a space, an arrow for a tab, each at
/// its mark's left edge on the line.
fn whitespace_canvas(marks: Vec<(f32, bool)>, space_width: f32, line_height: f32, color: Rgba) -> impl IntoElement {
    canvas(
        |_, _, _| (),
        move |bounds, _, window, _| {
            let center_y = line_height / 2.;
            let at = |x: f32, y: f32| bounds.origin + point(px(x), px(y));
            for (left, tab) in &marks {
                if !tab {
                    let radius = (space_width / 7. * 100.).round() / 100.;
                    let center_x = left + space_width / 2.;
                    let circle = Bounds::new(at(center_x - radius, center_y - radius), size(px(radius * 2.), px(radius * 2.)));
                    window.paint_quad(fill(circle, color).corner_radii(px(radius)));
                    continue;
                }
                // _renderArrow: a shaft half a stroke thick either side of the middle, then the head.
                let stroke = space_width / 7.;
                let tip = 100. / 125. * space_width;
                let p1 = (0., stroke / 2.);
                let p2 = (tip, p1.1);
                let p3 = (p2.0 - 0.2 * tip, p2.1 + 0.2 * tip);
                let p4 = (p3.0 + 0.1 * tip, p3.1 + 0.1 * tip);
                let p5 = (p4.0 + 0.35 * tip, p4.1 - 0.35 * tip);
                let points = [p1, p2, p3, p4, p5, (p5.0, -p5.1), (p4.0, -p4.1), (p3.0, -p3.1), (p2.0, -p2.1), (p1.0, -p1.1)];
                let mut arrow = PathBuilder::fill();
                arrow.move_to(at(left + p1.0, center_y + p1.1));
                for (x, y) in &points[1..] {
                    arrow.line_to(at(left + x, center_y + y));
                }
                arrow.close();
                if let Ok(path) = arrow.build() {
                    window.paint_path(path, color);
                }
            }
        },
    )
    .absolute()
    .top_0()
    .left_0()
    .size_full()
}

pub(super) fn selected_columns(selection: Selection, line: usize, text: &str) -> Option<(usize, usize, bool)> {
    let (start, end) = (selection.start(), selection.end());
    if selection.is_empty() || line < start.line || line > end.line {
        return None;
    }
    let first = if line == start.line { start.column } else { 0 };
    let last = if line == end.line { end.column } else { text.chars().count() };
    Some((first, last, line < end.line))
}

/// mouseHandler.ts `MouseDownState` of a left or middle press that selects: its click count, and whether it started
/// on the gutter (`startedOnLineNumbers`).
#[derive(Clone, Copy)]
pub(super) struct MouseDown {
    pub(super) count: usize,
    pub(super) on_gutter: bool,
}

/// mouseTarget.ts `mouseColumn` less one: the visible column nearest the pointer, past the line end too.
fn mouse_column(visible: f32) -> usize {
    visible.round().max(0.) as usize
}

/// `_initLanes` with three lanes: one device pixel for the border, then three thirds, the center taking the rest.
struct RulerLanes {
    center_x: f32,
    center_width: f32,
    right_x: f32,
    right_width: f32,
    full_x: f32,
    full_width: f32,
}

impl RulerLanes {
    fn new(canvas_width: f32) -> Self {
        let remaining = canvas_width - 1.;
        let side = (remaining / 3.).floor();
        let center_width = remaining - 2. * side;
        RulerLanes { center_x: 1. + side, center_width, right_x: 1. + side + center_width, right_width: side, full_x: 1., full_width: remaining }
    }
}



/// scrollbarVisibilityController.ts for both scrollbars, with the CSS opacity transition between its states.
#[derive(Default)]
pub(super) struct Scrollbars {
    pub mouse_over: bool,
    /// The code editor under the pointer, by group and model id; lists leave it empty.
    pointer_editor: Option<(u32, u32)>,
    pub(super) shown: bool,
    /// When `shown` last flipped, and the opacity the transition started from.
    changed: Option<(Instant, f32)>,
    hide_timer: Option<Task<()>>,
    drag: Option<SliderDrag>,
}

impl Scrollbars {
    pub(super) fn set_shown(&mut self, shown: bool, now: Instant) {
        if self.shown != shown {
            let from = self.opacity(now);
            self.shown = shown;
            self.changed = Some((now, from));
        }
    }

    /// Linear from where the last change started: 100ms to visible, 800ms to invisible.
    pub(super) fn opacity(&self, now: Instant) -> f32 {
        let target = if self.shown { 1. } else { 0. };
        let Some((at, from)) = self.changed else { return target };
        let duration = if self.shown { SCROLLBAR_FADE_IN } else { SCROLLBAR_FADE_OUT };
        let progress = (now.duration_since(at).as_secs_f32() / duration.as_secs_f32()).min(1.);
        from + (target - from) * progress
    }

    pub(super) fn in_transition(&self, now: Instant) -> bool {
        self.opacity(now) != if self.shown { 1. } else { 0. }
    }
}

/// folding.css: the expanded folding controls fade with `transition: opacity 0.5s` (ease) as the pointer enters
/// or leaves the margin.
#[derive(Default)]
pub(super) struct FoldControls {
    shown: bool,
    changed: Option<(Instant, f32)>,
}

impl FoldControls {
    /// folding.css: with reduced motion the icons show and hide without their fade.
    fn set_shown(&mut self, shown: bool, now: Instant, animate: bool) {
        if self.shown != shown {
            let from = self.opacity(now);
            self.shown = shown;
            self.changed = animate.then_some((now, from));
        }
    }

    fn opacity(&self, now: Instant) -> f32 {
        let target = if self.shown { 1. } else { 0. };
        let Some((at, from)) = self.changed else { return target };
        let progress = (now.duration_since(at).as_secs_f32() / FOLD_CONTROLS_FADE.as_secs_f32()).min(1.);
        from + (target - from) * ease(progress)
    }

    fn in_transition(&self, now: Instant) -> bool {
        self.opacity(now) != if self.shown { 1. } else { 0. }
    }
}

/// CSS `ease`, cubic-bezier(0.25, 0.1, 0.25, 1).
pub(super) fn ease(x: f32) -> f32 {
    super::transition::cubic_bezier(0.25, 0.1, 0.25, 1., x)
}

#[derive(Clone, Copy)]
struct SliderDrag {
    axis: Axis,
    /// The pointer's window coordinate along the axis at the press, and the scrollbar then.
    pointer: f32,
    state: Scrollbar,
}

fn scrollbar(editor: &OpenEditor, axis: Axis, viewport: Viewport) -> Scrollbar {
    match axis {
        Axis::Vertical => editor.vertical_scrollbar(viewport),
        Axis::Horizontal => editor.horizontal_scrollbar(viewport),
    }
}

fn set_axis_scroll(editor: &mut OpenEditor, axis: Axis, position: f32, viewport: Viewport) -> bool {
    match axis {
        Axis::Vertical => editor.set_scroll(position, editor.scroll.left, viewport),
        Axis::Horizontal => editor.set_scroll(editor.scroll.top, position, viewport),
    }
}

/// The slider spans the scrollbar's thickness (`verticalSliderSize` and `horizontalSliderSize` default to it).
fn slider_bounds(track: Bounds<Pixels>, axis: Axis, bar: Scrollbar) -> Bounds<Pixels> {
    match axis {
        Axis::Vertical => Bounds::new(track.origin + point(px(0.), px(bar.slider_position)), size(track.size.width, px(bar.slider_size))),
        Axis::Horizontal => Bounds::new(track.origin + point(px(bar.slider_position), px(0.)), size(px(bar.slider_size), track.size.height)),
    }
}

/// The complementary error function (Abramowitz and Stegun 7.1.26, error below 1.5e-7).
pub(super) fn erfc(x: f32) -> f32 {
    let t = 1. / (1. + 0.327_591_1 * x);
    let poly = t * (0.254_829_6 + t * (-0.284_496_74 + t * (1.421_413_7 + t * (-1.453_152_1 + t * 1.061_405_4))));
    poly * (-x * x).exp()
}


/// textModelTokens.ts `DefaultBackgroundTokenizer`: the lines of a drawn model still waiting for tokens are tokenized
/// in 1 ms chunks with input and frames let in between, then the editor is drawn again.
fn schedule_background_tokenization(model: &crate::editor::SharedModel, cx: &mut Context<Workbench>) {
    let scheduled = {
        let model = model.borrow();
        model.document.tokens.begin_background_tokenization(&model.document.lines)
    };
    if !scheduled {
        return;
    }
    let model = Rc::downgrade(model);
    cx.spawn(async move |workbench, cx| {
        loop {
            cx.background_executor().timer(Duration::from_millis(1)).await;
            let Some(shared) = model.upgrade() else { return };
            let mut model = shared.borrow_mut();
            let document = &mut model.document;
            if !document.tokens.tokenize_in_background(&document.lines, Duration::from_millis(1)) {
                break;
            }
        }
        let _ = workbench.update(cx, |_, cx| cx.notify());
    })
    .detach();
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};
    use std::sync::{Arc, Mutex};

    use exthost::scan::scan_extension;
    use gpui::{TestAppContext, VisualTestContext};
    use serde_json::json;

    use super::{Corner, LineNumbers, SelectionCorners, line_number_label, selection_corners};
    use crate::host_sync::HostSync;
    use crate::languages::Languages;
    use crate::theme::load_theme;
    use crate::workbench::Workbench;
    use Corner::{Extern, Flat, Intern};

    #[test]
    fn line_numbers_render_as_line_numbers_ts() {
        let labels = |render, cursor_line| (0..12).map(|line| line_number_label(render, line, cursor_line, 12).unwrap_or_default()).collect::<Vec<_>>().join(" ");
        assert_eq!(labels(LineNumbers::On, 2), "1 2 3 4 5 6 7 8 9 10 11 12");
        assert_eq!(labels(LineNumbers::Relative, 2), "2 1 3 1 2 3 4 5 6 7 8 9");
        assert_eq!(labels(LineNumbers::Interval, 2), "  3       10  12");
        assert_eq!(labels(LineNumbers::Off, 2), "           ");
    }

    #[test]
    fn selection_corners_follow_the_neighbor_lines() {
        let corners = |start_top, start_bottom, end_top, end_bottom| SelectionCorners { start_top, start_bottom, end_top, end_bottom };
        // One line: every corner rounds out.
        assert_eq!(selection_corners(None, (10., 50.), None, 2.), corners(Extern, Extern, Extern, Extern));
        // A middle line starting left of the line above, ending left of the line below.
        assert_eq!(selection_corners(Some((20., 80.)), (0., 80.), Some((0., 100.)), 2.), corners(Extern, Flat, Flat, Intern));
        // A last line starting right of the line above and ending inside it.
        assert_eq!(selection_corners(Some((0., 80.)), (10., 30.), None, 2.), corners(Intern, Extern, Intern, Extern));
        // A start within epsilon of the line below counts as aligned.
        assert_eq!(selection_corners(None, (20.5, 80.), Some((20., 60.)), 2.), corners(Extern, Flat, Extern, Extern));
    }

    fn workbench_in<'a>(name: &str, user_settings: &str, cx: &'a mut TestAppContext) -> (PathBuf, gpui::Entity<Workbench>, &'a mut VisualTestContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let dir = std::env::temp_dir().join(format!("vsrustium-editor-view-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("User")).unwrap();
        std::fs::write(dir.join("User/settings.json"), user_settings).unwrap();
        let settings = config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None);
        let settings = Arc::new(Mutex::new(settings));
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));
        (dir, workbench, cx)
    }

    /// Opens a file wrapped at column 20 with `editor.wrappingIndent` `indent`: its model id and the first view lines
    /// of model line 1 (wrapped) and 3 (blank).
    fn wrapped_file<'a>(name: &str, indent: &str, cx: &'a mut TestAppContext) -> (PathBuf, &'a mut VisualTestContext, u32, usize, usize) {
        let settings = json!({ "editor.wordWrap": "wordWrapColumn", "editor.wordWrapColumn": 20, "editor.wrappingIndent": indent }).to_string();
        let (dir, workbench, cx) = workbench_in(name, &settings, cx);
        let file = dir.join("a.txt");
        let deep = " ".repeat(28);
        std::fs::write(&file, format!("{{\n    aaaa bbbb cccc dddd eeee ffff\n{deep}x\n\n{deep}y\n}}\n")).unwrap();
        workbench.update_in(cx, |workbench, window, cx| workbench.open_file(file.clone(), true, window, cx));
        cx.run_until_parked();
        cx.update(|window, _| window.refresh());
        cx.run_until_parked();
        let (model_id, wrapped, blank) = workbench.read_with(cx, |workbench, _| {
            let editor = workbench.editors.active().unwrap();
            (editor.model_id, editor.view_line(1), editor.view_line(3))
        });
        (dir, cx, model_id, wrapped, blank)
    }

    fn indent_guide(model_id: u32, view_line: usize, level: usize, cx: &mut VisualTestContext) -> Option<gpui::Bounds<gpui::Pixels>> {
        cx.debug_bounds(format!("indent-guide-{model_id}-{view_line}-{level}").leak())
    }

    /// viewModelLines.ts `getViewLinesIndentGuides` and indentGuides.ts: a wrapped line repeats its indent guides at the
    /// same x on its view lines after a wrapping indent, and no guide starts past the wrapping column.
    #[gpui::test]
    fn a_wrapping_indent_repeats_the_indent_guides(cx: &mut TestAppContext) {
        let (dir, cx, model_id, wrapped, blank) = wrapped_file("wrapped-indent-guides-same", "same", cx);
        let first = indent_guide(model_id, wrapped, 0, cx).expect("the wrapped line's first view line draws its guide");
        let next = indent_guide(model_id, wrapped + 1, 0, cx).expect("the same wrapping indent repeats the guide");
        assert_eq!(next.left(), first.left(), "the repeated guide sits at the first one's x");
        // The blank line takes the 7 guides of its neighbors; at 4 columns each the 7th starts past column 20.
        assert!(indent_guide(model_id, blank, 5, cx).is_some());
        assert!(indent_guide(model_id, blank, 6, cx).is_none(), "no guide starts past the wrapping column");
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// viewModelLines.ts `IndentGuideRepeatOption.BlockSubsequent`: without a wrapping indent a wrapped line's other
    /// view lines have no indent guides.
    #[gpui::test]
    fn without_a_wrapping_indent_wrapped_view_lines_have_no_indent_guides(cx: &mut TestAppContext) {
        let (dir, cx, model_id, wrapped, _) = wrapped_file("wrapped-indent-guides-none", "none", cx);
        assert!(indent_guide(model_id, wrapped, 0, cx).is_some());
        assert!(indent_guide(model_id, wrapped + 1, 0, cx).is_none());
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// editorTitleControl.ts `createEditorTabsControl` per `workbench.editor.showTabs`: `single` draws one title with
    /// the breadcrumbs inline and a close action, `none` only the breadcrumbs row; layout.ts `toggleZenMode` enforces
    /// `zenMode.showTabs` on the main part until zen mode ends.
    #[gpui::test]
    fn show_tabs_picks_the_title_control_and_zen_mode_enforces_its_own(cx: &mut TestAppContext) {
        let settings = json!({ "workbench.editor.showTabs": "single", "zenMode.showTabs": "none", "zenMode.fullScreen": false }).to_string();
        let (dir, workbench, cx) = workbench_in("show-tabs", &settings, cx);
        let file = dir.join("a.txt");
        std::fs::write(&file, "one\n").unwrap();
        workbench.update_in(cx, |workbench, window, cx| workbench.open_file(file.clone(), true, window, cx));
        let title = |cx: &mut VisualTestContext| {
            cx.update(|window, _| window.refresh());
            cx.run_until_parked();
            let tabs_visible = workbench.update_in(cx, |workbench, window, _| (workbench.key_context(window)["editorTabsVisible"].clone(), workbench.key_context(window)["breadcrumbsVisible"].clone()));
            let close = cx.debug_bounds("editor-title-close").is_some();
            (cx.debug_bounds("editor-tab-strip"), cx.debug_bounds("single-tab-title"), cx.debug_bounds("breadcrumb-item-0"), (tabs_visible.0, tabs_visible.1, close))
        };

        let (strip, single, crumb, keys) = title(cx);
        let (single, crumb) = (single.expect("the single tab title"), crumb.expect("the breadcrumbs"));
        assert!(strip.is_none(), "single draws no tabs");
        assert!(crumb.top() >= single.top() && crumb.bottom() <= single.bottom(), "the breadcrumbs sit in the title: {crumb:?} in {single:?}");
        assert_eq!(keys, (json!(false), json!(true), true));
        let single_top = single.top();

        workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("workbench.action.toggleZenMode", Vec::new(), window, cx));
        let (strip, single, crumb, keys) = title(cx);
        assert_eq!((strip, single), (None, None), "zenMode.showTabs none: no title");
        assert!(crumb.expect("the breadcrumbs row stays").top() < single_top + gpui::px(super::TAB_STRIP_HEIGHT), "the breadcrumbs move up into the title's place");
        assert_eq!(keys, (json!(false), json!(true), true), "none has its editor actions, the close action too, in the title bar");

        workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("workbench.action.toggleZenMode", Vec::new(), window, cx));
        assert!(title(cx).1.is_some(), "leaving zen mode brings back the single tab");

        workbench.update_in(cx, |workbench, _, _| workbench.update_setting("workbench.editor.showTabs", json!("multiple")));
        let (strip, single, crumb, keys) = title(cx);
        let (strip, crumb) = (strip.expect("the tab strip"), crumb.expect("the breadcrumbs"));
        assert!(single.is_none());
        assert!(crumb.top() >= strip.bottom(), "the breadcrumbs sit below the tabs");
        assert_eq!(keys, (json!(true), json!(true), false));
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// titlebarPart.ts `editorActionsEnabled`: `showTabs: none` with `editorActionsLocation: default` moves the editor
    /// actions into the title bar before the layout controls, Customize Layout into the title bar's overflow
    /// (layoutActions.ts `EditorActionsInTitleBar`), and commandCenterControl.ts names the active file; `hidden` shows
    /// them nowhere.
    #[gpui::test]
    fn show_tabs_none_moves_the_editor_actions_into_the_title_bar(cx: &mut TestAppContext) {
        let settings = json!({ "workbench.editor.showTabs": "none" }).to_string();
        let (dir, workbench, cx) = workbench_in("editor-actions-title-bar", &settings, cx);
        let file = dir.join("a.txt");
        std::fs::write(&file, "one\n").unwrap();
        workbench.update_in(cx, |workbench, window, cx| workbench.open_file(file.clone(), true, window, cx));
        let title_bar = |cx: &mut VisualTestContext| {
            cx.update(|window, _| window.refresh());
            cx.run_until_parked();
            let close = cx.debug_bounds("editor-title-close").map(|bounds| bounds.top());
            let customize = cx.debug_bounds("workbench.action.customizeLayout").is_some();
            let more = cx.debug_bounds("title-bar-more");
            let label = workbench.read_with(cx, |workbench, _| workbench.command_center_label());
            (close, customize, more, label)
        };

        let (close, customize, more, label) = title_bar(cx);
        assert!(close.expect("the close action is drawn") < gpui::px(35.), "in the title bar");
        assert!(!customize, "Customize Layout leaves the layout controls");
        assert_eq!(label, "a.txt");
        workbench.update_in(cx, |workbench, window, cx| workbench.show_editor_title_menu(more.expect("the title bar overflow"), true, window, cx));
        let overflow = workbench.read_with(cx, |workbench, _| workbench.context_menu.as_ref().expect("the overflow shows").levels[0].actions.clone());
        let titles: Vec<_> = overflow.iter().filter_map(|action| match action {
            crate::menus::MenuAction::Command { title, .. } => Some(title.as_str()),
            _ => None,
        }).collect();
        assert_eq!(titles.first(), Some(&"Show Opened Editors"), "the editor actions' secondary ones first: {titles:?}");
        assert_eq!(titles.last(), Some(&"Customize Layout..."));
        workbench.update_in(cx, |workbench, window, cx| workbench.hide_context_menu(window, cx));

        workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("workbench.action.hideEditorActions", Vec::new(), window, cx));
        let (close, customize, more, _) = title_bar(cx);
        assert_eq!((close, customize, more.is_some()), (None, true, false), "hidden: no editor actions anywhere");

        workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("workbench.action.showMultipleEditorTabs", Vec::new(), window, cx));
        let (_, _, _, label) = title_bar(cx);
        assert_eq!(label, "Search", "with tabs the command center names the workspace");
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// debug.contribution.ts Run or Debug... and menuEntryActionViewItem.ts `DropdownWithDefaultActionViewItem`: the
    /// `editor/title/run` commands draw as a split button whose primary is the first, until another runs from the
    /// chevron's dropdown and becomes the primary, remembered as `EditorTitleRun_lastActionId`.
    #[gpui::test]
    fn editor_title_run_is_a_split_button_whose_dropdown_picks_the_primary(cx: &mut TestAppContext) {
        use crate::menus::{Entry, MenuId, MenuItem};
        let (dir, workbench, cx) = workbench_in("editor-title-run", "{}", cx);
        cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
        let file = dir.join("a.txt");
        std::fs::write(&file, "one\n").unwrap();
        workbench.update_in(cx, |workbench, window, cx| {
            for (id, title, order) in [("port.run", "Port Run", 1.), ("port.debug", "Port Debug", 2.)] {
                let entry = Entry::Command { id: id.into(), precondition: None, toggled: None, alt: None };
                workbench.menus.push(MenuItem { menu: MenuId::EditorTitleRun, entry, title: title.into(), group: "navigation".into(), order, when: None });
                workbench.command_icons.insert(id.into(), crate::menus::CommandIcon::Codicon("play".into()));
            }
            let entry = Entry::Command { id: "port.preview".into(), precondition: None, toggled: None, alt: None };
            workbench.menus.push(MenuItem { menu: MenuId::EditorTitle, entry, title: "Preview".into(), group: "navigation".into(), order: 0., when: None });
            workbench.command_icons.insert("port.preview".into(), crate::menus::CommandIcon::Codicon("open-preview".into()));
            workbench.open_file(file.clone(), true, window, cx);
        });
        cx.run_until_parked();
        cx.update(|window, _| window.refresh());
        cx.run_until_parked();
        assert!(cx.debug_bounds("split-button-primary-port.run").is_some(), "the first command is the primary");
        let chevron = cx.debug_bounds("split-button-dropdown-EditorTitleRun").expect("the chevron draws").center();
        let preview = cx.debug_bounds("codicon-open-preview").expect("the next action draws");
        assert!(cx.debug_bounds("split-button-dropdown-EditorTitleRun").unwrap().right() <= preview.left(), "the split button keeps its width");
        cx.simulate_click(chevron, gpui::Modifiers::none());
        cx.run_until_parked();
        let titles = workbench.read_with(cx, |workbench, _| {
            let menu = workbench.context_menu.as_ref().expect("the chevron opens the submenu");
            menu.levels[0].actions.iter().filter_map(|action| match action {
                crate::menus::MenuAction::Command { title, .. } => Some(title.clone()),
                _ => None,
            }).collect::<Vec<_>>()
        });
        assert_eq!(titles, ["Port Run", "Port Debug"]);
        cx.simulate_keystrokes("down down enter");
        cx.run_until_parked();
        let stored = workbench.read_with(cx, |workbench, _| workbench.workspace_storage.lock().unwrap().get("EditorTitleRun_lastActionId").map(str::to_string));
        assert_eq!(stored.as_deref(), Some("port.debug"));
        cx.update(|window, _| window.refresh());
        cx.run_until_parked();
        assert!(cx.debug_bounds("split-button-primary-port.debug").is_some(), "the command run from the dropdown is the primary");
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// menuService.ts `compareMenuItems`: git's Open Changes and merge-conflict's Next Conflict share `navigation@2` and sort by title.
    #[gpui::test]
    fn editor_title_actions_of_one_order_sort_by_title(cx: &mut TestAppContext) {
        use crate::menus::{Entry, MenuId, MenuItem};
        let (dir, workbench, cx) = workbench_in("editor-title-order", "{}", cx);
        cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
        let file = dir.join("a.txt");
        std::fs::write(&file, "one\n").unwrap();
        workbench.update_in(cx, |workbench, window, cx| {
            for (id, title, icon) in [("port.openChange", "Open Changes", "compare-changes"), ("port.next", "Next Conflict", "arrow-down")] {
                let entry = Entry::Command { id: id.into(), precondition: None, toggled: None, alt: None };
                workbench.menus.push(MenuItem { menu: MenuId::EditorTitle, entry, title: title.into(), group: "navigation".into(), order: 2., when: None });
                workbench.command_icons.insert(id.into(), crate::menus::CommandIcon::Codicon(icon.into()));
            }
            workbench.open_file(file.clone(), true, window, cx);
        });
        cx.run_until_parked();
        let x = |cx: &mut VisualTestContext, selector: &'static str| cx.debug_bounds(selector).unwrap_or_else(|| panic!("{selector} draws")).left();
        assert!(x(cx, "codicon-arrow-down") < x(cx, "codicon-compare-changes"), "Next Conflict before Open Changes");
        std::fs::remove_dir_all(dir).unwrap();
    }
}