use gpui::{
App, Context, Div, ElementId, FocusHandle, InteractiveElement, KeyBinding, KeyDownEvent, Menu,
MenuItem as OsMenuItem, MouseDownEvent, OsAction, Stateful, Styled, Window, actions, div, px,
};
use crate::lighting;
use crate::palette::Palette;
use crate::state::ControlHost;
use crate::text_input as text;
actions!(vampir, [FocusNext, FocusPrevious, Dismiss]);
pub fn ring(id: impl Into<ElementId>, radius: f32, palette: Palette) -> Stateful<Div> {
dress(div().id(id.into()).tab_index(0), radius, palette)
}
pub fn ring_for(focus: &FocusHandle, radius: f32, palette: Palette) -> Div {
dress(div().track_focus(focus), radius, palette)
}
fn dress<E: InteractiveElement + Styled>(el: E, radius: f32, palette: Palette) -> E {
let (accent, dark) = (palette.accent, palette.is_dark);
el.absolute()
.inset_0()
.rounded(px(radius))
.border_2()
.border_color(gpui::transparent_black())
.focus_visible(move |style| {
style.border_color(accent).shadow(vec![lighting::glow(
accent,
if dark { 0.8 } else { 0.5 },
4.0,
)])
})
}
pub fn standard_bindings() -> Vec<KeyBinding> {
const TEXT: Option<&str> = Some("TextInput");
let mut bindings = vec![
KeyBinding::new("tab", FocusNext, None),
KeyBinding::new("shift-tab", FocusPrevious, None),
KeyBinding::new("escape", Dismiss, None),
KeyBinding::new("backspace", text::Backspace, TEXT),
KeyBinding::new("delete", text::Delete, TEXT),
KeyBinding::new("left", text::Left, TEXT),
KeyBinding::new("right", text::Right, TEXT),
KeyBinding::new("up", text::Up, TEXT),
KeyBinding::new("down", text::Down, TEXT),
KeyBinding::new("shift-left", text::SelectLeft, TEXT),
KeyBinding::new("shift-right", text::SelectRight, TEXT),
KeyBinding::new("shift-up", text::SelectUp, TEXT),
KeyBinding::new("shift-down", text::SelectDown, TEXT),
KeyBinding::new("home", text::Home, TEXT),
KeyBinding::new("end", text::End, TEXT),
KeyBinding::new("shift-home", text::SelectToHome, TEXT),
KeyBinding::new("shift-end", text::SelectToEnd, TEXT),
KeyBinding::new("enter", text::Enter, TEXT),
KeyBinding::new("secondary-a", text::SelectAll, TEXT),
KeyBinding::new("secondary-c", text::Copy, TEXT),
KeyBinding::new("secondary-v", text::Paste, TEXT),
KeyBinding::new("secondary-x", text::Cut, TEXT),
KeyBinding::new("secondary-z", text::Undo, TEXT),
KeyBinding::new("secondary-shift-z", text::Redo, TEXT),
];
if cfg!(target_os = "macos") {
bindings.extend([
KeyBinding::new("alt-backspace", text::DeleteWordLeft, TEXT),
KeyBinding::new("cmd-backspace", text::DeleteToLineStart, TEXT),
KeyBinding::new("alt-left", text::WordLeft, TEXT),
KeyBinding::new("alt-right", text::WordRight, TEXT),
KeyBinding::new("alt-shift-left", text::SelectWordLeft, TEXT),
KeyBinding::new("alt-shift-right", text::SelectWordRight, TEXT),
KeyBinding::new("cmd-left", text::Home, TEXT),
KeyBinding::new("cmd-right", text::End, TEXT),
KeyBinding::new("cmd-shift-left", text::SelectToHome, TEXT),
KeyBinding::new("cmd-shift-right", text::SelectToEnd, TEXT),
KeyBinding::new("cmd-up", text::DocumentStart, TEXT),
KeyBinding::new("cmd-down", text::DocumentEnd, TEXT),
]);
} else {
bindings.extend([
KeyBinding::new("ctrl-backspace", text::DeleteWordLeft, TEXT),
KeyBinding::new("ctrl-left", text::WordLeft, TEXT),
KeyBinding::new("ctrl-right", text::WordRight, TEXT),
KeyBinding::new("ctrl-shift-left", text::SelectWordLeft, TEXT),
KeyBinding::new("ctrl-shift-right", text::SelectWordRight, TEXT),
KeyBinding::new("ctrl-home", text::DocumentStart, TEXT),
KeyBinding::new("ctrl-end", text::DocumentEnd, TEXT),
]);
}
bindings
}
pub fn bind_keys(cx: &mut App) {
cx.bind_keys(standard_bindings());
}
pub fn handle_keys<E: InteractiveElement, V: ControlHost>(
root: E,
view: &V,
cx: &mut Context<V>,
) -> E {
root.track_focus(&view.control_state().root_focus(cx))
.on_action(cx.listener(|this, _: &FocusNext, window, cx| {
move_focus(this, window, cx, false);
cx.notify();
}))
.on_action(cx.listener(|this, _: &FocusPrevious, window, cx| {
move_focus(this, window, cx, true);
cx.notify();
}))
.on_action(cx.listener(|this, _: &Dismiss, window, cx| {
if !this.control_state_mut().dismiss_overlays(window, cx) {
cx.propagate();
return;
}
cx.notify();
}))
.on_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, _window, _cx| {
this.control_state_mut().ring_hidden = true;
}))
}
pub fn root<E: InteractiveElement, V: ControlHost>(root: E, view: &V, cx: &mut Context<V>) -> E {
handle_keys(crate::state::handle_mouse(root, cx), view, cx)
}
pub fn edit_menu() -> Menu {
Menu::new("Edit").items([
OsMenuItem::os_action("Undo", text::Undo, OsAction::Undo),
OsMenuItem::os_action("Redo", text::Redo, OsAction::Redo),
OsMenuItem::separator(),
OsMenuItem::os_action("Cut", text::Cut, OsAction::Cut),
OsMenuItem::os_action("Copy", text::Copy, OsAction::Copy),
OsMenuItem::os_action("Paste", text::Paste, OsAction::Paste),
OsMenuItem::os_action("Select All", text::SelectAll, OsAction::SelectAll),
])
}
pub fn move_focus<V: ControlHost>(view: &mut V, window: &mut Window, cx: &mut App, backward: bool) {
let state = view.control_state_mut();
state.dismiss_popups();
let reveal = std::mem::take(&mut state.ring_hidden) && window.focused(cx).is_some();
if reveal {
return;
}
if let Some(next) = view.control_state().trap_next(window, backward) {
window.focus(&next, cx);
return;
}
if backward {
window.focus_prev(cx);
} else {
window.focus_next(cx);
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Key {
Activate,
Left,
Right,
Up,
Down,
Home,
End,
PageUp,
PageDown,
Dismiss,
}
pub fn key(event: &KeyDownEvent) -> Option<Key> {
let modifiers = &event.keystroke.modifiers;
if modifiers.platform || modifiers.control || modifiers.alt || modifiers.function {
return None;
}
Some(match event.keystroke.key.as_str() {
"space" | "enter" => Key::Activate,
"left" => Key::Left,
"right" => Key::Right,
"up" => Key::Up,
"down" => Key::Down,
"home" => Key::Home,
"end" => Key::End,
"pageup" => Key::PageUp,
"pagedown" => Key::PageDown,
"escape" => Key::Dismiss,
_ => return None,
})
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Orientation {
Horizontal,
Vertical,
Either,
}
pub fn step(key: Key, orientation: Orientation, current: usize, len: usize) -> Option<usize> {
if len == 0 {
return None;
}
let last = len - 1;
let current = current.min(last);
let backward = match orientation {
Orientation::Horizontal => key == Key::Left,
Orientation::Vertical => key == Key::Up,
Orientation::Either => matches!(key, Key::Left | Key::Up),
};
let forward = match orientation {
Orientation::Horizontal => key == Key::Right,
Orientation::Vertical => key == Key::Down,
Orientation::Either => matches!(key, Key::Right | Key::Down),
};
if backward {
Some(if current == 0 { last } else { current - 1 })
} else if forward {
Some(if current == last { 0 } else { current + 1 })
} else {
match key {
Key::Home => Some(0),
Key::End => Some(last),
_ => None,
}
}
}
pub fn nudge(key: Key, orientation: Orientation, value: f32, step_by: f32) -> Option<f32> {
let page = step_by * 10.0;
let delta = match (key, orientation) {
(Key::Left, Orientation::Horizontal | Orientation::Either) => -step_by,
(Key::Right, Orientation::Horizontal | Orientation::Either) => step_by,
(Key::Down, Orientation::Vertical | Orientation::Either) => -step_by,
(Key::Up, Orientation::Vertical | Orientation::Either) => step_by,
(Key::PageDown, _) => -page,
(Key::PageUp, _) => page,
(Key::Home, _) => return Some(0.0),
(Key::End, _) => return Some(1.0),
_ => return None,
};
let moved = (value + delta).clamp(0.0, 1.0);
(moved != value).then_some(moved)
}
pub fn nudge_stepped(key: Key, orientation: Orientation, value: f32, stops: u32) -> Option<f32> {
if stops == 0 {
return nudge(key, orientation, value, 0.05);
}
let current = (value * stops as f32).round() as i64;
let moved = match (key, orientation) {
(Key::Left, Orientation::Horizontal | Orientation::Either) => current - 1,
(Key::Right, Orientation::Horizontal | Orientation::Either) => current + 1,
(Key::Down, Orientation::Vertical | Orientation::Either) => current - 1,
(Key::Up, Orientation::Vertical | Orientation::Either) => current + 1,
(Key::PageDown, _) => current - (stops as i64 / 4).max(1),
(Key::PageUp, _) => current + (stops as i64 / 4).max(1),
(Key::Home, _) => 0,
(Key::End, _) => stops as i64,
_ => return None,
};
let moved = moved.clamp(0, stops as i64) as f32 / stops as f32;
(moved != value).then_some(moved)
}
#[cfg(test)]
mod tests {
use super::{Key, KeyBinding, Orientation, nudge, nudge_stepped, standard_bindings, step};
#[test]
fn a_group_wraps_at_both_ends() {
assert_eq!(step(Key::Down, Orientation::Vertical, 2, 3), Some(0));
assert_eq!(step(Key::Up, Orientation::Vertical, 0, 3), Some(2));
}
#[test]
fn home_and_end_reach_the_ends_from_anywhere() {
assert_eq!(step(Key::Home, Orientation::Vertical, 2, 4), Some(0));
assert_eq!(step(Key::End, Orientation::Horizontal, 0, 4), Some(3));
}
#[test]
fn a_group_only_answers_to_its_own_axis() {
assert_eq!(step(Key::Up, Orientation::Horizontal, 1, 3), None);
assert_eq!(step(Key::Left, Orientation::Vertical, 1, 3), None);
assert_eq!(step(Key::Left, Orientation::Either, 1, 3), Some(0));
assert_eq!(step(Key::Up, Orientation::Either, 1, 3), Some(0));
}
#[test]
fn an_empty_group_does_not_move() {
assert_eq!(step(Key::Down, Orientation::Vertical, 0, 0), None);
}
#[test]
fn an_index_past_the_end_is_pulled_back() {
assert_eq!(step(Key::Up, Orientation::Vertical, 9, 3), Some(1));
}
#[test]
fn a_range_stops_at_its_ends_rather_than_wrapping() {
assert_eq!(
nudge(Key::Right, Orientation::Horizontal, 0.98, 0.05),
Some(1.0)
);
assert_eq!(nudge(Key::Right, Orientation::Horizontal, 1.0, 0.05), None);
assert_eq!(nudge(Key::Left, Orientation::Horizontal, 0.0, 0.05), None);
}
#[test]
fn a_page_is_ten_arrow_presses() {
assert_eq!(
nudge(Key::PageUp, Orientation::Horizontal, 0.0, 0.05),
Some(0.5)
);
}
#[test]
fn down_lowers_a_value_and_up_raises_it() {
assert_eq!(nudge(Key::Down, Orientation::Vertical, 0.5, 0.1), Some(0.4));
assert_eq!(nudge(Key::Up, Orientation::Vertical, 0.5, 0.1), Some(0.6));
}
#[test]
fn a_stepped_range_moves_one_notch_at_a_time() {
assert_eq!(
nudge_stepped(Key::Right, Orientation::Horizontal, 0.5, 4),
Some(0.75)
);
assert_eq!(
nudge_stepped(Key::Left, Orientation::Horizontal, 0.5, 4),
Some(0.25)
);
assert_eq!(
nudge_stepped(Key::End, Orientation::Horizontal, 0.5, 4),
Some(1.0)
);
assert_eq!(
nudge_stepped(Key::Right, Orientation::Horizontal, 1.0, 4),
None
);
}
#[test]
fn a_stepped_range_lands_on_a_notch_from_between_two() {
assert_eq!(
nudge_stepped(Key::Right, Orientation::Horizontal, 0.6, 4),
Some(0.75)
);
}
#[test]
fn the_edit_menu_is_the_usual_one() {
let menu = super::edit_menu();
assert_eq!(menu.name.as_ref(), "Edit");
let names: Vec<String> = menu
.items
.iter()
.filter_map(|item| match item {
gpui::MenuItem::Action {
name, os_action, ..
} => {
assert!(os_action.is_some(), "{name} needs an OsAction");
Some(name.to_string())
}
_ => None,
})
.collect();
assert_eq!(
names,
["Undo", "Redo", "Cut", "Copy", "Paste", "Select All"]
);
}
#[test]
fn the_standard_bindings_parse_and_do_not_collide() {
let bindings = standard_bindings();
let keys = |binding: &KeyBinding| -> String {
binding
.keystrokes()
.iter()
.map(|keystroke| keystroke.unparse())
.collect::<Vec<_>>()
.join(" ")
};
let mut seen = std::collections::HashSet::new();
for binding in &bindings {
let scoped = binding.predicate().is_some();
assert!(
seen.insert((keys(binding), scoped)),
"{} is bound twice",
keys(binding)
);
}
let unscoped: Vec<String> = bindings
.iter()
.filter(|binding| binding.predicate().is_none())
.map(keys)
.collect();
assert_eq!(unscoped, ["tab", "shift-tab", "escape"]);
}
}