Nacre/src/keys.rs
astar76 a915040a0a S006: YouTube loads (HTTP/2 header limit), basics smoke, Escape leaves page full screen
servo-net 0.7.0 keeps hyper's 16 KiB HTTP/2 header list limit; YouTube sends
~19 KiB, so the stream was reset and Servo showed SendRequest. vendor/servo-net
raises it to 256 KiB (D-012).
Escape went to the page only in full screen (inverted check): keys::page_gets_key.
tests/smoke/basics.txt: tabs, navigation, address bar, find, zoom, full screen,
_blank, pop-up, new window. Selftest expect/locate, pagetype {escape}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 08:20:51 -06:00

363 lines
14 KiB
Rust

//! Keyboard: winit key events turned into the W3C key events Servo wants, and the browser's
//! shortcuts (rebindable in settings).
use std::collections::BTreeMap;
use std::str::FromStr;
use keyboard_types::{Code, Key, KeyState, Location, Modifiers, NamedKey};
use winit::event::{ElementState, KeyEvent};
use winit::keyboard::{Key as WKey, KeyLocation, ModifiersState, PhysicalKey};
/// winit -> W3C. winit's key and code names follow the W3C names, so they convert by name.
pub fn to_servo(event: &KeyEvent, mods: ModifiersState) -> keyboard_types::KeyboardEvent {
let key = match &event.logical_key {
WKey::Character(text) => Key::Character(text.to_string()),
WKey::Named(named) => {
let name = format!("{named:?}");
// winit says "Super" where W3C says "Meta".
let name = if name == "Super" { "Meta".to_owned() } else { name };
match NamedKey::from_str(&name) {
Ok(named) => Key::Named(named),
Err(_) => match named {
winit::keyboard::NamedKey::Space => Key::Character(" ".into()),
_ => Key::Named(NamedKey::Unidentified),
},
}
},
WKey::Dead(_) => Key::Named(NamedKey::Dead),
WKey::Unidentified(_) => Key::Named(NamedKey::Unidentified),
};
let code = match event.physical_key {
PhysicalKey::Code(code) => {
let name = format!("{code:?}").replace("Super", "Meta");
Code::from_str(&name).unwrap_or(Code::Unidentified)
},
PhysicalKey::Unidentified(_) => Code::Unidentified,
};
let location = match event.location {
KeyLocation::Standard => Location::Standard,
KeyLocation::Left => Location::Left,
KeyLocation::Right => Location::Right,
KeyLocation::Numpad => Location::Numpad,
};
keyboard_types::KeyboardEvent {
state: if event.state == ElementState::Pressed { KeyState::Down } else { KeyState::Up },
key,
code,
location,
modifiers: modifiers(mods),
repeat: event.repeat,
is_composing: false,
}
}
pub fn modifiers(mods: ModifiersState) -> Modifiers {
let mut m = Modifiers::empty();
m.set(Modifiers::CONTROL, mods.control_key());
m.set(Modifiers::SHIFT, mods.shift_key());
m.set(Modifiers::ALT, mods.alt_key());
m.set(Modifiers::META, mods.super_key());
m
}
/// Everything a shortcut can do.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Action {
NewTab,
NewWindow,
NewIncognito,
CloseTab,
CloseWindow,
ReopenClosed,
NextTab,
PrevTab,
Tab1,
Tab2,
Tab3,
Tab4,
Tab5,
Tab6,
Tab7,
Tab8,
LastTab,
MoveTabLeft,
MoveTabRight,
DuplicateTab,
PinTab,
MuteTab,
Back,
Forward,
Reload,
HardReload,
Stop,
Home,
FocusAddress,
Find,
FindNext,
FindPrev,
Bookmark,
BookmarkAll,
BookmarksManager,
ToggleBookmarksBar,
History,
Downloads,
Passwords,
Settings,
ZoomIn,
ZoomOut,
ZoomReset,
Fullscreen,
DevTools,
ViewSource,
SavePage,
Print,
PictureInPicture,
MediaPlayPause,
QrCode,
ClearData,
TaskManager,
Quit,
}
impl Action {
/// (action, settings key, label, default shortcuts)
pub const ALL: &'static [(Action, &'static str, &'static str, &'static [&'static str])] = &[
(Action::NewTab, "new_tab", "New tab", &["Ctrl+T"]),
(Action::NewWindow, "new_window", "New window", &["Ctrl+N"]),
(Action::NewIncognito, "new_incognito", "New incognito window", &["Ctrl+Shift+N"]),
(Action::CloseTab, "close_tab", "Close tab", &["Ctrl+W", "Ctrl+F4"]),
(Action::CloseWindow, "close_window", "Close window", &["Ctrl+Shift+W"]),
(Action::ReopenClosed, "reopen_closed", "Reopen closed tab", &["Ctrl+Shift+T"]),
(Action::NextTab, "next_tab", "Next tab", &["Ctrl+Tab", "Ctrl+PageDown"]),
(Action::PrevTab, "prev_tab", "Previous tab", &["Ctrl+Shift+Tab", "Ctrl+PageUp"]),
(Action::Tab1, "tab_1", "Tab 1", &["Ctrl+1", "Alt+1"]),
(Action::Tab2, "tab_2", "Tab 2", &["Ctrl+2", "Alt+2"]),
(Action::Tab3, "tab_3", "Tab 3", &["Ctrl+3", "Alt+3"]),
(Action::Tab4, "tab_4", "Tab 4", &["Ctrl+4", "Alt+4"]),
(Action::Tab5, "tab_5", "Tab 5", &["Ctrl+5", "Alt+5"]),
(Action::Tab6, "tab_6", "Tab 6", &["Ctrl+6", "Alt+6"]),
(Action::Tab7, "tab_7", "Tab 7", &["Ctrl+7", "Alt+7"]),
(Action::Tab8, "tab_8", "Tab 8", &["Ctrl+8", "Alt+8"]),
(Action::LastTab, "last_tab", "Last tab", &["Ctrl+9", "Alt+9"]),
(Action::MoveTabLeft, "move_tab_left", "Move tab left", &["Ctrl+Shift+PageUp"]),
(Action::MoveTabRight, "move_tab_right", "Move tab right", &["Ctrl+Shift+PageDown"]),
(Action::DuplicateTab, "duplicate_tab", "Duplicate tab", &["Ctrl+Shift+K"]),
(Action::PinTab, "pin_tab", "Pin or unpin tab", &[]),
(Action::MuteTab, "mute_tab", "Mute or unmute tab", &["Ctrl+M"]),
(Action::Back, "back", "Back", &["Alt+ArrowLeft", "BrowserBack"]),
(Action::Forward, "forward", "Forward", &["Alt+ArrowRight", "BrowserForward"]),
(Action::Reload, "reload", "Reload", &["Ctrl+R", "F5", "BrowserRefresh"]),
(Action::HardReload, "hard_reload", "Reload without cache", &["Ctrl+Shift+R", "Ctrl+F5"]),
(Action::Stop, "stop", "Stop loading", &["Escape"]),
(Action::Home, "home", "Home page", &["Alt+Home", "BrowserHome"]),
(Action::FocusAddress, "focus_address", "Go to the address bar", &["Ctrl+L", "Alt+D", "F6"]),
(Action::Find, "find", "Find in page", &["Ctrl+F"]),
(Action::FindNext, "find_next", "Find next", &["Ctrl+G", "F3"]),
(Action::FindPrev, "find_prev", "Find previous", &["Ctrl+Shift+G", "Shift+F3"]),
(Action::Bookmark, "bookmark", "Bookmark this page", &["Ctrl+D"]),
(Action::BookmarkAll, "bookmark_all", "Bookmark all tabs", &["Ctrl+Shift+D"]),
(Action::BookmarksManager, "bookmarks_manager", "Bookmark manager", &["Ctrl+Shift+O"]),
(Action::ToggleBookmarksBar, "toggle_bookmarks_bar", "Show or hide the bookmarks bar", &["Ctrl+Shift+B"]),
(Action::History, "history", "History", &["Ctrl+H"]),
(Action::Downloads, "downloads", "Downloads", &["Ctrl+J"]),
(Action::Passwords, "passwords", "Password manager", &["Ctrl+Shift+L"]),
(Action::Settings, "settings", "Settings", &["Ctrl+Comma"]),
(Action::ZoomIn, "zoom_in", "Zoom in", &["Ctrl+Equal", "Ctrl+Plus"]),
(Action::ZoomOut, "zoom_out", "Zoom out", &["Ctrl+Minus"]),
(Action::ZoomReset, "zoom_reset", "Actual size", &["Ctrl+0"]),
(Action::Fullscreen, "fullscreen", "Full screen", &["F11"]),
(Action::DevTools, "devtools", "Developer tools", &["F12", "Ctrl+Shift+I"]),
(Action::ViewSource, "view_source", "View page source", &["Ctrl+U"]),
(Action::SavePage, "save_page", "Save page as", &["Ctrl+S"]),
(Action::Print, "print", "Save as PDF or image", &["Ctrl+P"]),
(Action::PictureInPicture, "pip", "Picture in picture", &["Ctrl+Shift+Space"]),
(Action::MediaPlayPause, "media_play_pause", "Play or pause media", &["MediaPlayPause"]),
(Action::QrCode, "qr_code", "QR code for this page", &[]),
(Action::ClearData, "clear_data", "Delete browsing data", &["Ctrl+Shift+Delete"]),
(Action::TaskManager, "task_manager", "Task manager", &["Shift+Escape"]),
(Action::Quit, "quit", "Quit", &["Ctrl+Q"]),
];
pub fn key(self) -> &'static str {
Self::ALL.iter().find(|(a, ..)| *a == self).map(|(_, k, ..)| *k).unwrap_or("")
}
pub fn label(self) -> &'static str {
Self::ALL.iter().find(|(a, ..)| *a == self).map(|(_, _, l, _)| *l).unwrap_or("")
}
pub fn defaults(self) -> &'static [&'static str] {
Self::ALL.iter().find(|(a, ..)| *a == self).map(|(.., d)| *d).unwrap_or(&[])
}
}
/// A key combination.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Shortcut {
pub ctrl: bool,
pub shift: bool,
pub alt: bool,
pub meta: bool,
/// Lowercase character ("t", "1", "=") or a named key ("ArrowLeft", "F5", "Escape").
pub key: String,
}
/// Names for keys whose character is awkward in a settings file.
fn key_alias(name: &str) -> Option<&'static str> {
Some(match name.to_ascii_lowercase().as_str() {
"comma" => ",",
"equal" | "equals" => "=",
"plus" => "+",
"minus" => "-",
"period" => ".",
"slash" => "/",
"space" => " ",
_ => return None,
})
}
impl Shortcut {
/// "Ctrl+Shift+T", "Alt+ArrowLeft", "F5"
pub fn parse(text: &str) -> Option<Shortcut> {
let mut s = Shortcut { ctrl: false, shift: false, alt: false, meta: false, key: String::new() };
for part in text.split('+').map(str::trim) {
match part.to_ascii_lowercase().as_str() {
"ctrl" | "control" | "cmd" => s.ctrl = true,
"shift" => s.shift = true,
"alt" | "option" => s.alt = true,
"meta" | "super" | "win" => s.meta = true,
"" => {},
_ => {
s.key = match key_alias(part) {
Some(alias) => alias.to_owned(),
None if part.chars().count() == 1 => part.to_lowercase(),
None => part.to_owned(),
}
},
}
}
(!s.key.is_empty()).then_some(s)
}
/// The shortcut a key press makes, if it's a press.
pub fn from_event(event: &KeyEvent, mods: ModifiersState) -> Option<Shortcut> {
if event.state != ElementState::Pressed {
return None;
}
use winit::platform::modifier_supplement::KeyEventExtModifierSupplement;
let key = match event.key_without_modifiers() {
WKey::Character(c) => c.to_lowercase(),
WKey::Named(winit::keyboard::NamedKey::Space) => " ".to_owned(),
WKey::Named(named) => format!("{named:?}"),
_ => return None,
};
Some(Shortcut { ctrl: mods.control_key(), shift: mods.shift_key(), alt: mods.alt_key(), meta: mods.super_key(), key })
}
pub fn label(&self) -> String {
let mut parts = Vec::new();
if self.ctrl {
parts.push("Ctrl".to_owned());
}
if self.alt {
parts.push("Alt".to_owned());
}
if self.shift {
parts.push("Shift".to_owned());
}
if self.meta {
parts.push("Super".to_owned());
}
let key = match self.key.as_str() {
" " => "Space".to_owned(),
"," => "Comma".to_owned(),
"=" => "Equal".to_owned(),
"+" => "Plus".to_owned(),
"-" => "Minus".to_owned(),
k if k.chars().count() == 1 => k.to_uppercase(),
k => k.to_owned(),
};
parts.push(key);
parts.join("+")
}
/// Plain keys and Shift+key would steal typing; only some may be bound without a modifier.
pub fn safe_alone(&self) -> bool {
self.ctrl || self.alt || self.meta || self.key.len() > 1
}
}
/// The shortcut table in use.
pub struct Keymap {
map: BTreeMap<String, Vec<Shortcut>>,
}
impl Keymap {
/// Defaults with the user's overrides ("" unbinds an action).
pub fn new(overrides: &BTreeMap<String, String>) -> Keymap {
let mut map = BTreeMap::new();
for (_, key, _, defaults) in Action::ALL {
let list: Vec<Shortcut> = match overrides.get(*key) {
Some(text) => text.split(',').filter_map(Shortcut::parse).collect(),
None => defaults.iter().filter_map(|d| Shortcut::parse(d)).collect(),
};
map.insert((*key).to_owned(), list);
}
Keymap { map }
}
pub fn action_for(&self, shortcut: &Shortcut) -> Option<Action> {
Action::ALL.iter().find(|(_, key, ..)| self.map.get(*key).is_some_and(|list| list.contains(shortcut))).map(|(a, ..)| *a)
}
pub fn shortcuts(&self, action: Action) -> &[Shortcut] {
self.map.get(action.key()).map(Vec::as_slice).unwrap_or(&[])
}
pub fn label(&self, action: Action) -> String {
self.shortcuts(action).first().map(Shortcut::label).unwrap_or_default()
}
/// Other actions already using this shortcut.
pub fn conflicts(&self, shortcut: &Shortcut, except: Action) -> Vec<Action> {
Action::ALL.iter().filter(|(a, key, ..)| *a != except && self.map.get(*key).is_some_and(|l| l.contains(shortcut))).map(|(a, ..)| *a).collect()
}
}
/// Shortcuts that work even while a page has focus and wants the key (Chrome keeps these too).
pub fn reserved(action: Action) -> bool {
matches!(action, Action::NewTab | Action::NewWindow | Action::NewIncognito | Action::CloseTab | Action::CloseWindow | Action::ReopenClosed | Action::NextTab | Action::PrevTab | Action::Quit | Action::FocusAddress | Action::Fullscreen)
}
/// A plain Escape (Stop) on a focused page goes to the page, so sites can close their own pop-ups, except in
/// full screen, where it leaves full screen as in other browsers. Every other shortcut stays the browser's.
pub fn page_gets_key(action: Action, page_focused_plain: bool, fullscreen: bool) -> bool {
!reserved(action) && action == Action::Stop && page_focused_plain && !fullscreen
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escape_on_page() {
assert!(page_gets_key(Action::Stop, true, false));
assert!(!page_gets_key(Action::Stop, true, true), "Escape leaves page full screen");
assert!(!page_gets_key(Action::Stop, false, false));
assert!(!page_gets_key(Action::Find, true, false));
assert!(!page_gets_key(Action::NewTab, true, false));
}
#[test]
fn parse_and_label() {
let s = Shortcut::parse("Ctrl+Shift+T").unwrap();
assert!(s.ctrl && s.shift && s.key == "t");
assert_eq!(s.label(), "Ctrl+Shift+T");
assert_eq!(Shortcut::parse("Ctrl+Comma").unwrap().key, ",");
let map = Keymap::new(&BTreeMap::new());
assert_eq!(map.action_for(&Shortcut::parse("ctrl+t").unwrap()), Some(Action::NewTab));
let mut o = BTreeMap::new();
o.insert("new_tab".to_owned(), String::new());
assert_eq!(Keymap::new(&o).action_for(&Shortcut::parse("Ctrl+T").unwrap()), None);
}
}