// Package keymap matches key presses against Rex key bindings: single keys, // sequences such as ctrl+b>c, and keys in modes. // // Key spelling follows Rex: zero or more modifiers and one key, joined with +, // in any order and any case. A key is a character, written unshifted (plus // on a US layout is shift+=), a named key such as enter or pageup, or a // physical key in brackets, such as [KeyD], named by its W3C // KeyboardEvent.code. package keymap import ( "fmt" "strings" "unicode" "unicode/utf8" "100gex/internal/rex" ) // Mods is a set of modifier keys. type Mods uint8 const ( Shift Mods = 1 << iota Ctrl Alt Super ) var modNames = map[string]Mods{ "shift": Shift, "ctrl": Ctrl, "control": Ctrl, "alt": Alt, "opt": Alt, "option": Alt, "cmd": Super, "command": Super, "super": Super, "meta": Super, "win": Super, } // namedKeys maps Rex's names for keys that type no character to the // physical keys that rex.KeyEvent reports. var namedKeys = map[string][]string{ "enter": {"enter", "numpad_enter"}, "escape": {"escape"}, "esc": {"escape"}, "tab": {"tab"}, "space": {"space"}, "backspace": {"backspace"}, "delete": {"delete"}, "insert": {"insert"}, "left": {"arrow_left"}, "right": {"arrow_right"}, "up": {"arrow_up"}, "down": {"arrow_down"}, "home": {"home"}, "end": {"end"}, "pageup": {"page_up"}, "pagedown": {"page_down"}, } func init() { for i := 1; i <= 12; i++ { f := fmt.Sprintf("f%d", i) namedKeys[f] = []string{f} } } // Chord is one key with its modifiers. type Chord struct { Mods Mods // Exactly one of these names the key. Char rune // a character, unshifted and lower case Named string // a named key, such as pageup Physical string // a physical key in rex.KeyEvent's spelling, such as key_d } // ParseChord reads one key, such as ctrl+shift+d, cmd+[Digit1], or ctrl++. func ParseChord(s string) (Chord, error) { var c Chord rest := s for { i := strings.IndexByte(rest, '+') // A + with nothing after it is the key itself, as in ctrl++. if i < 0 || i == len(rest)-1 { break } m, ok := modNames[strings.ToLower(rest[:i])] if !ok { return Chord{}, fmt.Errorf("unknown modifier %q in %q", rest[:i], s) } c.Mods |= m rest = rest[i+1:] } switch { case rest == "": return Chord{}, fmt.Errorf("no key in %q", s) case strings.HasPrefix(rest, "[") && strings.HasSuffix(rest, "]") && len(rest) > 2: c.Physical = physicalName(rest[1 : len(rest)-1]) case utf8.RuneCountInString(rest) == 1: r, _ := utf8.DecodeRuneInString(rest) c.Char = unicode.ToLower(r) default: name := strings.ToLower(rest) if _, ok := namedKeys[name]; !ok { return Chord{}, fmt.Errorf("unknown key %q in %q", rest, s) } if name == "esc" { name = "escape" } c.Named = name } return c, nil } // physicalName turns a W3C KeyboardEvent.code, such as KeyD, Digit1, // ArrowLeft, or F5, into rex.KeyEvent's snake_case spelling. func physicalName(code string) string { if len(code) >= 2 && code[0] == 'F' && strings.Trim(code[1:], "0123456789") == "" { return strings.ToLower(code) } var b strings.Builder for i, r := range code { prev, _ := utf8.DecodeLastRuneInString(code[:i]) if i > 0 && (unicode.IsUpper(r) || unicode.IsDigit(r) && !unicode.IsDigit(prev)) { b.WriteByte('_') } b.WriteRune(unicode.ToLower(r)) } return b.String() } // String spells the chord the way Rex does. func (c Chord) String() string { var parts []string for _, m := range []struct { m Mods name string }{{Shift, "shift"}, {Ctrl, "ctrl"}, {Alt, "alt"}, {Super, "cmd"}} { if c.Mods&m.m != 0 { parts = append(parts, m.name) } } switch { case c.Physical != "": parts = append(parts, "["+c.Physical+"]") case c.Named != "": parts = append(parts, c.Named) default: parts = append(parts, string(c.Char)) } return strings.Join(parts, "+") } // eventMods reads a rex.KeyEvent's modifiers. func eventMods(k rex.KeyEvent) Mods { var m Mods for _, name := range strings.Split(k.Mods, "+") { switch name { case rex.ModShift: m |= Shift case rex.ModCtrl: m |= Ctrl case rex.ModAlt: m |= Alt case rex.ModSuper: m |= Super } } return m } // Matches reports whether a key press is this chord. Characters match on the // key's unshifted character, so they follow the keyboard layout; physical // keys match on the key's position. func (c Chord) Matches(k rex.KeyEvent) bool { if eventMods(k) != c.Mods { return false } switch { case c.Physical != "": return k.Key == c.Physical case c.Named != "": for _, key := range namedKeys[c.Named] { if k.Key == key { return true } } return false default: return k.UnshiftedCodepoint != 0 && unicode.ToLower(k.UnshiftedCodepoint) == c.Char } } // isEscape reports whether k is a bare Escape. func isEscape(k rex.KeyEvent) bool { return k.Key == "escape" && k.Mods == "" } // Event returns a press of the chord's key, as pane.send_key sends it. The // server encodes it, so ctrl+l becomes a form feed. func (c Chord) Event() rex.KeyEvent { k := rex.KeyEvent{ Action: "press", Mods: rex.Mods(c.Mods&Shift != 0, c.Mods&Ctrl != 0, c.Mods&Alt != 0, c.Mods&Super != 0), } switch { case c.Physical != "": k.Key = c.Physical case c.Named != "": k.Key = namedKeys[c.Named][0] if c.Named == "space" { k.Text, k.UnshiftedCodepoint = " ", ' ' } default: k.UnshiftedCodepoint = c.Char switch { case c.Char >= 'a' && c.Char <= 'z': k.Key = "key_" + string(c.Char) case c.Char >= '0' && c.Char <= '9': k.Key = "digit_" + string(c.Char) default: k.Key = "unidentified" } text := c.Char if c.Mods&Shift != 0 { text = unicode.ToUpper(text) if text != c.Char { k.ConsumedMods = rex.ModShift } } k.Text = string(text) } return k } // namedLabels spells named keys for people. var namedLabels = map[string]string{ "enter": "Enter", "escape": "Esc", "tab": "Tab", "space": "Space", "backspace": "Backspace", "delete": "Delete", "insert": "Insert", "left": "←", "right": "→", "up": "↑", "down": "↓", "home": "Home", "end": "End", "pageup": "PgUp", "pagedown": "PgDn", } // Label spells the chord for people, such as Ctrl+Shift+D. func (c Chord) Label() string { var parts []string for _, m := range []struct { m Mods name string }{{Ctrl, "Ctrl"}, {Alt, "Alt"}, {Shift, "Shift"}, {Super, "Super"}} { if c.Mods&m.m != 0 { parts = append(parts, m.name) } } switch { case c.Physical != "": name := c.Physical for _, prefix := range []string{"key_", "digit_", "arrow_"} { name = strings.TrimPrefix(name, prefix) } parts = append(parts, strings.ToUpper(name[:1])+name[1:]) case c.Named != "": if l, ok := namedLabels[c.Named]; ok { parts = append(parts, l) } else { parts = append(parts, strings.ToUpper(c.Named)) } default: parts = append(parts, strings.ToUpper(string(c.Char))) } return strings.Join(parts, "+") }