Visual Studio Code, rebuilt in Rust
Rust
//! A `custom` dialog of dialogHandler.ts: base/browser/ui/dialog/dialog.ts in a dimmed modal block, with a codicon,
//! the message, markdown details, optional inputs, an optional checkbox and buttons with optional descriptions.
use futures::channel::oneshot;
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, AnyWindowHandle, BoxShadow, ClickEvent, Context, FocusHandle, FontStyle, FontWeight, HighlightStyle, InteractiveElement, InteractiveText, IntoElement, Keystroke, MouseButton, ParentElement, StatefulInteractiveElement, Styled,
StyledText, TextRun, Window, div, point, px, rgba,
};
use super::Workbench;
use super::hover::{HoverContent, HoverOptions};
use super::input_box_view::{InputId, InputLook, InputView};
use crate::input_box::InputBox;
use crate::notifications::{Node, parse_linked_text};
/// notificationsDialogs.css (modern UI, on in 1.147.0): `min-width: 440px` on the content box, plus 4px padding and
/// the 1px border each side.
const MIN_WIDTH: f32 = 450.;
/// `.dialog-buttons`' margin-left: long button rows align with the message text.
const BUTTONS_MARGIN_LEFT: f32 = 67.;
pub struct DialogButton {
pub label: String,
/// `custom.buttonDetails`: a description under the button.
pub detail: Option<String>,
}
/// dialog.ts `IDialogInputOptions`.
pub struct DialogInput {
pub placeholder: String,
pub password: bool,
pub value: String,
}
pub struct CustomDialog {
pub icon: &'static str,
pub message: String,
/// The plain `detail` under the message, its line breaks kept.
pub detail: Option<String>,
/// `custom.markdownDetails`: trusted markdown paragraphs, with `[label](href)` links and `` `code` `` spans.
pub details: Vec<String>,
pub inputs: Vec<DialogInput>,
pub checkbox: Option<String>,
/// The checkbox's state when the dialog opens (`ICheckbox.checked`).
pub checkbox_checked: bool,
/// The first button is the primary one.
pub buttons: Vec<DialogButton>,
/// The button Escape picks; none with `disableCloseAction`.
pub cancel: Option<usize>,
}
pub struct DialogResult {
pub button: usize,
pub checkbox_checked: bool,
/// The inputs' values, in their order.
pub values: Vec<String>,
}
pub(super) struct ShownDialog {
pub(super) dialog: CustomDialog,
checked: bool,
/// The focused element of the inputs followed by the buttons.
focused: usize,
reply: oneshot::Sender<DialogResult>,
pub(super) inputs: Vec<ShownInput>,
/// The window whose focus the inputs take, and the element that has it back when the dialog closes.
window: Option<(AnyWindowHandle, Option<FocusHandle>)>,
}
pub(super) struct ShownInput {
pub(super) input: InputBox,
pub(super) view: InputView,
pub(super) focus: FocusHandle,
}
/// workbench/browser/parts/dialogs/dialog.ts `defaultDialogAllowableCommands`: the commands a key may run while a
/// dialog input has the focus.
const ALLOWABLE_COMMANDS: [&str; 8] = [
"workbench.action.quit",
"workbench.action.reloadWindow",
"copy",
"cut",
"editor.action.selectAll",
"editor.action.clipboardCopyAction",
"editor.action.clipboardCutAction",
"editor.action.clipboardPasteAction",
];
impl Workbench {
/// `IDialogService.prompt` with `custom`: the chosen button, once picked. Dialogs queue as the reference's do.
pub(crate) fn show_custom_dialog(&mut self, dialog: CustomDialog, cx: &mut Context<Self>) -> oneshot::Receiver<DialogResult> {
let (reply, receiver) = oneshot::channel();
let inputs = dialog.inputs.iter().map(|input| ShownInput { input: InputBox::new(input.value.clone()), view: InputView::default(), focus: cx.focus_handle() }).collect();
self.dialogs.push(ShownDialog { checked: dialog.checkbox_checked, dialog, focused: 0, reply, inputs, window: None });
cx.notify();
receiver
}
/// `IDialogService.input`: a dialog whose inputs take the focus of `window` once it shows.
pub(crate) fn show_input_dialog(&mut self, dialog: CustomDialog, window: &mut Window, cx: &mut Context<Self>) -> oneshot::Receiver<DialogResult> {
let answer = self.show_custom_dialog(dialog, cx);
self.dialogs.last_mut().expect("just pushed").window = Some((window.window_handle(), None));
if self.dialogs.len() == 1 {
self.focus_first_dialog_input(window, cx);
}
answer
}
/// dialog.ts `show`: the first input takes the focus with its value selected.
fn focus_first_dialog_input(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(shown) = self.dialogs.first_mut() else { return };
let Some(first) = shown.inputs.first_mut() else { return };
first.input.select_all();
let focus = first.focus.clone();
if let Some((_, focus_to_return)) = shown.window.as_mut() {
*focus_to_return = window.focused(cx);
}
window.focus(&focus, cx);
self.blink_caret(InputId::Dialog(0), window, cx);
}
pub(super) fn dialog_input(&self, index: usize) -> Option<&ShownInput> {
self.dialogs.first()?.inputs.get(index)
}
pub(super) fn close_custom_dialog(&mut self, button: usize, cx: &mut Context<Self>) {
if self.dialogs.is_empty() {
return;
}
let shown = self.dialogs.remove(0);
let values = shown.inputs.iter().map(|input| input.input.value.clone()).collect();
let _ = shown.reply.send(DialogResult { button, checkbox_checked: shown.checked, values });
// dialog.ts `dispose`: the focus returns to the element that had it before the dialog.
if let Some((window, focus_to_return)) = shown.window {
cx.defer(move |cx| {
let _ = window.update(cx, |_, window, cx| match focus_to_return {
Some(focus) => window.focus(&focus, cx),
None => window.blur(cx),
});
});
}
if let Some(window) = self.dialogs.first().and_then(|next| next.window.as_ref().map(|(window, _)| *window)) {
let workbench = cx.entity().downgrade();
cx.defer(move |cx| {
let _ = window.update(cx, |_, window, cx| workbench.update(cx, |workbench, cx| workbench.focus_first_dialog_input(window, cx)));
});
}
cx.notify();
}
/// dialog.ts's keydown handler on the modal block: it takes every key while the dialog shows, except the keys
/// of a focused input that no keybinding outside `ALLOWABLE_COMMANDS` takes.
pub(super) fn custom_dialog_key(&mut self, keystroke: &Keystroke, window: &mut Window, cx: &mut Context<Self>) -> bool {
let Some(shown) = self.dialogs.first() else { return false };
let inputs = shown.inputs.len();
let count = inputs + shown.dialog.buttons.len();
let focused = self.focused_dialog_element(window);
let in_input = focused < inputs;
let cancel = shown.dialog.cancel;
match (keystroke.key.as_str(), keystroke.modifiers.shift) {
// Enter in an input OKs the dialog: the first button in the row that is not the cancel one.
("enter", _) if in_input => {
let ok = button_order(shown.dialog.buttons.len(), cancel).into_iter().find(|button| Some(*button) != cancel).unwrap_or(0);
self.close_custom_dialog(ok, cx);
}
("enter" | "space", _) if !in_input => self.close_custom_dialog(focused - inputs, cx),
("escape", _) => {
if let Some(cancel) = cancel {
self.close_custom_dialog(cancel, cx);
}
}
("tab", false) => self.focus_dialog_element((focused + 1) % count, window, cx),
("tab", true) => self.focus_dialog_element((focused + count - 1) % count, window, cx),
("right" | "left", _) if in_input => return false,
("right", _) => self.focus_dialog_element((focused + 1) % count, window, cx),
("left", _) => self.focus_dialog_element((focused + count - 1) % count, window, cx),
_ if in_input => return self.dialog_blocks_key(keystroke, window),
_ => {}
}
cx.notify();
true
}
/// The index of the focused input, else of the focused button after the inputs.
fn focused_dialog_element(&self, window: &Window) -> usize {
let shown = &self.dialogs[0];
shown.inputs.iter().position(|input| input.focus.is_focused(window)).unwrap_or(shown.focused)
}
fn focus_dialog_element(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
let Some(shown) = self.dialogs.first_mut() else { return };
shown.focused = index;
match shown.inputs.get(index) {
Some(input) => {
let focus = input.focus.clone();
window.focus(&focus, cx);
self.blink_caret(InputId::Dialog(index), window, cx);
}
None if !shown.inputs.is_empty() => window.blur(cx),
None => {}
}
}
/// workbench/browser/parts/dialogs/dialog.ts `keyEventProcessor`: a key bound to a command outside
/// `ALLOWABLE_COMMANDS` does nothing.
fn dialog_blocks_key(&self, keystroke: &Keystroke, window: &Window) -> bool {
let chord = crate::keyboard_mapper::event_chord(keystroke);
match self.keybindings.resolver.resolve(&self.key_context(window), &[], chord) {
crate::keybindings::Resolution::KbFound { command, .. } => !command.is_empty() && !ALLOWABLE_COMMANDS.contains(&command.as_str()),
_ => false,
}
}
pub(super) fn custom_dialog_widget(&self, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
let shown = self.dialogs.first()?;
let dialog = &shown.dialog;
let foreground = self.color("editorWidget.foreground");
let mut buttons = div().flex().justify_end().ml(px(BUTTONS_MARGIN_LEFT));
let mut buttons_width = BUTTONS_MARGIN_LEFT;
let focused = self.focused_dialog_element(window);
for index in button_order(dialog.buttons.len(), dialog.cancel) {
let button = &dialog.buttons[index];
let label_width = text_width(&button.label, 12., FontStyle::Normal, window) + 18.;
let detail_width = button.detail.as_ref().map_or(0., |detail| text_width(detail, 11., FontStyle::Italic, window) + 40.);
buttons_width += label_width.max(detail_width) + 8.;
buttons = buttons.child(self.dialog_button(index, button, shown.inputs.len() + index == focused, cx));
}
let width = (buttons_width + 10.).max(MIN_WIDTH).min(f32::from(window.viewport_size().width) * 0.9);
// The details are markdown paragraphs, whose 13px margins also sit below the last one.
let mut body = div().flex().flex_col().when(!dialog.details.is_empty(), |body| body.mb(px(13.)));
if let Some(detail) = &dialog.detail {
body = body.child(div().line_height(px(20.)).text_color(self.color("descriptionForeground")).child(detail.clone()));
}
for (index, detail) in dialog.details.iter().filter(|detail| !detail.is_empty()).enumerate() {
body = body.child(div().mt(px(13.)).child(self.dialog_markdown(index, detail, cx)));
}
// dialog.css `.dialog-message-input`: 15px above each input, which fills the row.
let inputs = dialog.inputs.iter().enumerate().map(|(index, input)| {
let focused = shown.inputs[index].focus.is_focused(window);
let border = if focused { self.color("focusBorder") } else { self.theme.color("input.border").unwrap_or_default() };
let look = InputLook { password: input.password, placeholder: Some(input.placeholder.clone()), focused };
div().pt(px(15.)).flex().child(div().flex_1().h(px(26.)).flex().items_center().px(px(6.)).border_1().border_color(border).bg(self.color("input.background")).child(self.input_text(InputId::Dialog(index), look, cx)))
});
let inputs: Vec<_> = inputs.collect();
let checkbox = dialog.checkbox.as_ref().map(|label| {
div()
.id("dialog-checkbox")
.pt(px(15.))
.flex()
.cursor_pointer()
.child(self.checkbox(shown.checked, false).mr(px(9.)))
.child(div().flex_1().child(label.clone()))
.on_click(cx.listener(|workbench, _: &ClickEvent, _, cx| {
if let Some(shown) = workbench.dialogs.first_mut() {
shown.checked = !shown.checked;
cx.notify();
}
}))
});
let message_row = div()
.flex()
.pt(px(16.))
.px(px(8.))
.child(self.icon(dialog.icon, 24., 24., self.color(icon_color(dialog.icon))))
.child(
div()
.flex_1()
.min_w(px(0.))
.flex()
.flex_col()
.pl(px(8.))
.pr(px(20.))
.child(div().mt(px(2.)).mb(px(12.)).min_h(px(22.)).flex().items_center().font_weight(FontWeight::SEMIBOLD).child(dialog.message.clone()))
.child(body)
.children(inputs)
.children(checkbox),
);
// dialog.ts: the close action resolves with the cancel button; notificationsDialogs.css puts it 8px from the corner.
let close = dialog.cancel.map(|cancel| {
self.icon("close", 22., 16., foreground)
.id("dialog.close")
.role(gpui::Role::Button)
.aria_label("Close Dialog")
.absolute()
.top(px(8.))
.right(px(8.))
.rounded(px(4.))
.cursor_pointer()
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
.child(self.hover_target("dialog.close", HoverContent::Text("Close Dialog".into()), HoverOptions::mouse()))
.on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| workbench.close_custom_dialog(cancel, cx)))
});
let dialog_box = div()
.id("custom-dialog")
.relative()
.w(px(width))
.p(px(4.))
.flex()
.flex_col()
.rounded(px(8.))
.border_1()
.border_color(self.color("widget.border"))
.child(self.frosted_glass("editorWidget.background", 8.))
.text_color(foreground)
.text_size(px(13.))
.line_height(px(18.2))
.shadow(vec![BoxShadow { color: rgba(0x00000026).into(), offset: point(px(0.), px(0.)), blur_radius: px(20.), spread_radius: px(0.), inset: false }])
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.child(message_row)
.child(div().pt(px(16.)).flex().child(buttons.w_full()))
.children(close);
Some(
div()
.id("dialog-modal-block")
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.bg(rgba(0x00000080))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.child(dialog_box)
.into_any_element(),
)
}
fn dialog_button(&self, index: usize, button: &DialogButton, focused: bool, cx: &mut Context<Self>) -> AnyElement {
let primary = index == 0;
let (background, foreground, hover) = match primary {
true => ("button.background", "button.foreground", "button.hoverBackground"),
false => ("button.secondaryBackground", "button.secondaryForeground", "button.secondaryHoverBackground"),
};
let hover_color = self.color(hover);
let text_button = div()
.h(px(26.))
.px(px(8.))
.flex()
.items_center()
.justify_center()
.rounded(px(4.))
.text_size(px(12.))
.line_height(px(16.))
.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(move |button| button.bg(hover_color))
.whitespace_nowrap()
.child(button.label.clone());
// button.css: the focus outline is 1px, offset 1px, around the text button only. It sits in 2px of the
// button's 4px margin, so the ring and its gap are a 1px border and padding inside a 2px margin.
let text_button = div().p(px(1.)).rounded(px(5.)).border_1().border_color(gpui::transparent_black()).when(focused, |ring| ring.border_color(self.color("focusBorder"))).child(text_button);
div()
.id(("dialog-button", index))
.role(gpui::Role::Button)
.aria_label(button.label.clone())
.m(px(2.))
.flex()
.flex_col()
.cursor_pointer()
.child(text_button)
.children(button.detail.clone().map(|detail| div().px(px(20.)).py(px(4.)).text_size(px(11.)).italic().flex().justify_center().whitespace_nowrap().child(detail)))
.on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| workbench.close_custom_dialog(index, cx)))
.into_any_element()
}
/// A rendered markdown paragraph: its links open through the opener, `` `code` `` shows in the editor font,
/// `**bold**`, backslash escapes and ` ` render, and a leading `$(icon)` (supportThemeIcons) is drawn.
fn dialog_markdown(&self, index: usize, markdown: &str, cx: &mut Context<Self>) -> AnyElement {
let link_color = self.color("textLink.foreground");
if let Some(code) = markdown.strip_prefix('`').and_then(|rest| rest.strip_suffix('`')) {
return div().font_family("Menlo").child(code.to_owned()).into_any_element();
}
let (icon, markdown) = match markdown.strip_prefix("$(").and_then(|rest| rest.split_once(')')) {
Some((icon, rest)) => (Some(icon.to_owned()), rest),
None => (None, markdown),
};
let mut text = String::new();
// Per run of output text: whether it is bold and the link it belongs to.
let mut runs: Vec<(std::ops::Range<usize>, bool, Option<usize>)> = Vec::new();
let mut hrefs = Vec::new();
for node in parse_linked_text(markdown) {
let (raw, link) = match node {
Node::Text(value) => (value, None),
Node::Link { label, href, .. } => {
hrefs.push(href);
(label, Some(hrefs.len() - 1))
}
};
append_inline_markdown(&raw, link, &mut text, &mut runs);
}
let link_style = HighlightStyle { color: Some(link_color.into()), underline: Some(gpui::UnderlineStyle { thickness: px(1.), color: Some(link_color.into()), wavy: false }), ..Default::default() };
let mut highlights = Vec::new();
let mut links: Vec<std::ops::Range<usize>> = Vec::new();
for (range, bold, link) in runs {
let weight = bold.then_some(FontWeight::BOLD);
match link {
Some(link) => {
highlights.push((range.clone(), HighlightStyle { font_weight: weight, ..link_style }));
match links.get_mut(link) {
Some(existing) => existing.end = range.end,
None => links.push(range),
}
}
None if bold => highlights.push((range, HighlightStyle { font_weight: weight, ..Default::default() })),
None => {}
}
}
let weak = cx.entity().downgrade();
let text = InteractiveText::new(("dialog-markdown", index), StyledText::new(text).with_highlights(highlights)).on_click(links, move |index, window, cx| {
let href = hrefs[index].clone();
let _ = weak.update(cx, |workbench, cx| workbench.open_notification_link(&href, window, cx));
});
match icon {
// GPUI's StyledText holds no inline elements, so the icon sits beside the text; wraps under it differ.
Some(icon) => div().flex().items_center().child(self.icon(&icon, 16., 14., self.color("editorWidget.foreground"))).child(text).into_any_element(),
None => text.into_any_element(),
}
}
}
/// The inline markdown of a text run: `\x` escapes, ` ` and `**` bold; an inline `$(icon)` inside a link label
/// is dropped.
fn append_inline_markdown(raw: &str, link: Option<usize>, text: &mut String, runs: &mut Vec<(std::ops::Range<usize>, bool, Option<usize>)>) {
let mut bold = false;
let mut start = text.len();
let mut rest = raw;
while let Some(char) = rest.chars().next() {
if let Some(after) = rest.strip_prefix("**") {
if text.len() > start {
runs.push((start..text.len(), bold, link));
}
bold = !bold;
start = text.len();
rest = after;
} else if let Some(after) = rest.strip_prefix(" ") {
text.push('\u{a0}');
rest = after;
} else if let Some((_, after)) = rest.strip_prefix("$(").and_then(|icon| icon.split_once(')')) {
rest = after.strip_prefix(' ').unwrap_or(after);
} else if let Some(escaped) = rest.strip_prefix('\\').and_then(|after| after.chars().next()) {
text.push(escaped);
rest = &rest[1 + escaped.len_utf8()..];
} else {
text.push(char);
rest = &rest[char.len_utf8()..];
}
}
if text.len() > start {
runs.push((start..text.len(), bold, link));
}
}
/// dialog.ts `rearrangeButtons` on macOS: the cancel button moves second, then the row reverses, so the primary
/// button is last and cancel next to it.
fn button_order(count: usize, cancel: Option<usize>) -> Vec<usize> {
let mut order: Vec<usize> = (0..count).collect();
if count < 2 {
return order;
}
if let Some(cancel) = cancel.filter(|cancel| *cancel < count) {
order.remove(cancel);
order.insert(1, cancel);
}
order.reverse();
order
}
#[cfg(test)]
mod tests {
#[test]
fn cancel_sits_next_to_the_primary_button_on_the_right() {
assert_eq!(super::button_order(3, Some(2)), [1, 2, 0]);
assert_eq!(super::button_order(2, Some(1)), [1, 0]);
assert_eq!(super::button_order(3, None), [2, 1, 0]);
assert_eq!(super::button_order(1, Some(0)), [0]);
}
}
/// dialog.css: the error and warning codicons in the problems colors, every other icon in the info color.
fn icon_color(icon: &str) -> &'static str {
match icon {
"error" => "problemsErrorIcon.foreground",
"warning" => "problemsWarningIcon.foreground",
_ => "problemsInfoIcon.foreground",
}
}
fn text_width(text: &str, size: f32, style: FontStyle, window: &Window) -> f32 {
let mut font = window.text_style().font();
font.style = style;
let run = TextRun { len: text.len(), font, color: gpui::black(), background_color: None, underline: None, strikethrough: None };
f32::from(window.text_system().shape_line(text.to_string().into(), px(size), &[run], None).width)
}