package termview import ( "unicode" "unicode/utf8" "gioui.org/io/event" "gioui.org/io/key" "gioui.org/layout" "gioui.org/op/clip" "100gex/internal/rex" ) // allMods is every modifier a key filter may carry. const allMods = key.ModCtrl | key.ModCommand | key.ModShift | key.ModAlt | key.ModSuper // keyFilters returns the filters that route keyboard input to tag. Tab is a // focus-navigation key in Gio and is only delivered when named explicitly. func keyFilters(tag any) []key.Filter { return []key.Filter{ {Focus: tag, Optional: allMods}, {Focus: tag, Name: key.NameTab, Optional: allMods}, } } // translateKey converts a Gio key press into a Rex key event. ok is false for // presses that produce text with no Ctrl or Alt held: those also arrive as a // key.EditEvent, which carries the text the keyboard layout actually // produced, so they are sent from there instead. func translateKey(e key.Event) (k rex.KeyEvent, ok bool) { shift := e.Modifiers&key.ModShift != 0 k = rex.KeyEvent{ Action: "press", Mods: rex.Mods(shift, e.Modifiers&key.ModCtrl != 0, e.Modifiers&key.ModAlt != 0, e.Modifiers&(key.ModSuper|key.ModCommand) != 0), } ctrlOrAlt := e.Modifiers&(key.ModCtrl|key.ModAlt) != 0 if name, special := specialKeys[e.Name]; special { k.Key = name if e.Name == key.NameSpace { if !ctrlOrAlt { return k, false } k.Text, k.UnshiftedCodepoint = " ", ' ' } return k, true } // The remaining names are single printable characters, as produced by // the keyboard layout (so Shift+1 is "!", and letters are upper case). r, size := utf8.DecodeRuneInString(string(e.Name)) if r == utf8.RuneError || size != len(e.Name) || !ctrlOrAlt { return k, false } if unicode.IsUpper(r) && !shift { r = unicode.ToLower(r) } unshifted := unicode.ToLower(r) if u, ok := usUnshifted[r]; ok { unshifted = u } k.Key = physicalKeys[unshifted] if k.Key == "" { k.Key = "unidentified" } k.UnshiftedCodepoint = unshifted // The server's encoder wants the character, not a control code: it // works out Ctrl+C -> 0x03 and so on itself. k.Text = string(r) if shift && r != unshifted { k.ConsumedMods = rex.ModShift } return k, true } // textKey is the key event for text the keyboard layout or an input method // produced. Gio doesn't say which key typed it, so for a single printable // ASCII character it guesses, as for a US layout, so that key bindings such // as the c of ctrl+b>c, or shift+5 for %, can match it. func textKey(text string) rex.KeyEvent { k := rex.KeyEvent{Action: "press", Key: "unidentified", Text: text} r, size := utf8.DecodeRuneInString(text) if size != len(text) || r > unicode.MaxASCII || !unicode.IsPrint(r) { return k } if r == ' ' { k.Key, k.UnshiftedCodepoint = "space", ' ' return k } unshifted, shifted := unicode.ToLower(r), unicode.IsUpper(r) if u, ok := usUnshifted[r]; ok { unshifted, shifted = u, true } if key, ok := physicalKeys[unshifted]; ok { k.Key = key } k.UnshiftedCodepoint = unshifted if shifted { k.Mods, k.ConsumedMods = rex.ModShift, rex.ModShift } return k } // specialKeys maps Gio's names for non-text keys to Rex's physical key names. var specialKeys = map[key.Name]string{ key.NameLeftArrow: "arrow_left", key.NameRightArrow: "arrow_right", key.NameUpArrow: "arrow_up", key.NameDownArrow: "arrow_down", key.NameReturn: "enter", key.NameEnter: "numpad_enter", key.NameEscape: "escape", key.NameHome: "home", key.NameEnd: "end", key.NameDeleteBackward: "backspace", key.NameDeleteForward: "delete", key.NamePageUp: "page_up", key.NamePageDown: "page_down", key.NameTab: "tab", key.NameSpace: "space", key.NameF1: "f1", key.NameF2: "f2", key.NameF3: "f3", key.NameF4: "f4", key.NameF5: "f5", key.NameF6: "f6", key.NameF7: "f7", key.NameF8: "f8", key.NameF9: "f9", key.NameF10: "f10", key.NameF11: "f11", key.NameF12: "f12", } // physicalKeys maps the unshifted character to the key that produces it on a // US layout. Gio reports characters rather than physical keys, so this is a // best guess. Key bindings match on the unshifted character, which is right // for any layout; the physical key matters mostly for Kitty keyboard // reporting. var physicalKeys = func() map[rune]string { m := map[rune]string{ '`': "backquote", '\\': "backslash", '[': "bracket_left", ']': "bracket_right", ',': "comma", '=': "equal", '-': "minus", '.': "period", '\'': "quote", ';': "semicolon", '/': "slash", } for c := '0'; c <= '9'; c++ { m[c] = "digit_" + string(c) } for c := 'a'; c <= 'z'; c++ { m[c] = "key_" + string(c) } return m }() // usUnshifted maps shifted symbols to their unshifted characters on a US // layout. var usUnshifted = map[rune]rune{ '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', '{': '[', '}': ']', '|': '\\', ':': ';', '"': '\'', '<': ',', '>': '.', '?': '/', } // Keys turns keyboard input into Rex key events. One Keys serves a whole // window: the events go to whichever block has focus. type Keys struct { filters []event.Filter focused bool } // NewKeys returns a keyboard input handler. func NewKeys() *Keys { k := &Keys{} k.filters = []event.Filter{key.FocusFilter{Target: k}} for _, f := range keyFilters(k) { k.filters = append(k.filters, f) } return k } // Layout calls send with each key typed since the last frame. With focus, // it takes keyboard focus whenever it doesn't have it; without, it leaves // focus to another widget, such as a search field. func (k *Keys) Layout(gtx layout.Context, send func(rex.KeyEvent), focus bool) { for { ev, ok := gtx.Event(k.filters...) if !ok { break } switch e := ev.(type) { case key.FocusEvent: k.focused = e.Focus case key.EditEvent: send(textKey(e.Text)) case key.Event: if e.State != key.Press { continue } if ke, ok := translateKey(e); ok { send(ke) } } } defer clip.Rect{Max: gtx.Constraints.Max}.Push(gtx.Ops).Pop() event.Op(gtx.Ops, k) if focus && !k.focused { gtx.Execute(key.FocusCmd{Tag: k}) } }