Debian Codegraph @

vt/layout.go

raw symbols SCIP
1 // Copyright 2026 The TCell Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package vt
16
17 import (
18 "sort"
19 "sync"
20 "time"
21 )
22
23 // This file defines the layout mechanism for keyboards.
24 // All keyboards are assumed to pass "codes" that are mapped to one of
25 // the Key values (this is easy for USB because the codes are mostly the
26 // same as USB already!), and then we look up values. This can be done
27 // using a simple map, and we allow inheritance so we don't have to redefine
28 // too many things. For complex scenarios you'll probably want to make use
29 // of operating system facilities or supply your own tables (for example for
30 // Japanese keyboards.)
31
32 // ModifierMap is a map that represents keys that generate runes in various
33 // shift states (modifier states). A layout may have many of these, and they
34 // are searched until a match is fine.
35 type ModifierMap struct {
36 When func(Modifier) bool // Map only applies if this returns true
37 Map map[Key]rune // Map is the mapping from Key to specific rune when this map matches.
38 }
39
40 // KeyboardState represents the current state of the keyboard.
41 // A zero initialized value is ready for use. Note that emulators that
42 // get the associated events from their operating system do not need to
43 // make use of this, but this structure makes it possible to build an emulator
44 // with a keyboard layout that is not known to the operating system.
45 //
46 // The keyboard state is assumed to be "single threaded", meaning only a single
47 // caller will operate on it at any given time. Typically there is just a single
48 // keyboard polling thread or goroutine.
49 type KeyboardState struct {
50 deadKey map[rune]DeadKey // current dead key state
51 mod Modifier
52 layout *Layout
53 lastKey Key // last key pressed
54 lastRune rune // last rune for last key
55 repeating bool // true if we are repeating
56 repeatStart time.Time // when we started repeating
57 repeatTime time.Time // last time we checked
58 repeatDelay time.Duration // delay before starting repeat
59 repeatInterval time.Duration // duration between repeats
60 pressed map[Key]bool
61 initialized bool
62 }
63
64 // initialize the keyboard, lazily.
65 func (ks *KeyboardState) initialize() {
66 if !ks.initialized {
67 ks.pressed = make(map[Key]bool)
68 if ks.layout == nil {
69 ks.layout = KeyboardANSI
70 }
71 ks.repeatDelay = time.Millisecond * 250
72 ks.repeatInterval = time.Millisecond * 30
73 ks.initialized = true
74 }
75 }
76
77 // reset the keyboard state.
78 func (ks *KeyboardState) reset() {
79 ks.clearRepeat()
80 ks.mod = 0
81 ks.deadKey = nil
82 ks.pressed = make(map[Key]bool)
83 }
84
85 // clear repeat clears any repeating key.
86 func (ks *KeyboardState) clearRepeat() {
87 ks.repeating = false
88 ks.repeatStart = time.Time{}
89 ks.repeatTime = time.Time{}
90 ks.lastRune = 0
91 ks.lastKey = 0
92 }
93
94 // SetRepeat sets the repeat parameters. Note that this will only have any meaningful
95 // impact if the caller calls the Pressed function repeatedly (periodically) while
96 // a key is depressed.
97 //
98 // The repeat starts after a key has been held for for delay, with a new repeat
99 // added every interval.
100 //
101 // The caller should usually call this before processing keyboard events. It must
102 // not be called concurrently with either of the Pressed or Release functions.
103 func (ks *KeyboardState) SetRepeat(delay time.Duration, interval time.Duration) {
104 ks.initialize()
105 ks.repeatDelay = delay
106 ks.repeatInterval = interval
107 ks.clearRepeat()
108 }
109
110 // SetLayout sets the layout this keyboard should use.
111 // This also resets the keyboard state.
112 func (ks *KeyboardState) SetLayout(km *Layout) {
113 ks.initialize()
114 ks.reset()
115 ks.layout = km
116 }
117
118 // Pressed should be called when a given key is depressed.
119 func (ks *KeyboardState) Pressed(k Key) *KeyEvent {
120 ks.initialize()
121 event := &KeyEvent{
122 Down: true,
123 Key: k,
124 SC: k.ScanCode(),
125 Base: k.KittyBase(),
126 Mod: ks.mod,
127 }
128 // if another key was pressed, then clear the repeat state
129 lastKey := ks.lastKey
130 if lastKey != k && ks.repeatInterval != 0 {
131 ks.clearRepeat()
132 ks.repeatStart = time.Now().Add(ks.repeatDelay)
133 ks.repeatTime = ks.repeatStart
134 }
135 wasPressed := ks.pressed[k]
136 ks.pressed[k] = true
137 ks.lastKey = k
138
139 l := ks.layout
140 event.VK = l.Virtual[k]
141 if mod, ok := l.Locking[k]; ok {
142 // locking modifiers never repeat
143 if wasPressed {
144 return nil
145 }
146 if ks.mod&mod == 0 {
147 ks.mod |= mod
148 } else {
149 ks.mod &^= mod
150 }
151 ks.pressed[k] = true
152 event.Mod = ks.mod
153 return event
154 }
155 if mod, ok := l.Modifiers[k]; ok {
156 if wasPressed {
157 return nil
158 }
159 ks.mod |= mod
160 event.Mod = ks.mod
161 return event
162 }
163
164 // attempt to look up the rune for this
165 r := l.KeyToUTF(k, ks.mod)
166 if ks.deadKey == nil && l.DeadKeys != nil && r != 0 {
167 if dk, ok := l.DeadKeys[r]; ok {
168 ks.deadKey = dk.Next
169 return event
170 }
171 }
172
173 if dk := ks.deadKey; dk != nil {
174 if n, ok := dk[r]; ok {
175 if n.U != 0 {
176 event.Utf = string(n.U)
177 ks.lastRune = n.U
178 ks.deadKey = nil
179 } else {
180 ks.deadKey = n.Next
181 }
182 return event
183 }
184 // failed lookup - ignore it
185 ks.deadKey = nil
186 }
187
188 if r != 0 {
189 event.Utf = string(r)
190 }
191
192 if lastKey == k && wasPressed && ks.repeatInterval > 0 {
193 ks.repeating = true
194 if time.Now().After(ks.repeatStart) {
195 deltaT := time.Since(ks.repeatTime).Truncate(ks.repeatInterval)
196 event.Repeat = int(deltaT / ks.repeatInterval)
197 if ks.repeatTime == ks.repeatStart {
198 // fence post - count the first one!
199 event.Repeat++
200 }
201 ks.repeatTime = ks.repeatTime.Add(deltaT)
202 // if we polled before the repeat interval then report nothing
203 if event.Repeat == 0 {
204 return nil
205 }
206 }
207 }
208
209 return event
210 }
211
212 // Released should be called when a given key is Released.
213 func (ks *KeyboardState) Released(k Key) *KeyEvent {
214 ks.initialize()
215 event := &KeyEvent{
216 Down: false,
217 Key: k,
218 SC: k.ScanCode(),
219 Base: k.KittyBase(),
220 Mod: ks.mod,
221 }
222 if ks.lastKey == k {
223 ks.clearRepeat()
224 }
225 wasPressed := ks.pressed[k]
226 delete(ks.pressed, k)
227
228 l := ks.layout
229 event.VK = l.Virtual[k]
230
231 if mod, ok := ks.layout.Modifiers[k]; ok {
232 if !wasPressed {
233 // something weird
234 return nil
235 }
236 ks.mod &^= mod
237
238 event.Mod = ks.mod
239 return event
240 }
241
242 if _, ok := ks.layout.Locking[k]; !ok {
243 if r := l.KeyToUTF(k, ks.mod); r != 0 {
244 event.Utf = string(r)
245 }
246 }
247
248 // no real point in looking up UTF for key release, so we don't
249
250 return event
251 }
252
253 // DeadKey is what happens when a dead key is pressed. Either it starts an unresolved sequence,
254 // (in which case Next will be non-nil), or it resolves to a final rune (in which case U will be non-zero)
255 // This is also sometimes called a composed key sequence.
256 type DeadKey struct {
257 Next map[rune]DeadKey // Next corresponds to the next key in the sequence for dead keys
258 U rune // U is the rune that should be emitted on completion of the sequence.
259 }
260
261 // DeadRune is used internally to create a rune to represent a dead key.
262 // While any numbers can be used from this point on, the expectation is
263 // that this will be added to a smaller rune (such as an ASCII character)
264 // This rune value a bit inside the supplementary private use area B,
265 // in an attempt to minimize the chance of any conflicting use (for
266 // example nerd fonts.)
267 const DeadRune = 0x101000
268
269 // Layout is a structure that represents a keyboard layout.
270 // Applications or users may implement their own layouts by
271 // registering an instance of this.
272 type Layout struct {
273 // Name is the name of the keyboard layout.
274 // We prefer to use the same names that Microsoft uses for keyboard layouts.
275 Name string
276
277 // Base is a base keyboard layout, so that we can simplify by only
278 // overriding keys we are are handling differently.
279 Base *Layout
280
281 // DeadKeys maps specific starting keys, to an emitted rune.
282 // The keys should a rune value starting with DeadRune.
283 DeadKeys map[rune]DeadKey
284
285 // Locking are modifiers that toggle a locked state like NumLock or CapsLock.
286 Locking map[Key]Modifier
287
288 // Modifiers toggle a state, but only while the key is depressed.
289 Modifiers map[Key]Modifier
290
291 // Virtual maps keys to virtual keys.
292 Virtual map[Key]WinVK
293
294 // Maps is the list of key maps by modifier and mask.
295 // Use more specific masks first - for example NumLock
296 // mask might contain only the masks for the number keypad,
297 // and that should be listed before the maps for the rest
298 // of the keyboard. The algorithm searches for the first
299 // match, not the best match.
300 Maps []ModifierMap
301 }
302
303 func (km *Layout) KeyToUTF(k Key, m Modifier) rune {
304 for _, mm := range km.Maps {
305 if mm.When != nil && !mm.When(m) {
306 continue
307 }
308 if u, ok := mm.Map[k]; ok {
309 return u
310 }
311 }
312 if km.Base != nil {
313 return km.Base.KeyToUTF(k, m)
314 }
315 return 0
316 }
317
318 // KeysUsLower is a list of lower case key maps.
319 var KeysUsLower = map[Key]rune{
320 KeyA: 'a',
321 KeyB: 'b',
322 KeyC: 'c',
323 KeyD: 'd',
324 KeyE: 'e',
325 KeyF: 'f',
326 KeyG: 'g',
327 KeyH: 'h',
328 KeyI: 'i',
329 KeyJ: 'j',
330 KeyK: 'k',
331 KeyL: 'l',
332 KeyM: 'm',
333 KeyN: 'n',
334 KeyO: 'o',
335 KeyP: 'p',
336 KeyQ: 'q',
337 KeyR: 'r',
338 KeyS: 's',
339 KeyT: 't',
340 KeyU: 'u',
341 KeyV: 'v',
342 KeyW: 'w',
343 KeyX: 'x',
344 KeyY: 'y',
345 KeyZ: 'z',
346 }
347
348 // KeysUsUpper is a list of upper case key maps.
349 var KeysUsUpper = map[Key]rune{
350 KeyA: 'A',
351 KeyB: 'B',
352 KeyC: 'C',
353 KeyD: 'D',
354 KeyE: 'E',
355 KeyF: 'F',
356 KeyG: 'G',
357 KeyH: 'H',
358 KeyI: 'I',
359 KeyJ: 'J',
360 KeyK: 'K',
361 KeyL: 'L',
362 KeyM: 'M',
363 KeyN: 'N',
364 KeyO: 'O',
365 KeyP: 'P',
366 KeyQ: 'Q',
367 KeyR: 'R',
368 KeyS: 'S',
369 KeyT: 'T',
370 KeyU: 'U',
371 KeyV: 'V',
372 KeyW: 'W',
373 KeyX: 'X',
374 KeyY: 'Y',
375 KeyZ: 'Z',
376 }
377
378 // KeysDigits is a map of number keys to corresponding digits.
379 var KeysDigits = map[Key]rune{
380 Key1: '1',
381 Key2: '2',
382 Key3: '3',
383 Key4: '4',
384 Key5: '5',
385 Key6: '6',
386 Key7: '7',
387 Key8: '8',
388 Key9: '9',
389 Key0: '0',
390 }
391
392 // KeysPadDigits is a map of the digits on the numeric keypad,
393 // when num lock is engaged.
394 var KeysPadDigits = map[Key]rune{
395 KeyPad0: '0',
396 KeyPad1: '1',
397 KeyPad2: '2',
398 KeyPad3: '3',
399 KeyPad4: '4',
400 KeyPad5: '5',
401 KeyPad6: '6',
402 KeyPad7: '7',
403 KeyPad8: '8',
404 KeyPad9: '9',
405 KeyPadDec: '.',
406 }
407
408 var KeysPadOps = map[Key]rune{
409 KeyPadMul: '*',
410 KeyPadAdd: '+',
411 KeyPadSub: '-',
412 KeyPadDiv: '/',
413 }
414
415 // KeyboardANSI is the base PC keyboard used in ANSI (US) systems.
416 var KeyboardANSI = &Layout{
417 Name: "US",
418
419 Base: nil,
420
421 // Virtual maps physical keys to virtual keys.
422 Virtual: map[Key]WinVK{
423 KeyEsc: VkEscape,
424 KeyF1: VkF1,
425 KeyF2: VkF2,
426 KeyF3: VkF3,
427 KeyF4: VkF4,
428 KeyF5: VkF5,
429 KeyF6: VkF6,
430 KeyF7: VkF7,
431 KeyF8: VkF8,
432 KeyF9: VkF9,
433 KeyF10: VkF10,
434 KeyF11: VkF11,
435 KeyF12: VkF12,
436 KeyF13: VkF13,
437 KeyF14: VkF14,
438 KeyF15: VkF15,
439 KeyF16: VkF16,
440 KeyF17: VkF17,
441 KeyF18: VkF18,
442 KeyF19: VkF19,
443 KeyF20: VkF20,
444 KeyF21: VkF21,
445 KeyF22: VkF22,
446 KeyF23: VkF23,
447 KeyF24: VkF24,
448 KeyPrtScr: VkSnapshot,
449 KeyScrLock: VkScroll,
450 KeyPause: VkPause,
451 KeyInsert: VkInsert,
452 KeyDelete: VkDelete,
453 KeyHome: VkHome,
454 KeyEnd: VkEnd,
455 KeyPgUp: VkPrior,
456 KeyPgDn: VkNext,
457 KeyLeft: VkLeft,
458 KeyRight: VkRight,
459 KeyUp: VkUp,
460 KeyDown: VkDown,
461 KeyNumLock: VkNumLock,
462 KeyCapsLock: VkCapital,
463 KeyLShift: VkLShift,
464 KeyLCtrl: VkLControl,
465 KeyLMeta: VkLWin,
466 KeyLAlt: VkLMenu,
467 KeyRShift: VkRShift,
468 KeyRCtrl: VkRControl,
469 KeyRMeta: VkRWin,
470 KeyRAlt: VkRMenu,
471 KeyMenu: VkApps,
472 KeyConvert: VkConvert,
473 KeyNonConvert: VkNonConvert,
474 KeyBackspace: VkBack,
475 KeyEnter: VkReturn,
476 KeySpace: VkSpace,
477 KeyTab: VkTab,
478 Key1: Vk1,
479 Key2: Vk2,
480 Key3: Vk3,
481 Key4: Vk4,
482 Key5: Vk5,
483 Key6: Vk6,
484 Key7: Vk7,
485 Key8: Vk8,
486 Key9: Vk9,
487 Key0: Vk0,
488 KeyA: VkA,
489 KeyB: VkB,
490 KeyC: VkC,
491 KeyD: VkD,
492 KeyE: VkE,
493 KeyF: VkF,
494 KeyG: VkG,
495 KeyH: VkH,
496 KeyI: VkI,
497 KeyJ: VkJ,
498 KeyK: VkK,
499 KeyL: VkL,
500 KeyM: VkM,
501 KeyN: VkN,
502 KeyO: VkO,
503 KeyP: VkP,
504 KeyQ: VkQ,
505 KeyR: VkR,
506 KeyS: VkS,
507 KeyT: VkT,
508 KeyU: VkU,
509 KeyV: VkV,
510 KeyW: VkW,
511 KeyX: VkX,
512 KeyY: VkY,
513 KeyZ: VkZ,
514 KeyPadMul: VkMultiply,
515 KeyPadAdd: VkAdd,
516 KeyPadSub: VkSubtract,
517 KeyPadDiv: VkDivide,
518 KeyEqual: VkOemPlus,
519 KeyComma: VkOemComma,
520 KeyMinus: VkOemMinus,
521 KeyPeriod: VkOemPeriod,
522 KeySlash: VkOem2,
523 KeyGrave: VkOem3,
524 KeyLBrace: VkOem4,
525 KeyBackslash: VkOem5,
526 KeyRBrace: VkOem6,
527 KeyQuote: VkOem7,
528 KeyIsoBackSlash: VkOem102,
529 KeyPad0: VkInsert,
530 KeyPad1: VkEnd,
531 KeyPad2: VkDown,
532 KeyPad3: VkNext,
533 KeyPad4: VkLeft,
534 KeyPad5: VkClear,
535 KeyPad6: VkRight,
536 KeyPad7: VkHome,
537 KeyPad8: VkUp,
538 KeyPad9: VkPrior,
539 KeyPadDec: VkDelete,
540 },
541 Maps: []ModifierMap{
542 // Specials - without control
543 {
544 When: func(m Modifier) bool { return !m.IsCtrl() },
545 Map: map[Key]rune{
546 KeyTab: '\t',
547 KeyEnter: '\r',
548 KeyBackspace: '\b',
549 KeyEsc: '\x1b',
550 KeySpace: ' ',
551 KeyPadEnter: '\r',
552 },
553 },
554 // Specials - with control (but without shift)
555 {
556 When: func(m Modifier) bool { return m.IsCtrl() && !m.IsShift() },
557 Map: map[Key]rune{
558 KeyTab: '\t',
559 KeyEnter: '\n',
560 KeyBackspace: '\x7f',
561 KeyEsc: '\x1b',
562 KeySpace: ' ',
563 KeyPadEnter: '\n',
564 },
565 },
566 // Key pad operators
567 {
568 When: func(m Modifier) bool { return !m.IsAlt() },
569 Map: KeysPadOps,
570 },
571 // Numeric keypad when num lock is engaged
572 {
573 When: func(m Modifier) bool { return m.IsNumLock() },
574 Map: KeysPadDigits,
575 },
576 // Numbers - without shift
577 {
578 When: func(m Modifier) bool { return !m.IsShift() && !m.IsCtrl() },
579 Map: KeysDigits,
580 },
581 // Numbers - with shift - this is locale sensitive usually
582 {
583 When: func(m Modifier) bool { return m.IsShift() && !m.IsCtrl() },
584 Map: map[Key]rune{
585 Key1: '!',
586 Key2: '@',
587 Key3: '#',
588 Key4: '$',
589 Key5: '%',
590 Key6: '^',
591 Key7: '&',
592 Key8: '*',
593 Key9: '(',
594 Key0: ')',
595 },
596 },
597 // Special shift-control cases
598 {
599 When: func(m Modifier) bool { return m.IsCtrl() && m.IsShift() },
600 Map: map[Key]rune{
601 Key2: 0,
602 Key6: '\x1e',
603 KeyMinus: '\x1f',
604 },
605 },
606 // Letters - base (lower case)
607 {
608 When: func(m Modifier) bool { return !m.IsCtrl() && !m.IsCapitals() },
609 Map: KeysUsLower,
610 },
611 // Letters - capitals (either caps lock or shift, but not both)
612 {
613 When: func(m Modifier) bool { return !m.IsCtrl() && m.IsCapitals() },
614 Map: KeysUsUpper,
615 },
616 // OEM keys - base
617 {
618 When: func(m Modifier) bool { return !m.IsShift() && !m.IsCtrl() },
619 Map: map[Key]rune{
620 KeySemi: ';',
621 KeyEqual: '=',
622 KeyComma: ',',
623 KeyMinus: '-',
624 KeyPeriod: '.',
625 KeySlash: '/',
626 KeyGrave: '`',
627 KeyLBrace: '[',
628 KeyBackslash: '\\',
629 KeyRBrace: ']',
630 KeyQuote: '\'',
631 KeyIsoBackSlash: '\\',
632 },
633 },
634 // OEM keys - shift
635 {
636 When: func(m Modifier) bool { return m.IsShift() && !m.IsCtrl() },
637 Map: map[Key]rune{
638 KeySemi: ':',
639 KeyEqual: '+',
640 KeyComma: '<',
641 KeyMinus: '_',
642 KeyPeriod: '>',
643 KeySlash: '?',
644 KeyGrave: '~',
645 KeyLBrace: '{',
646 KeyBackslash: '|',
647 KeyRBrace: '}',
648 KeyQuote: '"',
649 KeyIsoBackSlash: '|',
650 },
651 },
652 // OEM keys - control (odd balls)
653 {
654 When: func(m Modifier) bool { return m.IsCtrl() && !m.IsShift() },
655 Map: map[Key]rune{
656 KeyLBrace: '\x1b',
657 KeyBackslash: '\x1c',
658 KeyRBrace: '\x1d',
659 KeyIsoBackSlash: '\x1c',
660 },
661 },
662 },
663 Modifiers: map[Key]Modifier{
664 KeyLShift: ModLShift,
665 KeyRShift: ModRShift,
666 KeyLCtrl: ModLCtrl,
667 KeyRCtrl: ModRCtrl,
668 KeyLAlt: ModLAlt,
669 KeyRAlt: ModRAlt,
670 KeyRMeta: ModRMeta,
671 KeyLMeta: ModLMeta,
672 KeyRHyper: ModRHyper,
673 KeyLHyper: ModLHyper,
674 },
675 Locking: map[Key]Modifier{
676 KeyNumLock: ModNumLock,
677 KeyCapsLock: ModCapsLock,
678 },
679 }
680
681 var allLayouts = map[string]*Layout{
682 KeyboardANSI.Name: KeyboardANSI,
683 }
684
685 var layoutsLock sync.Mutex
686
687 // RegisterLayout registers the given layout.
688 func RegisterLayout(km *Layout) {
689 layoutsLock.Lock()
690 allLayouts[km.Name] = km
691 layoutsLock.Unlock()
692 }
693
694 // GetLayout returns a keyboard layout for the given name.
695 // The layout must have been previously registered with RegisterLayout.
696 // (Builtin layouts do this as a consequence of importing the layout.)
697 func GetLayout(name string) *Layout {
698 layoutsLock.Lock()
699 defer layoutsLock.Unlock()
700 return allLayouts[name]
701 }
702
703 // Layouts returns a list of all known layout names.
704 func Layouts() []string {
705 layoutsLock.Lock()
706 defer layoutsLock.Unlock()
707 res := make([]string, 0, len(allLayouts))
708 for k := range allLayouts {
709 res = append(res, k)
710 }
711 sort.Strings(res)
712 return res
713 }