Visual Studio Code, rebuilt in Rust
Rust
//! The quick input widget: platform/quickinput/browser/quickInputController.ts with its list
//! (quickInputList.ts), laid out and colored as media/quickInput.css draws it. The store keeps every quick
//! input with its owner (main_thread_quick_open.rs); the widget shows one of them at a time.
use std::cell::Cell;
use std::ops::Range;
use std::path::Path;
use std::rc::Rc;
use std::time::Duration;
use gpui::{
Animation, AnimationExt, AnyElement, App, Bounds, BoxShadow, ClickEvent, DispatchPhase, Context, Div, FocusHandle, FontWeight, HighlightStyle, ListAlignment, ListOffset, ListState,
MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, Rgba, Stateful, StyledText, Subscription, Task, Window, canvas, div, list, point, prelude::*, px, rgba,
};
use serde_json::Value;
use super::Workbench;
use super::hover::{HoverContent, HoverOptions};
use super::input_box_view::{InputId, InputLook, InputView};
use crate::commands::Outcome;
use crate::main_thread_quick_open::Owner;
use crate::quick_input::{Button, Event, Focus, Header, Kind, QuickInput, Row, Severity, drag_layout};
/// `QuickInputController.MAX_WIDTH`.
const MAX_WIDTH: f32 = 600.;
/// `QuickInputDragAndDropController._snapThreshold` and `_snapLineHorizontalRatio`.
const SNAP_THRESHOLD: f32 = 20.;
const CENTER_SNAP_RATIO: f32 = 0.25;
/// `quickPickTop` in layout.ts while the title bar shows the command center.
const TOP: f32 = 6.;
/// The title bar part's height, `activeContainerOffset.top` for the drag.
const TITLE_BAR_HEIGHT: f32 = 35.;
const ROW_HEIGHT: f32 = 22.;
const DETAIL_ROW_HEIGHT: f32 = 44.;
/// quickInputList.ts `QuickInputItemDelegate.getHeight` of a `QuickPickSeparatorElement`.
const HEADER_HEIGHT: f32 = 30.;
const RADIUS: f32 = 8.;
/// quickInputController.ts, in StorageScope.APPLICATION.
const VIEWSTATE_STORAGE_KEY: &str = "workbench.quickInput.viewState";
pub struct QuickInputs {
inputs: Vec<(QuickInput, Owner)>,
next_id: i64,
visible: Option<i64>,
pub focus: FocusHandle,
/// The element focused before the widget showed, focused again when it hides (`previousFocusElement`).
previous_focus: Option<FocusHandle>,
focus_out: Option<Subscription>,
pub(super) list: ListState,
/// The input, its row order and `list_updates` the list was last laid out for, and the row it last revealed.
listed: (Option<i64>, Vec<usize>, u64),
revealed: Option<usize>,
hovered: Option<usize>,
/// The row whose header the pointer is over.
hovered_header: Option<usize>,
/// The hidden input, drawn while the close animation runs.
closing: Option<(QuickInput, Task<()>)>,
/// Counts the times the widget opened; a new count restarts the open animation.
opened: usize,
/// A busy input shows its progress bar after 800ms.
busy: Option<(i64, Task<()>)>,
busy_shown: bool,
pub input: InputView,
/// `QuickInputViewState`: the dragged position, top and center as fractions of the window.
view_state: Option<(Option<f32>, Option<f32>)>,
/// The pointer's offset from the widget's top left while the title or header is dragged.
drag: Option<Point<Pixels>>,
/// The widget's padding box as last painted.
bounds: Rc<Cell<Bounds<Pixels>>>,
}
impl QuickInputs {
pub fn new(cx: &mut App) -> Self {
QuickInputs {
inputs: Vec::new(),
next_id: 1,
visible: None,
focus: cx.focus_handle(),
previous_focus: None,
focus_out: None,
list: ListState::new(0, ListAlignment::Top, px(200.)),
listed: (None, Vec::new(), 0),
revealed: None,
hovered: None,
hovered_header: None,
closing: None,
opened: 0,
busy: None,
busy_shown: false,
input: InputView::default(),
view_state: None,
drag: None,
bounds: Rc::default(),
}
}
pub fn add(&mut self, mut input: QuickInput, owner: Owner) -> i64 {
let id = self.next_id;
self.next_id += 1;
input.id = id;
self.inputs.push((input, owner));
id
}
pub fn remove(&mut self, id: i64) {
self.inputs.retain(|(input, _)| input.id != id);
}
pub fn get(&self, id: i64) -> Option<&QuickInput> {
self.inputs.iter().find(|(input, _)| input.id == id).map(|(input, _)| input)
}
pub fn get_mut(&mut self, id: i64) -> Option<&mut QuickInput> {
self.inputs.iter_mut().find(|(input, _)| input.id == id).map(|(input, _)| input)
}
pub fn owner(&self, id: i64) -> Option<&Owner> {
self.inputs.iter().find(|(input, _)| input.id == id).map(|(_, owner)| owner)
}
pub fn owner_mut(&mut self, id: i64) -> Option<&mut Owner> {
self.inputs.iter_mut().find(|(input, _)| input.id == id).map(|(_, owner)| owner)
}
pub fn get_with_owner_mut(&mut self, id: i64) -> Option<(&mut QuickInput, &mut Owner)> {
self.inputs.iter_mut().find(|(input, _)| input.id == id).map(|(input, owner)| (input, owner))
}
pub fn find_id(&self, matches: impl Fn(&Owner) -> bool) -> Option<i64> {
self.inputs.iter().find(|(_, owner)| matches(owner)).map(|(input, _)| input.id)
}
pub fn find_mut(&mut self, matches: impl Fn(&Owner) -> bool) -> Option<&mut QuickInput> {
self.inputs.iter_mut().find(|(_, owner)| matches(owner)).map(|(input, _)| input)
}
/// `currentQuickInput`: the shown input.
pub fn current(&self) -> Option<&QuickInput> {
self.get(self.visible?)
}
pub(super) fn current_mut(&mut self) -> Option<&mut QuickInput> {
self.get_mut(self.visible?)
}
}
impl Workbench {
/// `QuickInputController.show`: the widget shows the input, hiding the one it showed before.
pub fn show_quick_input(&mut self, id: i64, window: &mut Window, cx: &mut Context<Self>) {
let inputs = &mut self.quick_inputs;
if inputs.visible == Some(id) {
return;
}
match inputs.visible.take() {
Some(previous) => {
if let Some(input) = inputs.get_mut(previous) {
input.did_hide();
}
}
None => {
inputs.previous_focus = window.focused(cx).filter(|focused| *focused != inputs.focus);
inputs.closing = None;
inputs.drag = None;
inputs.opened += 1;
}
}
let Some(input) = inputs.get_mut(id) else { return };
input.show();
inputs.visible = Some(id);
inputs.input.reset();
inputs.hovered = None;
inputs.revealed = None;
window.focus(&self.quick_inputs.focus, cx);
if self.quick_inputs.focus_out.is_none() {
let focus = self.quick_inputs.focus.clone();
self.quick_inputs.focus_out = Some(cx.on_focus_out(&focus, window, |workbench, _, window, cx| workbench.quick_input_focus_lost(window, cx)));
}
self.blink_caret(InputId::QuickInput, window, cx);
cx.notify();
}
pub fn hide_quick_input_by_id(&mut self, id: i64, window: &mut Window, cx: &mut Context<Self>) {
if self.quick_inputs.visible == Some(id) {
self.hide_quick_input(true, window, cx);
}
}
/// `QuickInputController.hide`: focus goes back where it was, unless the widget hid because it lost it.
fn hide_quick_input(&mut self, restore_focus: bool, window: &mut Window, cx: &mut Context<Self>) {
let Some(id) = self.quick_inputs.visible.take() else { return };
let Some(input) = self.quick_inputs.get_mut(id) else { return };
let closing = input.clone();
input.did_hide();
let close = cx.spawn(async move |workbench, cx| {
cx.background_executor().timer(Duration::from_millis(150)).await;
let _ = workbench.update(cx, |workbench, cx| {
workbench.quick_inputs.closing = None;
cx.notify();
});
});
self.quick_inputs.closing = Some((closing, close));
// An item's hover lives in the list's hover host and goes with it.
self.dismiss_hover(cx);
self.quick_inputs.input.reset();
let previous = self.quick_inputs.previous_focus.take();
if restore_focus && self.quick_inputs.focus.contains_focused(window, cx) {
match previous {
Some(previous) => {
if previous == self.editor_focus {
self.editor_text_focus_returned(cx);
}
window.focus(&previous, cx)
}
None => window.blur(cx),
}
}
cx.notify();
}
/// `QuickInput.dispose`: hides it, tells its owner, and forgets it.
pub fn dispose_quick_input(&mut self, id: i64, window: &mut Window, cx: &mut Context<Self>) {
self.hide_quick_input_by_id(id, window, cx);
self.flush_quick_input_events(window, cx);
self.quick_inputs.remove(id);
}
/// Hands the events of every quick input to its owner, oldest first, until none is left.
pub fn flush_quick_input_events(&mut self, window: &mut Window, cx: &mut Context<Self>) {
while let Some((id, events)) = self.quick_inputs.inputs.iter_mut().find(|(input, _)| !input.events.is_empty()).map(|(input, _)| (input.id, std::mem::take(&mut input.events))) {
for event in events {
self.deliver_quick_input_event(id, event, window, cx);
}
}
let busy = self.quick_inputs.current().filter(|input| input.busy).map(|input| input.id);
if busy != self.quick_inputs.busy.as_ref().map(|(id, _)| *id) {
self.quick_inputs.busy_shown = false;
self.quick_inputs.busy = busy.map(|id| {
let show = cx.spawn(async move |workbench, cx| {
cx.background_executor().timer(Duration::from_millis(800)).await;
let _ = workbench.update(cx, |workbench, cx| {
workbench.quick_inputs.busy_shown = true;
cx.notify();
});
});
(id, show)
});
}
cx.notify();
}
/// The `blur` of the widget: it hides unless it ignores focus out.
fn quick_input_focus_lost(&mut self, window: &mut Window, cx: &mut Context<Self>) {
// GPUI reports a window deactivation as focus out; the DOM keeps the active element there (dom.ts trackFocus).
if self.quick_inputs.focus.contains_focused(window, cx) {
return;
}
if self.quick_inputs.current().is_some_and(|input| !input.ignore_focus_out) {
self.hide_quick_input(false, window, cx);
self.flush_quick_input_events(window, cx);
}
}
/// Runs `change` on the shown input, then delivers what it fired.
pub(super) fn with_current_quick_input(&mut self, window: &mut Window, cx: &mut Context<Self>, change: impl FnOnce(&mut QuickInput)) -> Outcome {
let Some(input) = self.quick_inputs.current_mut() else { return Outcome::done() };
change(input);
self.flush_quick_input_events(window, cx);
Outcome::done()
}
/// The context keys of quickInputController.ts and quickInputService.ts.
pub(super) fn quick_input_context(&self, window: &Window, context: &mut std::collections::HashMap<String, Value>) {
let Some(input) = self.quick_inputs.current() else { return };
context.insert("inQuickOpen".into(), true.into());
// `contextKey` of the quick access provider: Quick Open's is `inFilesPicker`.
if let Some(Owner::QuickAccess(_)) = self.quick_inputs.owner(input.id)
&& super::quick_access::is_files_picker(&input.input_box.value)
{
context.insert("inFilesPicker".into(), true.into());
}
if let Some(Owner::QuickAccess(_)) = self.quick_inputs.owner(input.id)
&& super::quick_access::is_views_picker(&input.input_box.value)
{
context.insert("inViewsPicker".into(), true.into());
}
if !self.quick_inputs.focus.is_focused(window) {
return;
}
context.insert("inQuickInput".into(), true.into());
context.insert("inputFocus".into(), true.into());
let kind = match input.kind {
Kind::QuickPick => "quickPick",
Kind::InputBox => "inputBox",
Kind::Widget => "quickWidget",
};
context.insert("quickInputType".into(), kind.into());
context.insert("cursorAtEndOfQuickInputBox".into(), input.input_box.caret_at_end().into());
}
/// quickInputActions.ts and quickAccessActions.ts.
pub(super) fn register_quick_input_commands(&mut self) {
let focus_commands = [
("quickInput.next", Focus::Next),
("quickInput.previous", Focus::Previous),
("quickInput.first", Focus::First),
("quickInput.last", Focus::Last),
("quickInput.pageNext", Focus::NextPage),
("quickInput.pagePrevious", Focus::PreviousPage),
("quickInput.nextSeparator", Focus::NextSeparator),
("quickInput.previousSeparator", Focus::PreviousSeparator),
// The quick access fallback applies to quick navigation (Ctrl+Tab style pickers), which the port has none of.
("quickInput.nextSeparatorWithQuickAccessFallback", Focus::NextSeparator),
("quickInput.previousSeparatorWithQuickAccessFallback", Focus::PreviousSeparator),
("workbench.action.quickOpenSelectNext", Focus::Next),
("workbench.action.quickOpenSelectPrevious", Focus::Previous),
("workbench.action.quickOpenNavigateNext", Focus::Next),
("workbench.action.quickOpenNavigatePrevious", Focus::Previous),
("workbench.action.quickOpenNavigateNextInFilePicker", Focus::Next),
("workbench.action.quickOpenNavigatePreviousInFilePicker", Focus::Previous),
("workbench.action.quickOpenNavigateNextInViewPicker", Focus::Next),
("workbench.action.quickOpenNavigatePreviousInViewPicker", Focus::Previous),
];
for (id, focus) in focus_commands {
self.commands.register(id, move |workbench, _, window, cx| {
let page = workbench.quick_input_page_size(window);
workbench.with_current_quick_input(window, cx, |input| input.focus(focus, page))
});
}
self.commands.register("quickInput.accept", |workbench, _, window, cx| workbench.with_current_quick_input(window, cx, |input| input.accept(false)));
self.commands.register("quickInput.acceptInBackground", |workbench, _, window, cx| workbench.with_current_quick_input(window, cx, |input| input.accept(true)));
for id in ["workbench.action.acceptSelectedQuickOpenItem", "workbench.action.alternativeAcceptSelectedQuickOpenItem"] {
self.commands.register(id, |workbench, _, window, cx| workbench.with_current_quick_input(window, cx, QuickInput::accept_from_ui));
}
for id in ["quickInput.toggleCheckbox", "workbench.action.quickPickManyToggle"] {
self.commands.register(id, |workbench, _, window, cx| workbench.with_current_quick_input(window, cx, QuickInput::toggle));
}
for id in ["quickInput.hide", "workbench.action.closeQuickOpen"] {
self.commands.register(id, |workbench, _, window, cx| {
workbench.hide_quick_input(true, window, cx);
workbench.flush_quick_input_events(window, cx);
Outcome::done()
});
}
self.commands.register("workbench.action.focusQuickOpen", |workbench, _, window, cx| {
if workbench.quick_inputs.current().is_some() {
window.focus(&workbench.quick_inputs.focus, cx);
}
Outcome::done()
});
self.commands.register("workbench.action.quickInputBack", |workbench, _, window, cx| {
workbench.with_current_quick_input(window, cx, |input| {
if input.buttons.iter().any(|button| button.handle == -1) {
input.events.push(Event::TriggerButton(-1, None));
}
})
});
}
fn quick_input_page_size(&self, window: &Window) -> usize {
(self.quick_input_list_max_height(window) / ROW_HEIGHT).floor().max(1.) as usize
}
/// `QuickInputList.layout(height * 0.4)`: whole 44px rows plus 6px to show there is more.
fn quick_input_list_max_height(&self, window: &Window) -> f32 {
let height = f32::from(window.viewport_size().height) * 0.4;
(height / DETAIL_ROW_HEIGHT).floor() * DETAIL_ROW_HEIGHT + 6.
}
/// The widget, drawn over the workbench at the top center or where it was dragged.
pub(super) fn quick_input_widget(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<AnyElement> {
let (input, interactive) = match (self.quick_inputs.current(), self.quick_inputs.closing.as_ref()) {
(Some(input), _) => (input.clone(), true),
(None, Some((input, _))) => (input.clone(), false),
(None, None) => return None,
};
// Modern UI frosted glass (frostedGlass.css), on outside high contrast themes, drops the widget's animations.
let frosted = !self.theme.kind.is_high_contrast();
if frosted && !interactive {
return None;
}
let viewport = window.viewport_size();
let width = widget_width(f32::from(viewport.width));
let (top, left) = match self.quick_inputs.view_state {
Some((top, left)) => (top.map_or(TOP, |top| (f32::from(viewport.height) * top).round()), (f32::from(viewport.width) * left.unwrap_or(0.5) - width / 2.).round()),
None => (TOP, ((f32::from(viewport.width) - width) / 2.).round()),
};
let widget = div()
.id("quick-input-widget")
.absolute()
// quickInput.css `-webkit-app-region: no-drag`: the widget can lie over the title bar.
.occlude()
.top(px(top))
.left(px(left))
// The width is the content box; the 1px border goes outside it.
.w(px(width + if self.theme.color("widget.border").is_some() { 2. } else { 0. }))
.flex()
.flex_col()
// cornerRadius.large under Modern UI (roundedCorners.css).
.rounded(px(RADIUS))
.when(!frosted, |widget| widget.bg(self.color("quickInput.background")))
.when(frosted, |widget| widget.child(self.frosted_glass("quickInput.background", RADIUS)))
.when(interactive, |widget| widget.child(self.quick_input_drag_tracker(cx)))
.text_color(self.foreground_or("quickInput.foreground"))
.when_some(self.theme.color("widget.border"), |widget, border| widget.border_1().border_color(border))
// --vscode-shadow-xl blurs 20px; GPUI's blur_radius is the sigma, half the CSS blur.
.shadow(vec![BoxShadow { color: rgba(0x00000026).into(), offset: point(px(0.), px(0.)), blur_radius: px(10.), spread_radius: px(0.), inset: false }])
.when(interactive, |widget| widget.on_mouse_down_out(cx.listener(|workbench, _, window, cx| workbench.quick_input_focus_lost(window, cx))))
.when(input.shows_title_bar(), |widget| widget.child(self.quick_input_title(&input, cx)))
.when(input.description.as_ref().is_some_and(|description| !description.is_empty()), |widget| {
widget.child(div().mx(px(11.)).my(px(6.)).mr(px(6.)).child(input.description.clone().unwrap_or_default()))
})
.when(input.kind != Kind::Widget, |widget| widget.child(self.quick_input_header(&input, interactive, window, cx)))
.when(input.kind != Kind::Widget, |widget| widget.children(input.message().map(|message| self.quick_input_message(&input, message))))
// quickInput.ts `QuickPick.update`: no progress bar with a hidden input and no description; `QuickWidget.update` has none.
.when(input.kind == Kind::InputBox || input.kind == Kind::QuickPick && (!input.hide_input || input.description.as_ref().is_some_and(|description| !description.is_empty())), |widget| widget.child(self.quick_input_progress(&input)))
.when(input.kind == Kind::QuickPick, |widget| widget.child(self.quick_input_list(&input, interactive, window, cx)))
// The quick widget's element takes the focus from the widget's own handle, so focus inside it keeps it shown.
.when(input.kind == Kind::Widget, |widget| widget.track_focus(&self.quick_inputs.focus).children(self.icon_picker_quick_widget(width, window, cx)));
// quickInput.css: the open and close animations are `.modern-ui.monaco-enable-motion` ones.
if frosted || self.is_motion_reduced() {
return interactive.then(|| widget.into_any_element());
}
// GPUI has no element transforms, so the open (250ms) and close (150ms) animations fade without their 0.97/0.99 scale.
let ease = |t: f32| 1. - (1. - t).powi(4);
let element = if interactive {
widget.with_animation(("quick-input-open", self.quick_inputs.opened), Animation::new(Duration::from_millis(250)).with_easing(ease), |widget, delta| widget.opacity(delta)).into_any_element()
} else {
widget.with_animation(("quick-input-close", self.quick_inputs.opened), Animation::new(Duration::from_millis(150)).with_easing(ease), |widget, delta| widget.opacity(1. - delta)).into_any_element()
};
Some(element)
}
/// The `::before` layer of frostedGlass.css: the surface color at `frosted_glass_opacity` over a 12px blur of what
/// is behind it, inside a 1px border with `radius` corners. Without glass the solid surface color.
pub(super) fn frosted_glass(&self, surface: &str, radius: f32) -> impl IntoElement {
let mut color = self.color(surface);
let glass = self.frosted_glass_enabled();
if glass {
color.a *= self.frosted_glass_opacity();
}
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
// Inside the 1px border, so the corners follow the padding box.
let radii = gpui::Corners::all(px(radius - 1.));
match glass {
true => window.paint_backdrop_blur(bounds, radii, px(12.), color),
false => window.paint_quad(gpui::fill(bounds, color).corner_radii(radii)),
}
},
)
.absolute()
.inset_0()
}
/// frostedGlass.contribution.ts `update`: `workbench.modernUIFrostedGlass` on, transparency not reduced
/// (`workbench.reduceTransparency` on, or the macOS setting frostedGlass.css's `prefers-reduced-transparency`
/// reads whatever the setting says) and no high contrast theme.
pub(super) fn frosted_glass_enabled(&self) -> bool {
self.setting("workbench.modernUIFrostedGlass") != false
&& self.setting("workbench.reduceTransparency") != "on"
&& !system_reduces_transparency()
&& !self.theme.kind.is_high_contrast()
}
/// frostedGlass.contribution.ts `getOpacity`: `workbench.modernUIFrostedGlassOpacity` percent, 80 by default,
/// clamped to 50..100.
pub(super) fn frosted_glass_opacity(&self) -> f32 {
self.setting("workbench.modernUIFrostedGlassOpacity").as_f64().map_or(80., |value| value.clamp(50., 100.)) as f32 / 100.
}
/// Records the widget's bounds and, while it is dragged, follows the pointer anywhere in the window.
fn quick_input_drag_tracker(&self, cx: &mut Context<Self>) -> impl IntoElement {
let last_bounds = self.quick_inputs.bounds.clone();
let dragging = self.quick_inputs.drag.is_some();
let workbench = cx.entity();
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
last_bounds.set(bounds);
if !dragging {
return;
}
let moved = workbench.clone();
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if phase == DispatchPhase::Bubble {
moved.update(cx, |workbench, cx| workbench.quick_input_drag_to(event.position, window, cx));
}
});
window.on_mouse_event(move |_: &MouseUpEvent, phase, _, cx| {
if phase == DispatchPhase::Bubble {
workbench.update(cx, |workbench, cx| {
workbench.quick_inputs.drag = None;
workbench.save_quick_input_view_state();
cx.notify();
});
}
});
},
)
.absolute()
.inset_0()
}
/// `loadViewState`: the position stored by the last drag, if any.
pub(super) fn load_quick_input_view_state(&mut self) {
let storage = self.application_storage.lock().unwrap();
let data: Value = storage.get(VIEWSTATE_STORAGE_KEY).and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or_default();
self.quick_inputs.view_state = match (data["top"].as_f64(), data["left"].as_f64()) {
(None, None) => None,
(top, left) => Some((top.map(|top| top as f32), left.map(|left| left as f32))),
};
}
/// `saveViewState` in StorageScope.APPLICATION; the default position removes the key.
fn save_quick_input_view_state(&self) {
let mut storage = self.application_storage.lock().unwrap();
match self.quick_inputs.view_state {
Some((top, left)) => {
// JSON.stringify leaves out an undefined side.
let mut state = serde_json::Map::new();
if let Some(top) = top {
state.insert("top".into(), top.into());
}
if let Some(left) = left {
state.insert("left".into(), left.into());
}
storage.set(VIEWSTATE_STORAGE_KEY, Value::Object(state).to_string());
}
None => storage.delete(VIEWSTATE_STORAGE_KEY),
}
}
/// A press on the title or header starts a drag; a double click puts the widget back at the top center.
fn quick_input_drag_start(&mut self, event: &MouseDownEvent, _: &mut Window, cx: &mut Context<Self>) {
if event.click_count == 2 {
self.quick_inputs.view_state = None;
self.quick_inputs.drag = None;
self.save_quick_input_view_state();
cx.notify();
return;
}
let border = if self.theme.color("widget.border").is_some() { px(1.) } else { px(0.) };
self.quick_inputs.drag = Some(event.position - self.quick_inputs.bounds.get().origin + point(border, border));
cx.notify();
}
fn quick_input_drag_to(&mut self, position: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
let Some(offset) = self.quick_inputs.drag else { return };
let viewport = window.viewport_size();
let widget = self.quick_inputs.bounds.get().size;
let top_left = position - offset;
let window_size = (f32::from(viewport.width), f32::from(viewport.height));
let widget_size = (f32::from(widget.width), f32::from(widget.height));
let (top, left) = drag_layout(f32::from(top_left.y), f32::from(top_left.x), window_size, widget_size, TITLE_BAR_HEIGHT, TOP);
self.quick_inputs.view_state = Some((Some(top), Some(left)));
cx.notify();
}
/// `QuickInputDragAndDropController.setAlignment`: the top or the center snap line, centered across, saved as a
/// dragged position is.
pub(super) fn set_quick_input_alignment(&mut self, center: bool, window: &Window, cx: &mut Context<Self>) {
let viewport = window.viewport_size();
let (width, height) = (f32::from(viewport.width), f32::from(viewport.height));
let widget = widget_width(width);
let top = if center { (height * CENTER_SNAP_RATIO).round() } else { TOP };
let left = ((width / 2.).round() - (widget / 2.).round() + widget / 2.) / width;
self.quick_inputs.view_state = Some((Some(top / height), Some(left)));
self.save_quick_input_view_state();
cx.notify();
}
/// `QuickInputAlignmentContextKey`: `top` or `center` while the widget sits on that snap line and centered across
/// (`_layout` snaps within 20px), unset at any other position.
pub(super) fn quick_input_alignment(&self, window: &Window) -> Option<&'static str> {
let Some((top, left)) = self.quick_inputs.view_state else { return Some("top") };
let viewport = window.viewport_size();
let (width, height) = (f32::from(viewport.width), f32::from(viewport.height));
let widget = widget_width(width);
let centered_left = (width / 2.).round() - (widget / 2.).round();
if (width * left.unwrap_or(0.5) - widget / 2. - centered_left).abs() >= SNAP_THRESHOLD {
return None;
}
let top = top.map_or(TOP, |top| height * top);
if (top - TOP).abs() < SNAP_THRESHOLD {
Some("top")
} else if (top - (height * CENTER_SNAP_RATIO).round()).abs() < SNAP_THRESHOLD {
Some("center")
} else {
None
}
}
/// `.quick-input-titlebar`: the back button, the title, and the title buttons.
fn quick_input_title(&self, input: &QuickInput, cx: &mut Context<Self>) -> Div {
let (left, right): (Vec<&Button>, Vec<&Button>) = input.buttons.iter().filter(|button| button.location.is_none_or(|location| location <= 1)).partition(|button| button.handle == -1);
let title = input.title_text();
div()
.debug_selector(|| "quick-input-title".into())
.relative()
.flex()
.items_center()
.rounded_t(px(RADIUS))
.pt(px(2.))
.bg(self.color("quickInputTitle.background"))
.cursor_grab()
.on_mouse_down(MouseButton::Left, cx.listener(Self::quick_input_drag_start))
// The action bars are not drag areas (excludeNodes); in the flex row the back button moves the title right.
.child(div().ml(px(4.)).occlude().flex().children(left.into_iter().map(|button| self.quick_input_button(button, 20., cx))))
// The widget's line-height, 1.4 of its 13px font.
.child(div().flex_1().py(px(3.)).line_height(px(18.2)).text_center().child(if title.is_empty() { "\u{a0}".to_owned() } else { title }))
.child(div().mr(px(4.)).occlude().flex().gap(px(4.)).children(right.into_iter().map(|button| self.quick_input_button(button, 20., cx))))
}
/// A title, inline or input button: a 16px codicon in a `size` box, or the toggle's checked look.
fn quick_input_button(&self, button: &Button, size: f32, cx: &mut Context<Self>) -> AnyElement {
let codicon = match (&button.codicon, button.handle) {
(Some(codicon), _) => codicon.clone(),
(None, -1) => "arrow-left".to_owned(),
(None, _) => "blank".to_owned(),
};
let handle = button.handle;
let toggle = button.toggle;
let foreground = match toggle {
Some(true) => self.color("inputOption.activeForeground"),
_ => self.foreground_or("icon.foreground"),
};
let element = match &button.icon_path {
Some(icon) if button.codicon.is_none() => {
let path = if self.theme.kind.is_light() { &icon.light } else { &icon.dark };
div().size(px(size)).flex().items_center().justify_center().child(gpui::img(path.clone()).size(px(16.)))
}
_ => self.icon(&codicon, size, 16., foreground),
};
element
.id(("quick-input-button", handle as u64))
.cursor_pointer()
.rounded(px(4.))
.when(toggle == Some(true), |button| {
button.bg(self.color("inputOption.activeBackground")).border_1().border_color(self.color("inputOption.activeBorder"))
})
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
workbench.with_current_quick_input(window, cx, |input| {
if let Some(button) = input.buttons.iter_mut().find(|button| button.handle == handle) {
button.toggle = button.toggle.map(|checked| !checked);
input.events.push(Event::TriggerButton(handle, button.toggle));
}
});
}))
.into_any_element()
}
/// `.quick-input-header`: the check-all box, the input box with its count, inline buttons and OK.
fn quick_input_header(&self, input: &QuickInput, interactive: bool, window: &mut Window, cx: &mut Context<Self>) -> Div {
let checked = input.checked_count();
let pickable = input.rows.iter().filter(|row| row.item.pickable && !row.hidden).count();
let all_checked = pickable > 0 && input.order.iter().filter(|row| input.rows[**row].item.pickable).all(|row| input.rows[*row].checked);
let inline: Vec<&Button> = input.buttons.iter().filter(|button| button.location == Some(2)).collect();
div()
.flex()
.px(px(6.))
.pt(px(6.))
.pb(px(4.))
.when(input.hide_input, |header| header.p(px(0.)))
// Only the header itself is a drag area, so its children occlude it.
.cursor_grab()
.on_mouse_down(MouseButton::Left, cx.listener(Self::quick_input_drag_start))
.when(input.can_select_many && !input.hide_input && !input.hide_check_all, |header| {
header.child(
self.checkbox(all_checked, checked > 0 && !all_checked)
.id("quick-input-check-all")
.occlude()
.cursor_pointer()
.mt(px(4.))
.on_click(cx.listener(|workbench, _: &ClickEvent, window, cx| {
workbench.with_current_quick_input(window, cx, QuickInput::toggle_all);
})),
)
})
.when(!input.hide_input, |header| header.child(self.quick_input_box(input, interactive, window, cx).occlude()))
// quickInput.css: 5px before the first inline action, 4px between, 2px from the top; actionbar.css pads the label 3px.
.children(inline.into_iter().enumerate().map(|(i, button)| div().ml(px(if i == 0 { 5. } else { 4. })).mt(px(2.)).occlude().child(self.quick_input_button(button, 22., cx))))
.when(input.can_select_many || input.ok, |header| {
let label = input.ok_label.clone().unwrap_or_else(|| "OK".into());
header.child(self.quick_input_action_button("quick-input-ok", label, false).on_click(cx.listener(|workbench, _: &ClickEvent, window, cx| {
workbench.with_current_quick_input(window, cx, QuickInput::accept_from_ui);
})))
})
.when_some(input.custom_label.clone(), |header, label| {
header.child(self.quick_input_action_button("quick-input-custom", label, input.custom_secondary).on_click(cx.listener(|workbench, _: &ClickEvent, window, cx| {
workbench.with_current_quick_input(window, cx, |input| input.events.push(Event::Custom));
})))
})
}
/// quickInput.css `.quick-input-action`: the OK and custom buttons, 6px after the input, in the button colors.
fn quick_input_action_button(&self, id: &'static str, label: String, secondary: bool) -> gpui::Stateful<Div> {
let (background, foreground, hover) = match secondary {
true => ("button.secondaryBackground", "button.secondaryForeground", "button.secondaryHoverBackground"),
false => ("button.background", "button.foreground", "button.hoverBackground"),
};
div()
.id(id)
.occlude()
.cursor_pointer()
.ml(px(6.))
.h(px(26.))
.px(px(10.))
.flex()
.items_center()
.rounded(px(4.))
.bg(self.color(background))
.text_color(self.color(foreground))
.border_1()
.border_color(self.theme.color("button.border").unwrap_or(gpui::transparent_black().into()))
.hover(|button| button.bg(self.color(hover)))
.child(label)
}
/// The `.monaco-inputbox`: 26px, `input.*` colors, the focus border, the validation border, the count badge.
fn quick_input_box(&self, input: &QuickInput, interactive: bool, window: &mut Window, cx: &mut Context<Self>) -> Div {
let focused = interactive && self.quick_inputs.focus.is_focused(window);
let validation = match input.severity {
Severity::Info => self.theme.color("inputValidation.infoBorder"),
Severity::Warning => self.theme.color("inputValidation.warningBorder"),
Severity::Error => self.theme.color("inputValidation.errorBorder"),
Severity::Ignore => None,
};
let border = validation.or(focused.then(|| self.theme.color("focusBorder")).flatten()).or(self.theme.color("input.border"));
let input_buttons: Vec<&Button> = input.buttons.iter().filter(|button| button.location == Some(3)).collect();
let count = input.can_select_many.then(|| {
div()
.flex_none()
// .quick-input-count inherits the header's grab cursor.
.cursor_grab()
.mr(px(4.))
.px(px(4.))
.py(px(2.))
// modernUI roundedCorners.css and fontRamp.css: a round badge in the 10px label ramp.
.rounded_full()
.text_size(px(10.))
.bg(self.color("badge.background"))
.text_color(self.color("badge.foreground"))
.when_some(self.theme.color("contrastBorder"), |badge, border| badge.border_1().border_color(border))
.child(format!("{} Selected", input.checked_count()))
});
div()
.flex_1()
.cursor_text()
// 1px borders, 4px padding and the 15px normal line height of 13px text, measured on 1.147.
.h(px(25.))
.flex()
.items_center()
.rounded(px(4.))
.border_1()
.border_color(border.unwrap_or(rgba(0x00000000)))
.bg(self.color("input.background"))
.text_color(self.foreground_or("input.foreground"))
.when(input.can_select_many, |input_box| input_box.ml(px(5.)))
.child(div().flex_1().h_full().mx(px(6.)).flex().child(self.input_text(InputId::QuickInput, InputLook { password: input.password, placeholder: input.placeholder.clone(), focused }, cx)))
.children(count)
.children(input_buttons.into_iter().map(|button| div().mr(px(2.)).child(self.quick_input_button(button, 20., cx))))
}
/// `.quick-input-message`: the prompt, or the validation message in its severity's colors.
fn quick_input_message(&self, input: &QuickInput, message: String) -> Div {
let colors = match input.severity {
Severity::Info => Some(("inputValidation.infoBackground", "inputValidation.infoForeground", "inputValidation.infoBorder")),
Severity::Warning => Some(("inputValidation.warningBackground", "inputValidation.warningForeground", "inputValidation.warningBorder")),
Severity::Error => Some(("inputValidation.errorBackground", "inputValidation.errorForeground", "inputValidation.errorBorder")),
Severity::Ignore => None,
};
let message_box = div().mx(px(6.)).mt(px(-1.)).p(px(5.)).child(message);
match colors {
Some((background, foreground, border)) => message_box
.mb(px(-2.))
.bg(self.color(background))
.when_some(self.theme.color(foreground), |message_box, color| message_box.text_color(color))
.when_some(self.theme.color(border), |message_box, border| message_box.border_1().border_color(border)),
None => message_box,
}
}
/// The 2px infinite progress bar.
fn quick_input_progress(&self, input: &QuickInput) -> AnyElement {
let shown = self.quick_inputs.busy_shown && self.quick_inputs.busy.as_ref().is_some_and(|(id, _)| *id == input.id);
let bar = div().relative().h(px(2.)).overflow_hidden();
if !shown {
return bar.into_any_element();
}
bar.child(infinite_progress_bit("quick-input-progress", self.color("progressBar.background"))).into_any_element()
}
/// `.quick-input-list`: the visible rows, at most the layout's height, with 7px below them.
fn quick_input_list(&mut self, input: &QuickInput, interactive: bool, window: &mut Window, cx: &mut Context<Self>) -> Div {
let heights: Vec<f32> = input.order.iter().map(|row| row_height(&input.rows[*row])).collect();
let height = heights.iter().sum::<f32>().min(self.quick_input_list_max_height(window)).min(20. * ROW_HEIGHT);
let inputs = &mut self.quick_inputs;
let focused_position = input.focused.and_then(|row| input.order.iter().position(|shown| *shown == row));
let same_input = inputs.listed.0 == Some(input.id);
if !same_input || inputs.listed.1 != input.order || inputs.listed.2 != input.list_updates {
// quickInput.ts `update`: the scroll goes back to the top, and the focused row is revealed, unless kept.
let scroll_top = inputs.list.logical_scroll_top();
if !same_input || inputs.listed.1 != input.order {
inputs.list.reset(input.order.len());
}
if same_input && input.keep_scroll_position {
inputs.list.scroll_to(scroll_top);
inputs.revealed = focused_position;
} else {
inputs.list.scroll_to(ListOffset::default());
inputs.revealed = None;
}
inputs.listed = (Some(input.id), input.order.clone(), input.list_updates);
}
if interactive && let Some(position) = focused_position.filter(|position| inputs.revealed != Some(*position)) {
// listView.ts `renderHeight` leaves out the 7px bottom padding: a revealed last row ends above it.
reveal_row(&inputs.list, &heights, position, height);
inputs.revealed = focused_position;
}
let rows = list(self.quick_inputs.list.clone(), cx.processor(move |workbench: &mut Workbench, position: usize, window, cx| workbench.quick_input_row(position, interactive, window, cx)))
.size_full();
// .monaco-list: rows show through the 7px bottom padding, but listView.ts renders only the rows that start
// inside `renderHeight`: when a row starts right at its end, the padding stays empty (ref-dom, Customize Layout).
let scroll_top = scroll_top_px(&self.quick_inputs.list, &heights);
let render_bottom = scroll_top + height;
let mut row_top = 0.;
let mut padding_empty = true;
for row_height in &heights {
if row_top < render_bottom - 0.5 && row_top + row_height > render_bottom + 0.5 {
padding_empty = false;
}
row_top += row_height;
}
let cover = padding_empty.then(|| div().absolute().left_0().right_0().bottom_0().h(px(7.)).bg(self.color("quickInput.background")));
// The list clamps a reveal past its end as it lays out, after this render read the scroll.
let list_state = self.quick_inputs.list.clone();
let follow_scroll = canvas(|_, _, _| (), move |_, _, window, cx| {
if scroll_top_px(&list_state, &heights) != scroll_top {
super::part_view::redraw_after_frame(window, cx);
}
});
// .monaco-scrollable-element: 6px on the sides.
let rows = div().relative().h(px(height + 7.)).px(px(6.)).child(rows).children(cover).child(follow_scroll).child(self.list_scroll_layer(super::list_scroll::ListId::QuickInput, cx));
// quickInput.css `.quick-input-list`: line-height 22px.
div().line_height(px(22.)).when(input.hide_input, |list| list.mt(px(4.)).pb(px(4.))).child(rows)
}
/// A `.quick-input-list-entry`.
fn quick_input_row(&mut self, position: usize, interactive: bool, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
let input = match (self.quick_inputs.current(), self.quick_inputs.closing.as_ref()) {
(Some(input), _) if interactive => input,
(_, Some((input, _))) => input,
_ => return div().into_any_element(),
};
let Some(&row_index) = input.order.get(position) else { return div().into_any_element() };
let row = &input.rows[row_index];
let focused = input.focused == Some(row_index);
let hovered = self.quick_inputs.hovered == Some(row_index);
let can_select_many = input.can_select_many;
let foreground = if focused { self.theme.color("quickInputList.focusForeground") } else { None };
// listWidget.ts: a focused row's `.codicon` takes quickInputList.focusIconForeground; unset by default, so it inherits the row color.
let icon_color = if focused { self.theme.color("quickInputList.focusIconForeground").or(foreground) } else { None }.unwrap_or(self.foreground_or("icon.foreground"));
let highlight = self.color(if focused { "quickInputList.focusHighlightForeground" } else { "list.highlightForeground" });
// terminalIcon.ts `createColorStyleElement`: the color class wins over the focused row's color (`!important`).
let label_icon_color = row.item.icon_color.as_deref().and_then(|key| self.theme.color(key)).unwrap_or(icon_color);
// quickInputList.ts: an item's tooltip is the row's hover; without one the description and the detail each have theirs.
let text_hovers = interactive && row.item.tooltip.is_none();
let label_box = div()
.flex_1()
.min_w_0()
.ml(px(5.))
.flex()
.flex_col()
.justify_center()
.overflow_hidden()
.child(
div()
.h(px(ROW_HEIGHT))
.flex()
.items_center()
.whitespace_nowrap()
.when(row.item.icon.is_some() || row.item.icon_path.is_some(), |line| {
let icon = match (&row.item.icon, &row.item.icon_path) {
(Some(codicon), _) => self.icon(codicon, 16., 16., icon_color),
(None, Some(path)) => {
let path = if self.theme.kind.is_light() { &path.light } else { &path.dark };
div().size(px(16.)).flex_none().child(gpui::img(path.clone()).size(px(16.)))
}
(None, None) => div(),
};
line.child(icon.mr(px(6.)))
})
.children(row.item.file_icon.as_ref().and_then(|path| self.quick_input_file_icon(path, row.item.folder_icon, row.item.root_folder_icon, icon_color)))
.children(row.item.language_icon.as_ref().and_then(|language| {
let icon = self.file_icons.as_ref()?.language_icon(language, self.theme.kind, 13., ROW_HEIGHT, icon_color)?;
Some(icon.mr(px(6.)))
}))
// A long description is cut, not the name (monaco-icon-label-container's overflow).
.child(div().debug_selector(|| "quick-input-label".into()).flex_none().when(row.item.strikethrough, |label| label.line_through()).when(row.item.italic, |label| label.italic()).child(self.highlighted_label(&row.item.label, &row.label_highlights, highlight, 16., label_icon_color)))
.children(row.item.description.as_ref().filter(|description| !description.is_empty()).map(|description| {
// monaco-icon-label: .label-description at 0.9em, 0.7 opacity, 0.5em of its own 11.7px after the name.
super::icon_label::label_description().debug_selector(|| "quick-input-description".into()).min_w_0().overflow_hidden().when(row.item.strikethrough, |label| label.line_through()).when(row.item.italic, |label| label.italic()).opacity(if focused { 1. } else { 0.7 }).child(self.highlighted_label(description, &row.description_highlights, highlight, 14., icon_color))
.when(text_hovers, |label| label.relative().child(self.hover_target(("quick-input-description-hover", row_index), HoverContent::Text(description.clone()), HoverOptions::quick_input())))
})),
)
.children(row.item.detail.as_ref().filter(|detail| !detail.is_empty()).map(|detail| {
div().h(px(ROW_HEIGHT)).flex().items_center().whitespace_nowrap().opacity(if focused { 1. } else { 0.7 }).child(self.highlighted_label(detail, &row.detail_highlights, highlight, 14., icon_color))
.when(text_hovers, |line| line.relative().child(self.hover_target(("quick-input-detail-hover", row_index), HoverContent::Text(detail.clone()), HoverOptions::quick_input())))
}));
let separator = row.separator.clone().filter(|label| !label.is_empty());
// quickInput.css: `.quick-input-list-entry .quick-input-list-separator` outranks the controller's pickerGroup.foreground rule.
let separator_color = if focused { foreground.unwrap_or(self.foreground_or("quickInput.foreground")) } else { self.color("descriptionForeground") };
let buttons_shown = focused || hovered;
let any_button_shown = row.item.buttons.iter().any(|button| buttons_shown || button.always_visible);
let handle = row.item.handle;
let entry = div()
.relative()
.size_full()
.flex()
// Measured on 1.147: keybinding caps and the gear end 4px from the row edge, labels start at 9px.
.pl(px(4.))
.pr(px(2.))
.when(row.separator.is_some() && position > 0, |entry| entry.border_t_1().border_color(self.color("pickerGroup.border")))
.when(can_select_many, |entry| {
entry.child(
self.checkbox(row.checked, false)
.id(("quick-input-row-check", row_index))
.mt(px(2.))
.when(row.item.pickable, |checkbox| checkbox.cursor_pointer())
.when(!row.item.pickable, |checkbox| checkbox.opacity(0.4)),
)
})
.child(label_box)
.when(!row.item.keybinding.is_empty(), |entry| entry.child(self.keybinding_label(&row.item.keybinding, focused, hovered)))
// The separator label ends 4px from the row edge (the entry's 2px and its own), and 4px before the buttons
// (`.quick-input-list-separator` margin-right).
.children(separator.map(|label| div().flex().items_center().ml(px(4.)).mr(px(if any_button_shown { 4. } else { 2. })).text_size(px(11.)).text_color(separator_color).child(label)))
.when(any_button_shown, |entry| {
let buttons = row.item.buttons.iter().enumerate().filter(|(_, button)| buttons_shown || button.always_visible);
// quickInput.css puts 4px between two `.action-label.codicon` (margin-right); the last one lines up as is.
entry.child(div().flex().items_center().gap(px(2.)).mt(px(1.)).children(buttons.map(|(index, button)| {
let toggle = button.toggle;
self.icon(button.codicon.as_deref().unwrap_or("blank"), 20., 16., icon_color)
.id(("quick-input-item-button", index))
.mr(px(2.))
.rounded(px(4.))
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
cx.stop_propagation();
workbench.with_current_quick_input(window, cx, |input| {
input.events.push(Event::TriggerItemButton(handle, index as i64, toggle.map(|checked| !checked)));
});
}))
})))
});
let background = if focused { self.theme.color("quickInputList.focusBackground") } else if hovered { self.theme.color("list.hoverBackground") } else { None };
// listWidget.ts: the focused row of the unfocused list gets a 1px dotted listInactiveFocusOutline (activeContrastBorder).
// Dashed: GPUI has no dotted border.
// quickInput.ts `update`: with the input box hidden the list has the DOM focus, and quickInput.css outlines
// its focused row 1px solid list.focusOutline, inside the row.
let list_focused = input.hide_input && self.quick_inputs.focus.is_focused(window);
let outline = match list_focused {
true => self.theme.color("list.focusOutline").filter(|_| focused).map(|color| div().absolute().inset_0().rounded(px(4.)).border_1().border_color(color)),
false => self.theme.color("contrastActiveBorder").filter(|_| focused).map(|color| div().absolute().inset_0().rounded(px(4.)).border_1().border_dashed().border_color(color)),
};
let header = row.header.clone();
// quickInputList.ts `focusInsideSeparator`: the separator's buttons also show while an item of its section is active or under the pointer.
let focus_inside = [input.focused, self.quick_inputs.hovered].into_iter().flatten().any(|other| input.rows.get(other).is_some_and(|other| other.section == row.section));
let row_element = div()
.id(("quick-input-row", row_index))
.relative()
.h(px(item_height(row)))
// modernUI roundedCorners.css: list rows 4px, over quickInput.css's 3px.
.cursor_pointer()
.rounded(px(4.))
.when_some(background, |row, background| row.bg(background))
.when_some(foreground, |row, color| row.text_color(color))
.child(entry)
.children(outline)
.when_some(row.item.tooltip.clone().filter(|_| interactive), |row, tooltip| row.child(self.hover_target(("quick-input-item-hover", row_index), HoverContent::Text(tooltip), HoverOptions::quick_input_item())))
.when(interactive, |row| {
row.on_hover(cx.listener(move |workbench, hovered: &bool, _, cx| {
let inputs = &mut workbench.quick_inputs;
if *hovered {
inputs.hovered = Some(row_index);
} else if inputs.hovered == Some(row_index) {
inputs.hovered = None;
}
cx.notify();
}))
.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
workbench.with_current_quick_input(window, cx, |input| input.click_row(row_index));
}))
});
match header {
Some(header) => div().flex().flex_col().child(self.quick_input_separator_row(header, position, row_index, focus_inside, cx)).child(row_element).into_any_element(),
None => row_element.into_any_element(),
}
}
/// `QuickPickSeparatorElementRenderer` (`.quick-input-list-separator-as-item`): the label in semibold, its
/// description, and the separator's buttons while it or its section is active or under the pointer.
fn quick_input_separator_row(&self, header: Header, position: usize, row_index: usize, focus_inside: bool, cx: &mut Context<Self>) -> Stateful<Div> {
let color = self.color("descriptionForeground");
let buttons_shown = focus_inside || self.quick_inputs.hovered_header == Some(row_index);
let handle = header.handle;
div()
.id(("quick-input-header", row_index))
.h(px(HEADER_HEIGHT))
.flex()
.items_center()
.pl(px(9.))
.pr(px(2.))
.text_size(px(12.))
.text_color(color)
.when(position > 0, |header| header.border_t_1().border_color(self.color("pickerGroup.border")))
.on_hover(cx.listener(move |workbench, hovered: &bool, _, cx| {
let inputs = &mut workbench.quick_inputs;
if *hovered {
inputs.hovered_header = Some(row_index);
} else if inputs.hovered_header == Some(row_index) {
inputs.hovered_header = None;
}
cx.notify();
}))
.child(div().font_weight(FontWeight::SEMIBOLD).whitespace_nowrap().child(header.label))
.children(header.description.map(|description| div().ml(px(5.4)).min_w_0().overflow_hidden().whitespace_nowrap().text_size(px(10.8)).child(description)))
.child(div().flex_1())
.when(buttons_shown, |row| {
row.children(header.buttons.iter().enumerate().map(|(index, button)| {
self.icon(button.codicon.as_deref().unwrap_or("blank"), 20., 16., self.foreground_or("icon.foreground"))
.id(("quick-input-header-button", index))
.debug_selector(|| "quick-input-header-button".into())
.mr(px(2.))
.rounded(px(4.))
.cursor_pointer()
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
cx.stop_propagation();
workbench.with_current_quick_input(window, cx, |input| input.events.push(Event::TriggerItemButton(handle, index as i64, None)));
}))
}))
})
}
/// iconlabel.css `.monaco-icon-label::before`: 16px wide, 22px tall, 6px before the label.
fn quick_input_file_icon(&self, path: &Path, folder: bool, is_root: bool, foreground: Rgba) -> Option<Div> {
let icons = self.file_icons.as_ref()?;
let icon = match folder || is_root {
true => icons.folder_icon(crate::file_icons::FolderIcon { path: &path, is_root, expanded: false }, self.theme.kind, 13., ROW_HEIGHT, foreground)?,
false => icons.file_icon(path, self.languages.language_of(path, ""), self.theme.kind, 13., ROW_HEIGHT, foreground)?,
};
Some(icon.mr(px(6.)))
}
/// A `HighlightedLabel` with `supportIcons`: `$(name)` draws a codicon, matches are bold in the highlight color.
pub(super) fn highlighted_label(&self, text: &str, highlights: &[Range<usize>], color: Rgba, icon_size: f32, icon_color: Rgba) -> Div {
let chars: Vec<char> = text.chars().collect();
let mut line = div().flex().items_center().min_w_0();
let mut segment = String::new();
let mut segment_highlights = Vec::new();
let mut index = 0;
let flush = |line: Div, segment: &mut String, segment_highlights: &mut Vec<(Range<usize>, HighlightStyle)>| {
if segment.is_empty() {
return line;
}
let styled = StyledText::new(std::mem::take(segment)).with_highlights(std::mem::take(segment_highlights));
line.child(styled)
};
while index < chars.len() {
if let Some((name, length)) = icon_at(&chars[index..]) {
line = flush(line, &mut segment, &mut segment_highlights);
line = line.child(self.icon(&name, icon_size, icon_size, icon_color));
index += length;
continue;
}
let start = segment.len();
segment.push(chars[index]);
if highlights.iter().any(|range| range.contains(&index)) {
segment_highlights.push((start..segment.len(), HighlightStyle { color: Some(color.into()), font_weight: Some(FontWeight::BOLD), ..Default::default() }));
}
index += 1;
}
flush(line, &mut segment, &mut segment_highlights)
}
/// A `.monaco-text-button` label with `supportIcons`. button.css: the button is a flex box, so the whitespace
/// around an icon collapses, and `.codicon` takes `margin: 0 0.2em` of the button's 12px font.
pub(super) fn button_label(&self, text: &str, color: Rgba) -> Div {
let chars: Vec<char> = text.chars().collect();
let mut line = div().flex().items_center().min_w_0();
let mut segment = String::new();
let mut index = 0;
while index < chars.len() {
let Some((name, length)) = icon_at(&chars[index..]) else {
segment.push(chars[index]);
index += 1;
continue;
};
line = line.when(!segment.trim().is_empty(), |line| line.child(segment.trim().to_owned()));
segment.clear();
line = line.child(self.icon(&name, 16., 16., color).mx(px(2.4)));
index += length;
}
line.when(!segment.trim().is_empty(), |line| line.child(segment.trim().to_owned()))
}
/// The `.monaco-keybinding` of a row: a box per key, chords apart.
/// quickInput.css: a focused row's keys take the row's color (`color: inherit`); on a focused or hovered row
/// their border is that color at 30% outside high contrast themes.
fn keybinding_label(&self, chords: &[Vec<String>], focused: bool, hovered: bool) -> Div {
let row_color = self.theme.color("quickInputList.focusForeground").filter(|_| focused).unwrap_or_else(|| self.foreground_or(if focused { "quickInput.foreground" } else { "keybindingLabel.foreground" }));
let mut border = row_color;
border.a *= 0.3;
let mixed_border = (focused || hovered) && !self.theme.kind.is_high_contrast();
let key = |label: &String| {
self.key_cap(label, focused || hovered)
.when(focused, |key| key.text_color(row_color))
.when(mixed_border, |key| key.border_color(border))
};
div().flex().items_center().children(chords.iter().enumerate().map(|(index, chord)| div().flex().when(index > 0, |chord| chord.ml(px(5.))).children(chord.iter().map(key))))
}
/// keybindingLabel.css `.monaco-keybinding-key`.
/// GPUI draws one border color per box, so the bottom border (keybindingLabel.ts `borderBottomColor`) and the
/// `inset 0 -1px 0` widget shadow above it are 1px strips over the box's open bottom edge.
pub(super) fn key_cap(&self, label: &str, row_active: bool) -> Div {
div()
.relative()
.mx(px(2.))
.px(px(5.))
.pb(px(1.))
.h(px(18.))
.min_w(px(24.))
.flex()
.items_center()
.justify_center()
.rounded(px(3.))
.text_size(px(11.))
.border_t_1()
.border_x_1()
.border_color(self.color("keybindingLabel.border"))
.when(!row_active, |key| key.bg(self.color("keybindingLabel.background")))
.text_color(self.foreground_or("keybindingLabel.foreground"))
.child(label.to_string())
.child(div().absolute().left_0().right_0().bottom(px(1.)).h(px(1.)).bg(self.color("widget.shadow")))
.child(div().absolute().left(px(-1.)).right(px(-1.)).bottom_0().h(px(4.)).rounded_b(px(3.)).border_b_1().border_color(self.color("keybindingLabel.bottomBorder")))
}
/// The 18px `.monaco-checkbox` of the list and the header: tri-state when `mixed`.
pub(super) fn checkbox(&self, checked: bool, mixed: bool) -> Div {
let icon = if mixed { Some("dash") } else if checked { Some("check") } else { None };
div()
.size(px(18.))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(px(3.))
.border_1()
.border_color(self.color("checkbox.border"))
.bg(self.color("checkbox.background"))
.children(icon.map(|icon| self.icon(icon, 16., 16., self.color("checkbox.foreground"))))
}
}
/// progressbar.css `infinite`: a 2% bit crossing in 4s, scaling to 3x halfway.
pub(super) fn infinite_progress_bit(id: &'static str, color: Rgba) -> impl IntoElement {
div().absolute().top_0().h_full().w(gpui::relative(0.02)).bg(color).with_animation(id, Animation::new(Duration::from_secs(4)).repeat(), |bit, delta| {
let (offset, scale) = if delta < 0.5 { (delta * 2. * 25., 1. + delta * 4.) } else { (25. + (delta - 0.5) * 2. * 24., 3. - (delta - 0.5) * 4.) };
bit.left(gpui::relative(offset * 0.02)).w(gpui::relative(0.02 * scale))
})
}
/// The list's scroll position in pixels, from its first shown row and the offset into it.
fn scroll_top_px(list: &ListState, heights: &[f32]) -> f32 {
let current = list.logical_scroll_top();
heights[..current.item_ix.min(heights.len())].iter().sum::<f32>() + f32::from(current.offset_in_item)
}
/// `list.reveal`: scrolls a row above the viewport to its top, one below it to its bottom. The rows' heights are
/// known here, where GPUI's `scroll_to_reveal_item` would read them from a layout that has not run for new rows.
fn reveal_row(list: &ListState, heights: &[f32], position: usize, viewport: f32) {
let current_top = scroll_top_px(list, heights);
let row_top: f32 = heights[..position].iter().sum();
let row_bottom = row_top + heights[position];
let top = if row_top < current_top {
row_top
} else if row_bottom > current_top + viewport {
row_bottom - viewport
} else {
return;
};
let mut item_top = 0.;
for (item_ix, item_height) in heights.iter().enumerate() {
if item_top + item_height > top {
list.scroll_to(ListOffset { item_ix, offset_in_item: px(top - item_top) });
return;
}
item_top += item_height;
}
}
/// quickInputController.ts `updateLayout`: 62% of the window, at most `MAX_WIDTH`.
pub(super) fn widget_width(window_width: f32) -> f32 {
(window_width * 0.62).min(MAX_WIDTH)
}
fn row_height(row: &Row) -> f32 {
item_height(row) + if row.header.is_some() { HEADER_HEIGHT } else { 0. }
}
fn item_height(row: &Row) -> f32 {
if row.item.detail.as_ref().is_some_and(|detail| !detail.is_empty()) { DETAIL_ROW_HEIGHT } else { ROW_HEIGHT }
}
/// `$(name)` or `$(name~spin)` at the start of `chars`: the codicon name and the chars it spans.
pub(super) fn icon_at(chars: &[char]) -> Option<(String, usize)> {
if chars.len() < 4 || chars[0] != '$' || chars[1] != '(' {
return None;
}
let close = chars.iter().position(|c| *c == ')')?;
let inner: String = chars[2..close].iter().collect();
let name = inner.split('~').next().unwrap_or_default();
let valid = !name.is_empty() && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
valid.then(|| (name.to_owned(), close + 1))
}
/// Chromium's `prefers-reduced-transparency: reduce`: the macOS Reduce Transparency setting, read on each call.
fn system_reduces_transparency() -> bool {
#[cfg(target_os = "macos")]
return objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceTransparency();
// shortcut: the Linux desktop's reduced transparency is not read; read it when a Linux user needs it.
#[cfg(target_os = "linux")]
return false;
// shortcut: Windows' transparency effects setting is not read; port/ledger.md M24 row app/src/workbench/accessibility.rs:531.
#[cfg(target_os = "windows")]
return false;
}
#[cfg(test)]
mod tests;