Skip to content

Visual Studio Code, rebuilt in Rust

Rust
47.2 KB
Raw Blame
//! The input element of `InputBox` as the workbench draws it: the value with its selection, IME marked text
//! and blinking caret, its caret keys, mouse selection, text commands and the platform input handler. The quick
//! input, the Explorer's inline editor and the editor find widget's two inputs each own an `InputBox` and an `InputView`.

use std::cell::RefCell;
use std::ops::Range;
use std::rc::Rc;
use std::time::{Duration, Instant};

use gpui::{
    Context, ElementInputHandler, FocusHandle, Font, KeyDownEvent, MouseButton, MouseDownEvent, Modifiers, MouseMoveEvent, ShapedLine, Task, TextRun, UTF16Selection, UnderlineStyle,
    Window, canvas, div, fill, point, prelude::*, px, size,
};

use super::Workbench;
use super::search_editor_widget::SEARCH_EDITOR_FIELDS;
use super::search_view::{SEARCH_FIELDS, SearchField};
use crate::commands::Outcome;
use crate::input_box::{InputBox, Motion};
use crate::workbench::editor_options::CURSOR_BLINKING;

/// Which input element: the quick input's, the Explorer's inline editor, the find widget's, one of the Search view's
/// inputs, one of the search editor's query widget, or the Keyboard Shortcuts editor's.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum InputId {
    QuickInput,
    Explorer,
    ExplorerFind,
    OutlineFind,
    DebugHoverFind,
    ReplFind,
    Find,
    Replace,
    Search(SearchField),
    KeybindingsSearch,
    KeybindingsWhen,
    SearchEditor(SearchField),
    OutputFilter,
    ProblemsFilter,
    ScmInput,
    ExtensionsSearch,
    SettingsSearch,
    SettingsValue,
    SettingsListKey,
    SettingsListValue,
    DebugView,
    BreakpointWidget,
    DebugConsole,
    TerminalFind,
    NotebookFind,
    NotebookReplace,
    Rename,
    ProfileName,
    IconSelectSearch,
    CommentsFilter,
    DebugConsoleFilter,
    TestingFilter,
    TrustedPath,
    /// One of the custom dialog's inputs (dialog.ts `inputs`).
    Dialog(usize),
}

const INPUTS: [InputId; 31] = [
    InputId::QuickInput,
    InputId::Explorer,
    InputId::ExplorerFind,
    InputId::OutlineFind,
    InputId::DebugHoverFind,
    InputId::ReplFind,
    InputId::Find,
    InputId::Replace,
    InputId::KeybindingsSearch,
    InputId::KeybindingsWhen,
    InputId::OutputFilter,
    InputId::ProblemsFilter,
    InputId::ScmInput,
    InputId::ExtensionsSearch,
    InputId::SettingsSearch,
    InputId::SettingsValue,
    InputId::SettingsListKey,
    InputId::SettingsListValue,
    InputId::DebugView,
    InputId::BreakpointWidget,
    InputId::DebugConsole,
    InputId::TerminalFind,
    InputId::NotebookFind,
    InputId::NotebookReplace,
    InputId::Rename,
    InputId::ProfileName,
    InputId::IconSelectSearch,
    InputId::CommentsFilter,
    InputId::DebugConsoleFilter,
    InputId::TestingFilter,
    InputId::TrustedPath,
];

/// The view state of one input element.
pub struct InputView {
    /// The IME's marked text, a UTF-16 range of the value.
    pub marked: Option<Range<usize>>,
    selecting: bool,
    /// On the executor's clock, which the blink timer runs on: a test's clock in tests.
    caret_moved: Instant,
    blink: Option<Task<()>>,
    /// The shaped text, its window position, and the scroll that keeps the caret visible.
    text: Rc<RefCell<InputText>>,
}

#[derive(Default)]
struct InputText {
    /// Each line of the value (the find widget's textarea holds several) with its char offset into the value.
    lines: Vec<(usize, ShapedLine)>,
    left: f32,
    /// The window y of the first line's top, and the distance between lines.
    top: f32,
    line_height: f32,
    scroll: f32,
    scroll_y: f32,
}

impl InputText {
    /// The line holding the char at `index`, and the index's byte offset in it.
    fn line_of(&self, index: usize) -> Option<(usize, &ShapedLine, usize)> {
        let row = self.lines.iter().rposition(|(start, _)| *start <= index)?;
        let (start, line) = &self.lines[row];
        let byte = line.text.char_indices().nth(index - start).map_or(line.text.len(), |(byte, _)| byte);
        Some((row, line, byte))
    }

    /// The char offset closest to a window point.
    fn index_at(&self, x: f32, y: f32) -> usize {
        let row = ((y - self.top) / self.line_height).floor().max(0.) as usize;
        let Some((start, line)) = self.lines.get(row.min(self.lines.len().saturating_sub(1))) else { return 0 };
        let byte = line.closest_index_for_x(px(x - self.left + self.scroll));
        start + line.text[..byte.min(line.text.len())].chars().count()
    }
}

impl Default for InputView {
    fn default() -> Self {
        InputView { marked: None, selecting: false, caret_moved: Instant::now(), blink: None, text: Rc::default() }
    }
}

impl InputView {
    /// The element hides: the IME composition and the caret blink end.
    pub fn reset(&mut self) {
        self.marked = None;
        self.selecting = false;
        self.blink = None;
        self.text = Rc::default();
    }

    /// `x_of_char` as it reads later in the frame, once the input painted.
    pub fn x_of_char_after_paint(&self) -> impl Fn(&str, usize) -> f32 + 'static {
        let text = self.text.clone();
        move |value, index| x_of_char(&text.borrow(), value, index)
    }

    /// The x of the char at `index` of `value` from the input's left edge, as last painted.
    pub fn x_of_char(&self, value: &str, index: usize) -> f32 {
        x_of_char(&self.text.borrow(), value, index)
    }
}

fn x_of_char(text: &InputText, value: &str, index: usize) -> f32 {
    let Some((_, line, byte)) = text.line_of(index.min(value.chars().count())) else { return 0. };
    f32::from(line.x_for_index(byte)) - text.scroll
}

/// What the input element draws besides its value.
pub struct InputLook {
    pub password: bool,
    pub placeholder: Option<String>,
    pub focused: bool,
}

impl Workbench {
    /// The font size of the input's value as last painted.
    #[cfg(test)]
    pub(super) fn input_font_size(&self, id: InputId) -> Option<gpui::Pixels> {
        self.input_view(id).text.borrow().lines.first().map(|(_, line)| line.font_size)
    }

    pub(super) fn input_view(&self, id: InputId) -> &InputView {
        match id {
            InputId::QuickInput => &self.quick_inputs.input,
            InputId::Explorer => &self.explorer.input,
            InputId::ExplorerFind => &self.explorer.find.view,
            InputId::OutlineFind => &self.outline_pane.find.view,
            InputId::DebugHoverFind => &self.debug_hover.find.view,
            InputId::ReplFind => &self.debug_console.find.view,
            InputId::Find => &self.find.find_view,
            InputId::Replace => &self.find.replace_view,
            InputId::Search(field) => &self.search.input(field).view,
            InputId::KeybindingsSearch => &self.keybindings_editor.search_view,
            InputId::KeybindingsWhen => &self.keybindings_editor.when_view,
            InputId::SearchEditor(field) => &self.search_editor_widget.view.input(field).view,
            InputId::OutputFilter => &self.output_view.filter_view,
            InputId::ProblemsFilter => &self.problems.filter_view,
            InputId::ScmInput => &self.scm.input_view,
            InputId::ExtensionsSearch => &self.extensions_viewlet.search_view,
            InputId::SettingsSearch => &self.settings_editor.search_view,
            InputId::SettingsValue => &self.settings_editor.value_view,
            InputId::ProfileName => &self.user_data_profiles.editor.name_view,
            InputId::IconSelectSearch => self.icon_select.picker.as_ref().map_or(&self.user_data_profiles.editor.name_view, |picker| &picker.search_view),
            InputId::SettingsListKey => &self.settings_editor.list.key_view,
            InputId::SettingsListValue => &self.settings_editor.list.value_view,
            InputId::DebugView => &self.debug_view.input_view,
            InputId::BreakpointWidget => &self.debug_view.widget_view,
            InputId::CommentsFilter => &self.comments.view.filter_view,
            InputId::TestingFilter => &self.testing_view.filter.view,
            InputId::DebugConsoleFilter => &self.debug_console.filter_view,
            InputId::DebugConsole => &self.debug_console.input_view,
            InputId::TerminalFind => &self.terminal_view.find.view,
            InputId::NotebookFind => &self.notebook_views.find.find_view,
            InputId::NotebookReplace => &self.notebook_views.find.replace_view,
            InputId::Rename => &self.rename.view,
            InputId::TrustedPath => &self.trust_editor.path_view,
            InputId::Dialog(index) => self.dialog_input(index).map_or(&self.rename.view, |input| &input.view),
        }
    }

    pub(super) fn input_view_mut(&mut self, id: InputId) -> &mut InputView {
        match id {
            InputId::QuickInput => &mut self.quick_inputs.input,
            InputId::Explorer => &mut self.explorer.input,
            InputId::ExplorerFind => &mut self.explorer.find.view,
            InputId::OutlineFind => &mut self.outline_pane.find.view,
            InputId::DebugHoverFind => &mut self.debug_hover.find.view,
            InputId::ReplFind => &mut self.debug_console.find.view,
            InputId::Find => &mut self.find.find_view,
            InputId::Replace => &mut self.find.replace_view,
            InputId::Search(field) => &mut self.search.input_mut(field).view,
            InputId::KeybindingsSearch => &mut self.keybindings_editor.search_view,
            InputId::KeybindingsWhen => &mut self.keybindings_editor.when_view,
            InputId::SearchEditor(field) => &mut self.search_editor_widget.view.input_mut(field).view,
            InputId::OutputFilter => &mut self.output_view.filter_view,
            InputId::ProblemsFilter => &mut self.problems.filter_view,
            InputId::ScmInput => &mut self.scm.input_view,
            InputId::ExtensionsSearch => &mut self.extensions_viewlet.search_view,
            InputId::SettingsSearch => &mut self.settings_editor.search_view,
            InputId::SettingsValue => &mut self.settings_editor.value_view,
            InputId::ProfileName => &mut self.user_data_profiles.editor.name_view,
            InputId::IconSelectSearch => match &mut self.icon_select.picker {
                Some(picker) => &mut picker.search_view,
                None => &mut self.user_data_profiles.editor.name_view,
            },
            InputId::SettingsListKey => &mut self.settings_editor.list.key_view,
            InputId::SettingsListValue => &mut self.settings_editor.list.value_view,
            InputId::DebugView => &mut self.debug_view.input_view,
            InputId::BreakpointWidget => &mut self.debug_view.widget_view,
            InputId::CommentsFilter => &mut self.comments.view.filter_view,
            InputId::TestingFilter => &mut self.testing_view.filter.view,
            InputId::DebugConsoleFilter => &mut self.debug_console.filter_view,
            InputId::DebugConsole => &mut self.debug_console.input_view,
            InputId::TerminalFind => &mut self.terminal_view.find.view,
            InputId::NotebookFind => &mut self.notebook_views.find.find_view,
            InputId::NotebookReplace => &mut self.notebook_views.find.replace_view,
            InputId::Rename => &mut self.rename.view,
            InputId::TrustedPath => &mut self.trust_editor.path_view,
            InputId::Dialog(index) => match self.dialogs.first_mut().and_then(|shown| shown.inputs.get_mut(index)) {
                Some(input) => &mut input.view,
                None => &mut self.rename.view,
            },
        }
    }

    pub(super) fn input_focus(&self, id: InputId) -> &FocusHandle {
        match id {
            InputId::QuickInput => &self.quick_inputs.focus,
            InputId::Explorer => &self.explorer.input_focus,
            InputId::ExplorerFind => &self.explorer.find.focus,
            InputId::OutlineFind => &self.outline_pane.find.focus,
            InputId::DebugHoverFind => &self.debug_hover.find.focus,
            InputId::ReplFind => &self.debug_console.find.focus,
            InputId::Find => &self.find.find_focus,
            InputId::Replace => &self.find.replace_focus,
            InputId::Search(field) => &self.search.input(field).focus,
            InputId::KeybindingsSearch => &self.keybindings_editor.search_focus,
            InputId::KeybindingsWhen => &self.keybindings_editor.when_focus,
            InputId::SearchEditor(field) => &self.search_editor_widget.view.input(field).focus,
            InputId::OutputFilter => &self.output_view.filter_focus,
            InputId::ProblemsFilter => &self.problems.filter_focus,
            InputId::ScmInput => &self.scm.input_focus,
            InputId::ExtensionsSearch => &self.extensions_viewlet.search_focus,
            InputId::SettingsSearch => &self.settings_editor.search_focus,
            InputId::SettingsValue => &self.settings_editor.value_focus,
            InputId::ProfileName => self.user_data_profiles.editor.name_focus.as_ref().unwrap_or(&self.settings_editor.value_focus),
            InputId::IconSelectSearch => self.icon_select.search_focus.as_ref().unwrap_or(&self.settings_editor.value_focus),
            InputId::SettingsListKey => &self.settings_editor.list.key_focus,
            InputId::SettingsListValue => &self.settings_editor.list.value_focus,
            InputId::DebugView => &self.debug_view.input_focus,
            InputId::BreakpointWidget => &self.debug_view.widget_focus,
            InputId::CommentsFilter => &self.comments.view.filter_focus,
            InputId::TestingFilter => &self.testing_view.filter.focus,
            InputId::DebugConsoleFilter => &self.debug_console.filter_focus,
            InputId::DebugConsole => &self.debug_console.input_focus,
            InputId::TerminalFind => &self.terminal_view.find.focus,
            InputId::NotebookFind => &self.notebook_views.find.find_focus,
            InputId::NotebookReplace => &self.notebook_views.find.replace_focus,
            InputId::Rename => &self.rename.focus,
            InputId::TrustedPath => self.trust_editor.path_focus.as_ref().unwrap_or(&self.rename.focus),
            InputId::Dialog(index) => self.dialog_input(index).map_or(&self.rename.focus, |input| &input.focus),
        }
    }

    fn input_box(&self, id: InputId) -> Option<&InputBox> {
        match id {
            InputId::QuickInput => self.quick_inputs.current().map(|input| &input.input_box),
            InputId::Explorer => self.explorer.edit.as_ref().map(|edit| &edit.input),
            InputId::ExplorerFind => Some(&self.explorer.find.input),
            InputId::OutlineFind => Some(&self.outline_pane.find.input),
            InputId::DebugHoverFind => Some(&self.debug_hover.find.input),
            InputId::ReplFind => Some(&self.debug_console.find.input),
            InputId::Find => Some(&self.find.find_input),
            InputId::Replace => Some(&self.find.replace_input),
            InputId::Search(field) => Some(&self.search.input(field).value),
            InputId::KeybindingsSearch => Some(&self.keybindings_editor.search),
            InputId::KeybindingsWhen => self.keybindings_editor.when.as_ref().map(|when| &when.input),
            InputId::SearchEditor(field) => Some(&self.search_editor_widget.view.input(field).value),
            InputId::OutputFilter => Some(&self.output_view.filter),
            InputId::ProblemsFilter => Some(&self.problems.filter),
            InputId::ScmInput => Some(&self.scm.input),
            InputId::ExtensionsSearch => Some(&self.extensions_viewlet.search),
            InputId::SettingsSearch => Some(&self.settings_editor.search),
            InputId::SettingsValue => self.settings_editor.value.as_ref().map(|(_, input)| input),
            InputId::ProfileName => Some(&self.user_data_profiles.editor.name),
            InputId::IconSelectSearch => self.icon_select.picker.as_ref().map(|picker| &picker.search),
            InputId::SettingsListKey => Some(&self.settings_editor.list.key),
            InputId::SettingsListValue => Some(&self.settings_editor.list.value),
            InputId::DebugView => self.debug_view.editing.as_ref().map(|_| &self.debug_view.input),
            InputId::BreakpointWidget => self.breakpoint_widget.as_ref().map(|widget| &widget.input),
            InputId::CommentsFilter => Some(&self.comments.view.filter),
            InputId::TestingFilter => Some(&self.testing_view.filter.input),
            InputId::DebugConsoleFilter => Some(&self.debug_console.filter),
            InputId::DebugConsole => Some(&self.debug_console.input),
            InputId::TerminalFind => Some(&self.terminal_view.find.input),
            InputId::NotebookFind => Some(&self.notebook_views.find.find_input),
            InputId::NotebookReplace => Some(&self.notebook_views.find.replace_input),
            InputId::Rename => self.rename.widget.as_ref().map(|widget| &widget.input),
            InputId::TrustedPath => self.trust_editor.edit.as_ref().map(|(_, input)| input),
            InputId::Dialog(index) => self.dialog_input(index).map(|input| &input.input),
        }
    }

    /// The input element with the keyboard focus.
    pub(super) fn focused_input(&self, window: &Window) -> Option<InputId> {
        self.input_ids().find(|id| self.input_focus(*id).is_focused(window))
    }

    /// Any input element in an IME composition: the IME owns the keys.
    pub(super) fn input_composing(&self) -> bool {
        self.input_ids().any(|id| self.input_view(id).marked.is_some())
    }

    fn input_ids(&self) -> impl Iterator<Item = InputId> + use<> {
        let dialog_inputs = self.dialogs.first().map_or(0, |shown| shown.inputs.len());
        INPUTS.into_iter().chain(SEARCH_FIELDS.map(InputId::Search)).chain(SEARCH_EDITOR_FIELDS.map(InputId::SearchEditor)).chain((0..dialog_inputs).map(InputId::Dialog))
    }

    /// Runs `edit` on the element's value and restarts the caret blink.
    pub(super) fn edit_input_box(&mut self, id: InputId, window: &mut Window, cx: &mut Context<Self>, edit: impl FnOnce(&mut InputBox)) -> Outcome {
        self.input_view_mut(id).caret_moved = cx.background_executor().now();
        match id {
            InputId::QuickInput => {
                let before = self.quick_inputs.current().map(|input| input.input_box.value.clone());
                let outcome = self.with_current_quick_input(window, cx, |input| input.edit_input(edit));
                // quickInputBox.ts `hideHoverOnValueChange`: typing hides the hover a key down leaves.
                if self.quick_inputs.current().map(|input| &input.input_box.value) != before.as_ref() {
                    self.dismiss_hover(cx);
                }
                outcome
            }
            InputId::Explorer => {
                self.edit_explorer_input(edit, cx);
                Outcome::done()
            }
            InputId::ExplorerFind => {
                self.edit_explorer_find_input(edit, window, cx);
                Outcome::done()
            }
            InputId::OutlineFind => {
                self.edit_outline_find_input(edit, cx);
                Outcome::done()
            }
            InputId::DebugHoverFind => {
                self.edit_debug_hover_find_input(edit, cx);
                Outcome::done()
            }
            InputId::ReplFind => {
                self.edit_repl_find_input(edit, cx);
                Outcome::done()
            }
            InputId::Find | InputId::Replace => {
                self.edit_find_input(id, edit, window, cx);
                Outcome::done()
            }
            InputId::Search(field) => {
                self.edit_search_input(field, edit, window, cx);
                Outcome::done()
            }
            InputId::KeybindingsSearch => {
                self.edit_keybindings_search(edit, window, cx);
                Outcome::done()
            }
            InputId::KeybindingsWhen => {
                self.edit_when_input(edit, cx);
                Outcome::done()
            }
            InputId::SearchEditor(field) => {
                self.edit_search_editor_input(field, edit, window, cx);
                Outcome::done()
            }
            InputId::OutputFilter => {
                self.edit_output_filter(edit, window, cx);
                Outcome::done()
            }
            InputId::ProblemsFilter => {
                self.edit_problems_filter(edit, window, cx);
                Outcome::done()
            }
            InputId::ScmInput => {
                self.edit_scm_input(edit, window, cx);
                Outcome::done()
            }
            InputId::ExtensionsSearch => {
                self.edit_extensions_search(edit, window, cx);
                Outcome::done()
            }
            InputId::SettingsSearch => {
                self.edit_settings_search(edit, window, cx);
                Outcome::done()
            }
            InputId::SettingsValue => {
                self.edit_settings_value(edit, window, cx);
                Outcome::done()
            }
            InputId::ProfileName => {
                self.edit_profile_name(edit, cx);
                Outcome::done()
            }
            InputId::IconSelectSearch => {
                self.edit_icon_select_search(edit, cx);
                Outcome::done()
            }
            InputId::SettingsListKey | InputId::SettingsListValue => {
                self.edit_settings_list_input(id == InputId::SettingsListKey, edit, cx);
                Outcome::done()
            }
            InputId::DebugView => {
                self.edit_debug_view_input(edit, cx);
                Outcome::done()
            }
            InputId::BreakpointWidget => {
                self.edit_breakpoint_widget_input(edit, cx);
                Outcome::done()
            }
            InputId::CommentsFilter => {
                self.edit_comments_filter(edit, window, cx);
                Outcome::done()
            }
            InputId::TestingFilter => {
                self.edit_testing_filter(edit, window, cx);
                Outcome::done()
            }
            InputId::DebugConsoleFilter => {
                self.edit_debug_console_filter(edit, window, cx);
                Outcome::done()
            }
            InputId::DebugConsole => {
                self.edit_debug_console_input(edit, cx);
                Outcome::done()
            }
            InputId::TerminalFind => {
                self.edit_terminal_find_input(edit, cx);
                Outcome::done()
            }
            InputId::NotebookFind | InputId::NotebookReplace => {
                self.edit_notebook_find_input(id, edit, cx);
                Outcome::done()
            }
            InputId::Rename => {
                if let Some(widget) = self.rename.widget.as_mut() {
                    edit(&mut widget.input);
                    cx.notify();
                }
                Outcome::done()
            }
            InputId::TrustedPath => {
                self.edit_trusted_path_input(edit, cx);
                Outcome::done()
            }
            InputId::Dialog(index) => {
                if let Some(input) = self.dialogs.first_mut().and_then(|shown| shown.inputs.get_mut(index)) {
                    edit(&mut input.input);
                    cx.notify();
                }
                Outcome::done()
            }
        }
    }

    /// Whether the focused `id`'s caret shows `since_moved` after an edit or move. Native carets blink at a 1s period; the
    /// inputs that are code editors with simpleEditorOptions.ts's `cursorBlinking` keep it under "solid", and in a
    /// screenshot as ref-screenshot's `editor.cursorBlinking: solid` does.
    pub(super) fn input_caret_on(&self, id: InputId, since_moved: Duration) -> bool {
        let code_editor = matches!(id, InputId::SettingsSearch | InputId::ExtensionsSearch | InputId::ScmInput | InputId::DebugConsole | InputId::BreakpointWidget);
        if code_editor {
            if self.input_carets_hidden || self.global_editor_option(&CURSOR_BLINKING) == "solid" {
                return true;
            }
        } else if self.input_carets_hidden {
            return false;
        }
        (since_moved.as_millis() / 500) % 2 == 0
    }

    /// The caret blinks while the input has focus; a key restarts the blink.
    pub(super) fn blink_caret(&mut self, id: InputId, window: &mut Window, cx: &mut Context<Self>) {
        self.input_view_mut(id).caret_moved = cx.background_executor().now();
        self.input_view_mut(id).blink = Some(cx.spawn_in(window, async move |workbench, cx| {
            loop {
                cx.background_executor().timer(Duration::from_millis(500)).await;
                if workbench.update(cx, |_, cx| cx.notify()).is_err() {
                    return;
                }
            }
        }));
    }

    /// The text commands of the focused input element by their editor ids (`MultiCommand`s fall back to the native input).
    pub(super) fn input_text_command(&mut self, command: &str, window: &mut Window, cx: &mut Context<Self>) -> Option<Outcome> {
        let id = self.focused_input(window)?;
        let selected = self.input_box(id)?.selected_text();
        let password = id == InputId::QuickInput && self.quick_inputs.current().is_some_and(|input| input.password);
        match command {
            "editor.action.clipboardCopyAction" | "editor.action.clipboardCutAction" if selected.is_empty() || password => return Some(Outcome::done()),
            "editor.action.clipboardCopyAction" | "editor.action.clipboardCutAction" => cx.write_to_clipboard(gpui::ClipboardItem::new_string(selected)),
            _ => {}
        }
        let pasted = cx.read_from_clipboard().and_then(|item| item.text()).unwrap_or_default();
        Some(self.edit_input_box(id, window, cx, |input| match command {
            "undo" => input.undo(false),
            "redo" => input.undo(true),
            "editor.action.selectAll" => input.select_all(),
            "editor.action.clipboardCutAction" => input.insert(None, ""),
            // The find widget's textareas keep the line breaks of what is pasted, a single-line input drops them.
            "editor.action.clipboardPasteAction" if matches!(id, InputId::Find | InputId::Replace) => input.insert(None, &super::find_widget::textarea_value(&pasted)),
            "editor.action.clipboardPasteAction" => input.insert(None, &pasted.replace(['\r', '\n'], "")),
            _ => {}
        }))
    }

    /// Keys of the input element that no keybinding took: caret moves and deletes.
    fn input_key_down(&mut self, id: InputId, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        let keystroke = &event.keystroke;
        let modifiers = keystroke.modifiers;
        // findWidget.ts `_onFindInputKeyDown`: Ctrl+Enter no keybinding took inserts a line break.
        if matches!(id, InputId::Find | InputId::Replace) && keystroke.key == "enter" && modifiers == (Modifiers { control: true, ..Modifiers::default() }) {
            cx.stop_propagation();
            self.edit_input_box(id, window, cx, |input| input.insert(None, "\n"));
            return;
        }
        if modifiers.control || self.input_view(id).marked.is_some() {
            return;
        }
        let word = modifiers.alt;
        let line = modifiers.platform;
        let motion = |back: bool| match (back, line, word) {
            (true, true, _) => Motion::Home,
            (false, true, _) => Motion::End,
            (true, false, true) => Motion::WordLeft,
            (false, false, true) => Motion::WordRight,
            (true, false, false) => Motion::Left,
            (false, false, false) => Motion::Right,
        };
        if let InputId::Search(field) = id
            && self.search_input_key(field, keystroke, window, cx)
        {
            cx.stop_propagation();
            return;
        }
        if let InputId::SearchEditor(field) = id
            && self.search_editor_input_key(field, keystroke, window, cx)
        {
            cx.stop_propagation();
            return;
        }
        if id == InputId::Explorer && self.explorer_input_key(&keystroke.key, window, cx) {
            cx.stop_propagation();
            return;
        }
        if id == InputId::TrustedPath && !modifiers.platform && !modifiers.alt && !modifiers.shift && self.trusted_path_input_key(&keystroke.key, window, cx) {
            cx.stop_propagation();
            return;
        }
        if id == InputId::ExplorerFind && self.explorer_find_input_key(keystroke, window, cx) {
            cx.stop_propagation();
            return;
        }
        if id == InputId::OutlineFind && self.outline_find_input_key(keystroke, window, cx) {
            cx.stop_propagation();
            return;
        }
        if id == InputId::DebugHoverFind && self.debug_hover_find_input_key(keystroke, window, cx) {
            cx.stop_propagation();
            return;
        }
        if id == InputId::ReplFind && self.repl_find_input_key(keystroke, window, cx) {
            cx.stop_propagation();
            return;
        }
        if matches!(id, InputId::SettingsListKey | InputId::SettingsListValue) && self.settings_list_input_key(keystroke, window, cx) {
            cx.stop_propagation();
            return;
        }
        if matches!(id, InputId::Find | InputId::Replace) && self.find_input_key(id, keystroke, window, cx) {
            cx.stop_propagation();
            return;
        }
        if matches!(id, InputId::NotebookFind | InputId::NotebookReplace) && self.notebook_find_input_key(id, keystroke, window, cx) {
            cx.stop_propagation();
            return;
        }
        let extend = modifiers.shift;
        let edit: Box<dyn FnOnce(&mut InputBox)> = match keystroke.key.as_str() {
            "left" => Box::new(move |input| input.move_caret(motion(true), extend)),
            "right" => Box::new(move |input| input.move_caret(motion(false), extend)),
            "home" => Box::new(move |input| input.move_caret(Motion::Home, extend)),
            "end" => Box::new(move |input| input.move_caret(Motion::End, extend)),
            "up" if line => Box::new(move |input| input.move_caret(Motion::ValueStart, extend)),
            "down" if line => Box::new(move |input| input.move_caret(Motion::ValueEnd, extend)),
            "up" | "down" if self.input_box(id).is_some_and(|input| input.value.contains('\n')) => {
                let Some(target) = self.input_vertical_target(id, keystroke.key == "down") else { return };
                Box::new(move |input| input.selection = if extend { (input.selection.0, target) } else { (target, target) })
            }
            "backspace" => Box::new(move |input| input.delete(motion(true))),
            "delete" => Box::new(move |input| input.delete(motion(false))),
            // Tab moves the focus between the widget's controls; the input is the only one the port draws focusable.
            "tab" => Box::new(|_| {}),
            _ => return,
        };
        cx.stop_propagation();
        self.edit_input_box(id, window, cx, edit);
    }

    /// A press in the input text puts the caret there; a double press selects the word, a triple one all.
    fn input_mouse_down(&mut self, id: InputId, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        window.focus(&self.input_focus(id).clone(), cx);
        let index = self.input_view(id).text.borrow().index_at(f32::from(event.position.x), f32::from(event.position.y));
        self.input_view_mut(id).selecting = true;
        let extend = event.modifiers.shift;
        let clicks = event.click_count;
        self.edit_input_box(id, window, cx, |input| match clicks {
            1 if extend => input.selection.1 = index,
            1 => input.selection = (index, index),
            2 => input.select_word_at(index),
            _ => input.select_all(),
        });
    }

    fn input_mouse_move(&mut self, id: InputId, event: &MouseMoveEvent, window: &mut Window, cx: &mut Context<Self>) {
        if !self.input_view(id).selecting || event.pressed_button != Some(MouseButton::Left) {
            return;
        }
        let index = self.input_view(id).text.borrow().index_at(f32::from(event.position.x), f32::from(event.position.y));
        self.edit_input_box(id, window, cx, |input| input.selection.1 = index);
    }

    /// Up and Down in a textarea: the caret goes to the closest x on the line above or below, past the first or
    /// last line to the value's start or end.
    fn input_vertical_target(&self, id: InputId, down: bool) -> Option<usize> {
        let input = self.input_box(id)?;
        let text = self.input_view(id).text.borrow();
        let (row, line, byte) = text.line_of(input.selection.1)?;
        let x = f32::from(line.x_for_index(byte)) + text.left - text.scroll;
        let target = match (down, row) {
            (false, 0) => return Some(0),
            (true, row) if row + 1 == text.lines.len() => return Some(input.len()),
            (true, row) => row + 1,
            (false, row) => row - 1,
        };
        Some(text.index_at(x, text.top + (target as f32 + 0.5) * text.line_height))
    }

    /// The input handler's view of the value: UTF-16 offsets.
    pub(super) fn input_text_for_range(&self, id: InputId, range: Range<usize>, adjusted_range: &mut Option<Range<usize>>) -> Option<String> {
        let units: Vec<u16> = self.input_box(id)?.value.encode_utf16().collect();
        let range = range.start.min(units.len())..range.end.min(units.len());
        *adjusted_range = Some(range.clone());
        Some(String::from_utf16_lossy(&units[range]))
    }

    pub(super) fn input_selected_range(&self, id: InputId) -> Option<UTF16Selection> {
        let input = self.input_box(id)?;
        let (anchor, head) = (chars_to_utf16(&input.value, input.selection.0), chars_to_utf16(&input.value, input.selection.1));
        Some(UTF16Selection { range: anchor.min(head)..anchor.max(head), reversed: head < anchor })
    }

    /// Typed text and IME composition; marked text replaces the previous marked text and stays marked.
    pub(super) fn input_replace(&mut self, id: InputId, range: Option<Range<usize>>, text: &str, mark: bool, window: &mut Window, cx: &mut Context<Self>) {
        let Some(input) = self.input_box(id) else { return };
        let range = range.or(self.input_view(id).marked.clone()).map(|range| utf16_to_chars(&input.value, range.start)..utf16_to_chars(&input.value, range.end));
        let start = range.as_ref().map_or(input.selected_range().start, |range| range.start);
        let start_utf16 = chars_to_utf16(&input.value, start);
        self.input_view_mut(id).marked = (mark && !text.is_empty()).then(|| start_utf16..start_utf16 + text.encode_utf16().count());
        self.edit_input_box(id, window, cx, |input| input.insert(range, text));
    }

    /// The input element: the value (or placeholder) with its selection, marked text and caret.
    pub(super) fn input_text(&self, id: InputId, look: InputLook, cx: &mut Context<Self>) -> impl IntoElement {
        let input = self.input_box(id).cloned().unwrap_or_default();
        let view = self.input_view(id);
        let display: String = if look.password { input.value.chars().map(|_| '\u{2022}').collect() } else { input.value.clone() };
        let byte_at = |chars: usize| display.char_indices().nth(chars).map_or(display.len(), |(byte, _)| byte);
        let selection = byte_at(input.selected_range().start)..byte_at(input.selected_range().end);
        let caret = byte_at(input.selection.1);
        let marked = view.marked.clone().map(|range| byte_at(utf16_to_chars(&input.value, range.start))..byte_at(utf16_to_chars(&input.value, range.end)));
        let placeholder = look.placeholder.filter(|_| input.value.is_empty());
        let text_color = self.foreground_or("input.foreground");
        let placeholder_color = self.color("input.placeholderForeground");
        let selection_color = self.color(if look.focused { "selection.background" } else { "editor.inactiveSelectionBackground" });
        let selection_color = if self.theme.color("selection.background").is_some() { selection_color } else { self.color("editor.selectionBackground") };
        let caret_on = look.focused && self.input_caret_on(id, cx.background_executor().now().saturating_duration_since(view.caret_moved));
        // A Monaco cursor is `lineHeight` tall; these inputs' elements are one editor line.
        let full_height_caret = matches!(id, InputId::SettingsSearch | InputId::DebugConsole);
        let layout = view.text.clone();
        let focus = self.input_focus(id).clone();
        let workbench = cx.entity();
        div()
            .id(match id {
                InputId::QuickInput => gpui::ElementId::from("quick-input-text"),
                InputId::Explorer => "explorer-input-text".into(),
                InputId::ExplorerFind => "explorer-find-input-text".into(),
                InputId::OutlineFind => "outline-find-input-text".into(),
                InputId::DebugHoverFind => "debug-hover-find-input-text".into(),
                InputId::ReplFind => "repl-find-input-text".into(),
                InputId::Find => "find-input-text".into(),
                InputId::Replace => "replace-input-text".into(),
                InputId::Search(field) => ("search-input-text", field as usize).into(),
                InputId::KeybindingsSearch => "keybindings-search-text".into(),
                InputId::KeybindingsWhen => "keybindings-when-text".into(),
                InputId::SearchEditor(field) => ("search-editor-input-text", field as usize).into(),
                InputId::OutputFilter => "output-filter-text".into(),
                InputId::ProblemsFilter => "problems-filter-text".into(),
                InputId::ScmInput => "scm-input-text".into(),
                InputId::ExtensionsSearch => "extensions-search-text".into(),
                InputId::SettingsSearch => "settings-search-text".into(),
                InputId::SettingsValue => "settings-value-text".into(),
                InputId::ProfileName => "profile-name-text".into(),
                InputId::IconSelectSearch => "icon-select-search-text".into(),
                InputId::SettingsListKey => "settings-list-key-text".into(),
                InputId::SettingsListValue => "settings-list-value-text".into(),
                InputId::DebugView => "debug-view-input-text".into(),
                InputId::BreakpointWidget => "breakpoint-widget-input-text".into(),
                InputId::CommentsFilter => "comments-filter-text".into(),
                InputId::TestingFilter => "testing-filter-text".into(),
                InputId::DebugConsoleFilter => "debug-console-filter-text".into(),
                InputId::DebugConsole => "debug-console-input-text".into(),
                InputId::TerminalFind => "terminal-find-text".into(),
                InputId::NotebookFind => "notebook-find-text".into(),
                InputId::NotebookReplace => "notebook-replace-text".into(),
                InputId::Rename => "rename-input-text".into(),
                InputId::TrustedPath => "trusted-path-input-text".into(),
                InputId::Dialog(index) => ("dialog-input-text", index).into(),
            })
            .flex_1()
            .h_full()
            .overflow_hidden()
            // inputBox.css: the input element has the text cursor.
            .cursor_text()
            // The find widget of a code editor without the focus shares the focused one's handles (find_widget.rs `sibling`).
            .when(!(matches!(id, InputId::Find | InputId::Replace) && self.editor_groups.drawing_inactive), |input| input.track_focus(&focus))
            .on_key_down(cx.listener(move |workbench, event, window, cx| workbench.input_key_down(id, event, window, cx)))
            .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event, window, cx| workbench.input_mouse_down(id, event, window, cx)))
            .on_mouse_move(cx.listener(move |workbench, event, window, cx| workbench.input_mouse_move(id, event, window, cx)))
            .on_mouse_up(MouseButton::Left, cx.listener(move |workbench, _, _, _| workbench.input_view_mut(id).selecting = false))
            .on_mouse_up_out(MouseButton::Left, cx.listener(move |workbench, _, _, _| workbench.input_view_mut(id).selecting = false))
            .child(
                canvas(
                    move |_, _, _| (),
                    move |bounds, _, window, cx| {
                        let font: Font = window.text_style().font();
                        let font_size = window.text_style().font_size.to_pixels(window.rem_size());
                        let line_height = px(18.);
                        let origin_y = bounds.origin.y + (bounds.size.height - line_height) / 2.;
                        if let Some(placeholder) = placeholder {
                            let shape = |text: String, window: &mut Window| {
                                let run = TextRun { len: text.len(), font: font.clone(), color: placeholder_color.into(), background_color: None, underline: None, strikethrough: None };
                                window.text_system().shape_line(text.into(), font_size, &[run], None)
                            };
                            // inputBox.css `text-overflow: ellipsis` on the placeholder.
                            let mut line = shape(placeholder.clone(), window);
                            let mut kept: Vec<char> = placeholder.chars().collect();
                            while line.width > bounds.size.width && !kept.is_empty() {
                                kept.pop();
                                line = shape(format!("{}\u{2026}", kept.iter().collect::<String>()), window);
                            }
                            let _ = line.paint(point(bounds.origin.x, origin_y), line_height, gpui::TextAlign::Left, None, window, cx);
                        }
                        let plain = |len: usize| TextRun { len, font: font.clone(), color: text_color.into(), background_color: None, underline: None, strikethrough: None };
                        // The find widget's textarea: lines 19px apart below its 2px padding, scrolled to the caret.
                        let multiline = display.contains('\n');
                        let (line_height, content_top) = if multiline { (px(19.), bounds.origin.y + px(2.)) } else { (line_height, origin_y) };
                        let mut lines = Vec::new();
                        let (mut byte_start, mut char_start) = (0, 0);
                        for line_text in display.split('\n') {
                            let byte_end = byte_start + line_text.len();
                            let mut runs = Vec::new();
                            match marked.as_ref().map(|marked| marked.start.clamp(byte_start, byte_end)..marked.end.clamp(byte_start, byte_end)) {
                                Some(marked) if !marked.is_empty() => {
                                    runs.push(plain(marked.start - byte_start));
                                    let underline = UnderlineStyle { thickness: px(1.), color: Some(text_color.into()), wavy: false };
                                    runs.push(TextRun { underline: Some(underline), ..plain(marked.len()) });
                                    runs.push(plain(byte_end - marked.end));
                                }
                                _ => runs.push(plain(line_text.len())),
                            }
                            runs.retain(|run| run.len > 0);
                            let line = window.text_system().shape_line(line_text.to_string().into(), font_size, &runs, None);
                            lines.push((byte_start, char_start, line));
                            byte_start = byte_end + 1;
                            char_start += line_text.chars().count() + 1;
                        }
                        let caret_row = lines.iter().rposition(|(start, _, _)| *start <= caret).unwrap_or(0);
                        let caret_x = f32::from(lines[caret_row].2.x_for_index(caret - lines[caret_row].0));
                        let width = f32::from(bounds.size.width);
                        let content_width = lines.iter().map(|(_, _, line)| f32::from(line.width())).fold(0., f32::max);
                        let mut text = layout.borrow_mut();
                        let mut scroll = text.scroll;
                        if caret_x - scroll > width - 1. {
                            scroll = caret_x - width + 1.;
                        }
                        if caret_x < scroll {
                            scroll = caret_x;
                        }
                        scroll = scroll.min((content_width - width + 1.).max(0.)).max(0.);
                        let left = f32::from(bounds.origin.x) - scroll;
                        let mut scroll_y = 0.;
                        if multiline {
                            let (height, pitch) = (f32::from(bounds.size.height), f32::from(line_height));
                            // Chromium reveals the caret's glyph box, centered in its line, not the line with the padding.
                            let caret_line = &lines[caret_row].2;
                            let glyph_height = f32::from(caret_line.ascent + caret_line.descent);
                            let caret_top = 2. + caret_row as f32 * pitch + (pitch - glyph_height) / 2.;
                            scroll_y = text.scroll_y.max(caret_top + glyph_height - height).min(caret_top);
                            scroll_y = scroll_y.min(lines.len() as f32 * pitch + 4. - height).max(0.);
                        }
                        let top = f32::from(content_top) - scroll_y;
                        for (row, (start, _, line)) in lines.iter().enumerate() {
                            let row_top = px(top + row as f32 * f32::from(line_height));
                            let end = start + line.text.len();
                            if !selection.is_empty() && selection.start <= end && selection.end > *start {
                                let from = f32::from(line.x_for_index(selection.start.max(*start) - start));
                                let to = f32::from(line.x_for_index(selection.end.min(end) - start));
                                window.paint_quad(fill(gpui::Bounds::new(point(px(left + from), row_top), size(px(to - from), line_height)), selection_color));
                            }
                            let _ = line.paint(point(px(left), row_top), line_height, gpui::TextAlign::Left, None, window, cx);
                        }
                        if caret_on && selection.is_empty() {
                            let caret_top = px(top + caret_row as f32 * f32::from(line_height));
                            let (caret_y, caret_height) = if full_height_caret && !multiline { (bounds.origin.y, bounds.size.height) } else { (caret_top, line_height) };
                            window.paint_quad(fill(gpui::Bounds::new(point(px(left + caret_x), caret_y), size(px(1.), caret_height)), text_color));
                        }
                        let lines = lines.into_iter().map(|(_, char_start, line)| (char_start, line)).collect();
                        *text = InputText { lines, left: f32::from(bounds.origin.x), top, line_height: f32::from(line_height), scroll, scroll_y };
                        drop(text);
                        window.handle_input(&focus, ElementInputHandler::new(bounds, workbench), cx);
                    },
                )
                .size_full(),
            )
    }
}

/// The char offset of a UTF-16 offset into `text`; an offset inside a surrogate pair rounds up.
pub fn utf16_to_chars(text: &str, offset: usize) -> usize {
    let mut units = 0;
    for (index, c) in text.chars().enumerate() {
        if units >= offset {
            return index;
        }
        units += c.len_utf16();
    }
    text.chars().count()
}

pub fn chars_to_utf16(text: &str, chars: usize) -> usize {
    text.chars().take(chars).map(char::len_utf16).sum()
}