Debian Codegraph @

input/driver_windows.go

raw
1 //go:build windows
2 // +build windows
3
4 package input
5
6 import (
7 "errors"
8 "fmt"
9 "strings"
10 "time"
11 "unicode"
12 "unicode/utf16"
13 "unicode/utf8"
14
15 "github.com/charmbracelet/x/ansi"
16 xwindows "github.com/charmbracelet/x/windows"
17 "github.com/muesli/cancelreader"
18 "golang.org/x/sys/windows"
19 )
20
21 // ReadEvents reads input events from the terminal.
22 //
23 // It reads the events available in the input buffer and returns them.
24 func (d *Reader) ReadEvents() ([]Event, error) {
25 events, err := d.handleConInput()
26 if errors.Is(err, errNotConInputReader) {
27 return d.readEvents()
28 }
29 return events, err
30 }
31
32 var errNotConInputReader = fmt.Errorf("handleConInput: not a conInputReader")
33
34 func (d *Reader) handleConInput() ([]Event, error) {
35 cc, ok := d.rd.(*conInputReader)
36 if !ok {
37 return nil, errNotConInputReader
38 }
39
40 var (
41 events []xwindows.InputRecord
42 err error
43 )
44 for {
45 // Peek up to 256 events, this is to allow for sequences events reported as
46 // key events.
47 events, err = peekNConsoleInputs(cc.conin, 256)
48 if cc.isCanceled() {
49 return nil, cancelreader.ErrCanceled
50 }
51 if err != nil {
52 return nil, fmt.Errorf("peek coninput events: %w", err)
53 }
54 if len(events) > 0 {
55 break
56 }
57
58 // Sleep for a bit to avoid busy waiting.
59 time.Sleep(10 * time.Millisecond)
60 }
61
62 events, err = readNConsoleInputs(cc.conin, uint32(len(events)))
63 if cc.isCanceled() {
64 return nil, cancelreader.ErrCanceled
65 }
66 if err != nil {
67 return nil, fmt.Errorf("read coninput events: %w", err)
68 }
69
70 var evs []Event
71 for _, event := range events {
72 if e := d.parser.parseConInputEvent(event, &d.keyState); e != nil {
73 if multi, ok := e.(MultiEvent); ok {
74 evs = append(evs, multi...)
75 } else {
76 evs = append(evs, e)
77 }
78 }
79 }
80
81 return evs, nil
82 }
83
84 func (p *Parser) parseConInputEvent(event xwindows.InputRecord, keyState *win32InputState) Event {
85 switch event.EventType {
86 case xwindows.KEY_EVENT:
87 kevent := event.KeyEvent()
88 return p.parseWin32InputKeyEvent(keyState, kevent.VirtualKeyCode, kevent.VirtualScanCode,
89 kevent.Char, kevent.KeyDown, kevent.ControlKeyState, kevent.RepeatCount)
90
91 case xwindows.WINDOW_BUFFER_SIZE_EVENT:
92 wevent := event.WindowBufferSizeEvent()
93 if wevent.Size.X != keyState.lastWinsizeX || wevent.Size.Y != keyState.lastWinsizeY {
94 keyState.lastWinsizeX, keyState.lastWinsizeY = wevent.Size.X, wevent.Size.Y
95 return WindowSizeEvent{
96 Width: int(wevent.Size.X),
97 Height: int(wevent.Size.Y),
98 }
99 }
100 case xwindows.MOUSE_EVENT:
101 mevent := event.MouseEvent()
102 Event := mouseEvent(keyState.lastMouseBtns, mevent)
103 keyState.lastMouseBtns = mevent.ButtonState
104 return Event
105 case xwindows.FOCUS_EVENT:
106 fevent := event.FocusEvent()
107 if fevent.SetFocus {
108 return FocusEvent{}
109 }
110 return BlurEvent{}
111 case xwindows.MENU_EVENT:
112 // ignore
113 }
114 return nil
115 }
116
117 func mouseEventButton(p, s uint32) (MouseButton, bool) {
118 var isRelease bool
119 button := MouseNone
120 btn := p ^ s
121 if btn&s == 0 {
122 isRelease = true
123 }
124
125 if btn == 0 {
126 switch {
127 case s&xwindows.FROM_LEFT_1ST_BUTTON_PRESSED > 0:
128 button = MouseLeft
129 case s&xwindows.FROM_LEFT_2ND_BUTTON_PRESSED > 0:
130 button = MouseMiddle
131 case s&xwindows.RIGHTMOST_BUTTON_PRESSED > 0:
132 button = MouseRight
133 case s&xwindows.FROM_LEFT_3RD_BUTTON_PRESSED > 0:
134 button = MouseBackward
135 case s&xwindows.FROM_LEFT_4TH_BUTTON_PRESSED > 0:
136 button = MouseForward
137 }
138 return button, isRelease
139 }
140
141 switch btn {
142 case xwindows.FROM_LEFT_1ST_BUTTON_PRESSED: // left button
143 button = MouseLeft
144 case xwindows.RIGHTMOST_BUTTON_PRESSED: // right button
145 button = MouseRight
146 case xwindows.FROM_LEFT_2ND_BUTTON_PRESSED: // middle button
147 button = MouseMiddle
148 case xwindows.FROM_LEFT_3RD_BUTTON_PRESSED: // unknown (possibly mouse backward)
149 button = MouseBackward
150 case xwindows.FROM_LEFT_4TH_BUTTON_PRESSED: // unknown (possibly mouse forward)
151 button = MouseForward
152 }
153
154 return button, isRelease
155 }
156
157 func mouseEvent(p uint32, e xwindows.MouseEventRecord) (ev Event) {
158 var mod KeyMod
159 var isRelease bool
160 if e.ControlKeyState&(xwindows.LEFT_ALT_PRESSED|xwindows.RIGHT_ALT_PRESSED) != 0 {
161 mod |= ModAlt
162 }
163 if e.ControlKeyState&(xwindows.LEFT_CTRL_PRESSED|xwindows.RIGHT_CTRL_PRESSED) != 0 {
164 mod |= ModCtrl
165 }
166 if e.ControlKeyState&(xwindows.SHIFT_PRESSED) != 0 {
167 mod |= ModShift
168 }
169
170 m := Mouse{
171 X: int(e.MousePositon.X),
172 Y: int(e.MousePositon.Y),
173 Mod: mod,
174 }
175
176 wheelDirection := int16(highWord(e.ButtonState)) //nolint:gosec
177 switch e.EventFlags {
178 case 0, xwindows.DOUBLE_CLICK:
179 m.Button, isRelease = mouseEventButton(p, e.ButtonState)
180 case xwindows.MOUSE_WHEELED:
181 if wheelDirection > 0 {
182 m.Button = MouseWheelUp
183 } else {
184 m.Button = MouseWheelDown
185 }
186 case xwindows.MOUSE_HWHEELED:
187 if wheelDirection > 0 {
188 m.Button = MouseWheelRight
189 } else {
190 m.Button = MouseWheelLeft
191 }
192 case xwindows.MOUSE_MOVED:
193 m.Button, _ = mouseEventButton(p, e.ButtonState)
194 return MouseMotionEvent(m)
195 }
196
197 if isWheel(m.Button) {
198 return MouseWheelEvent(m)
199 } else if isRelease {
200 return MouseReleaseEvent(m)
201 }
202
203 return MouseClickEvent(m)
204 }
205
206 func highWord(data uint32) uint16 {
207 return uint16((data & 0xFFFF0000) >> 16) //nolint:gosec
208 }
209
210 func readNConsoleInputs(console windows.Handle, maxEvents uint32) ([]xwindows.InputRecord, error) {
211 if maxEvents == 0 {
212 return nil, fmt.Errorf("maxEvents cannot be zero")
213 }
214
215 records := make([]xwindows.InputRecord, maxEvents)
216 n, err := readConsoleInput(console, records)
217 return records[:n], err
218 }
219
220 func readConsoleInput(console windows.Handle, inputRecords []xwindows.InputRecord) (uint32, error) {
221 if len(inputRecords) == 0 {
222 return 0, fmt.Errorf("size of input record buffer cannot be zero")
223 }
224
225 var read uint32
226
227 err := xwindows.ReadConsoleInput(console, &inputRecords[0], uint32(len(inputRecords)), &read) //nolint:gosec
228
229 return read, err //nolint:wrapcheck
230 }
231
232 func peekConsoleInput(console windows.Handle, inputRecords []xwindows.InputRecord) (uint32, error) {
233 if len(inputRecords) == 0 {
234 return 0, fmt.Errorf("size of input record buffer cannot be zero")
235 }
236
237 var read uint32
238
239 err := xwindows.PeekConsoleInput(console, &inputRecords[0], uint32(len(inputRecords)), &read) //nolint:gosec
240
241 return read, err //nolint:wrapcheck
242 }
243
244 func peekNConsoleInputs(console windows.Handle, maxEvents uint32) ([]xwindows.InputRecord, error) {
245 if maxEvents == 0 {
246 return nil, fmt.Errorf("maxEvents cannot be zero")
247 }
248
249 records := make([]xwindows.InputRecord, maxEvents)
250 n, err := peekConsoleInput(console, records)
251 return records[:n], err
252 }
253
254 // parseWin32InputKeyEvent parses a single key event from either the Windows
255 // Console API or win32-input-mode events. When state is nil, it means this is
256 // an event from win32-input-mode. Otherwise, it's a key event from the Windows
257 // Console API and needs a state to decode ANSI escape sequences and utf16
258 // runes.
259 func (p *Parser) parseWin32InputKeyEvent(state *win32InputState, vkc uint16, _ uint16, r rune, keyDown bool, cks uint32, repeatCount uint16) (event Event) {
260 defer func() {
261 // Respect the repeat count.
262 if repeatCount > 1 {
263 var multi MultiEvent
264 for i := 0; i < int(repeatCount); i++ {
265 multi = append(multi, event)
266 }
267 event = multi
268 }
269 }()
270 if state != nil {
271 defer func() {
272 state.lastCks = cks
273 }()
274 }
275
276 var utf8Buf [utf8.UTFMax]byte
277 var key Key
278 if state != nil && state.utf16Half {
279 state.utf16Half = false
280 state.utf16Buf[1] = r
281 codepoint := utf16.DecodeRune(state.utf16Buf[0], state.utf16Buf[1])
282 rw := utf8.EncodeRune(utf8Buf[:], codepoint)
283 r, _ = utf8.DecodeRune(utf8Buf[:rw])
284 key.Code = r
285 key.Text = string(r)
286 key.Mod = translateControlKeyState(cks)
287 key = ensureKeyCase(key, cks)
288 if keyDown {
289 return KeyPressEvent(key)
290 }
291 return KeyReleaseEvent(key)
292 }
293
294 var baseCode rune
295 switch {
296 case vkc == 0:
297 // Zero means this event is either an escape code or a unicode
298 // codepoint.
299 if state != nil && state.ansiIdx == 0 && r != ansi.ESC {
300 // This is a unicode codepoint.
301 baseCode = r
302 break
303 }
304
305 if state != nil {
306 // Collect ANSI escape code.
307 state.ansiBuf[state.ansiIdx] = byte(r)
308 state.ansiIdx++
309 if state.ansiIdx <= 2 {
310 // We haven't received enough bytes to determine if this is an
311 // ANSI escape code.
312 return nil
313 }
314 if r == ansi.ESC {
315 // We're expecting a closing String Terminator [ansi.ST].
316 return nil
317 }
318
319 n, event := p.parseSequence(state.ansiBuf[:state.ansiIdx])
320 if n == 0 {
321 return nil
322 }
323 if _, ok := event.(UnknownEvent); ok {
324 return nil
325 }
326
327 state.ansiIdx = 0
328 return event
329 }
330 case vkc == xwindows.VK_BACK:
331 baseCode = KeyBackspace
332 case vkc == xwindows.VK_TAB:
333 baseCode = KeyTab
334 case vkc == xwindows.VK_RETURN:
335 baseCode = KeyEnter
336 case vkc == xwindows.VK_SHIFT:
337 //nolint:nestif
338 if cks&xwindows.SHIFT_PRESSED != 0 {
339 if cks&xwindows.ENHANCED_KEY != 0 {
340 baseCode = KeyRightShift
341 } else {
342 baseCode = KeyLeftShift
343 }
344 } else if state != nil {
345 if state.lastCks&xwindows.SHIFT_PRESSED != 0 {
346 if state.lastCks&xwindows.ENHANCED_KEY != 0 {
347 baseCode = KeyRightShift
348 } else {
349 baseCode = KeyLeftShift
350 }
351 }
352 }
353 case vkc == xwindows.VK_CONTROL:
354 if cks&xwindows.LEFT_CTRL_PRESSED != 0 {
355 baseCode = KeyLeftCtrl
356 } else if cks&xwindows.RIGHT_CTRL_PRESSED != 0 {
357 baseCode = KeyRightCtrl
358 } else if state != nil {
359 if state.lastCks&xwindows.LEFT_CTRL_PRESSED != 0 {
360 baseCode = KeyLeftCtrl
361 } else if state.lastCks&xwindows.RIGHT_CTRL_PRESSED != 0 {
362 baseCode = KeyRightCtrl
363 }
364 }
365 case vkc == xwindows.VK_MENU:
366 if cks&xwindows.LEFT_ALT_PRESSED != 0 {
367 baseCode = KeyLeftAlt
368 } else if cks&xwindows.RIGHT_ALT_PRESSED != 0 {
369 baseCode = KeyRightAlt
370 } else if state != nil {
371 if state.lastCks&xwindows.LEFT_ALT_PRESSED != 0 {
372 baseCode = KeyLeftAlt
373 } else if state.lastCks&xwindows.RIGHT_ALT_PRESSED != 0 {
374 baseCode = KeyRightAlt
375 }
376 }
377 case vkc == xwindows.VK_PAUSE:
378 baseCode = KeyPause
379 case vkc == xwindows.VK_CAPITAL:
380 baseCode = KeyCapsLock
381 case vkc == xwindows.VK_ESCAPE:
382 baseCode = KeyEscape
383 case vkc == xwindows.VK_SPACE:
384 baseCode = KeySpace
385 case vkc == xwindows.VK_PRIOR:
386 baseCode = KeyPgUp
387 case vkc == xwindows.VK_NEXT:
388 baseCode = KeyPgDown
389 case vkc == xwindows.VK_END:
390 baseCode = KeyEnd
391 case vkc == xwindows.VK_HOME:
392 baseCode = KeyHome
393 case vkc == xwindows.VK_LEFT:
394 baseCode = KeyLeft
395 case vkc == xwindows.VK_UP:
396 baseCode = KeyUp
397 case vkc == xwindows.VK_RIGHT:
398 baseCode = KeyRight
399 case vkc == xwindows.VK_DOWN:
400 baseCode = KeyDown
401 case vkc == xwindows.VK_SELECT:
402 baseCode = KeySelect
403 case vkc == xwindows.VK_SNAPSHOT:
404 baseCode = KeyPrintScreen
405 case vkc == xwindows.VK_INSERT:
406 baseCode = KeyInsert
407 case vkc == xwindows.VK_DELETE:
408 baseCode = KeyDelete
409 case vkc >= '0' && vkc <= '9':
410 baseCode = rune(vkc)
411 case vkc >= 'A' && vkc <= 'Z':
412 // Convert to lowercase.
413 baseCode = rune(vkc) + 32
414 case vkc == xwindows.VK_LWIN:
415 baseCode = KeyLeftSuper
416 case vkc == xwindows.VK_RWIN:
417 baseCode = KeyRightSuper
418 case vkc == xwindows.VK_APPS:
419 baseCode = KeyMenu
420 case vkc >= xwindows.VK_NUMPAD0 && vkc <= xwindows.VK_NUMPAD9:
421 baseCode = rune(vkc-xwindows.VK_NUMPAD0) + KeyKp0
422 case vkc == xwindows.VK_MULTIPLY:
423 baseCode = KeyKpMultiply
424 case vkc == xwindows.VK_ADD:
425 baseCode = KeyKpPlus
426 case vkc == xwindows.VK_SEPARATOR:
427 baseCode = KeyKpComma
428 case vkc == xwindows.VK_SUBTRACT:
429 baseCode = KeyKpMinus
430 case vkc == xwindows.VK_DECIMAL:
431 baseCode = KeyKpDecimal
432 case vkc == xwindows.VK_DIVIDE:
433 baseCode = KeyKpDivide
434 case vkc >= xwindows.VK_F1 && vkc <= xwindows.VK_F24:
435 baseCode = rune(vkc-xwindows.VK_F1) + KeyF1
436 case vkc == xwindows.VK_NUMLOCK:
437 baseCode = KeyNumLock
438 case vkc == xwindows.VK_SCROLL:
439 baseCode = KeyScrollLock
440 case vkc == xwindows.VK_LSHIFT:
441 baseCode = KeyLeftShift
442 case vkc == xwindows.VK_RSHIFT:
443 baseCode = KeyRightShift
444 case vkc == xwindows.VK_LCONTROL:
445 baseCode = KeyLeftCtrl
446 case vkc == xwindows.VK_RCONTROL:
447 baseCode = KeyRightCtrl
448 case vkc == xwindows.VK_LMENU:
449 baseCode = KeyLeftAlt
450 case vkc == xwindows.VK_RMENU:
451 baseCode = KeyRightAlt
452 case vkc == xwindows.VK_VOLUME_MUTE:
453 baseCode = KeyMute
454 case vkc == xwindows.VK_VOLUME_DOWN:
455 baseCode = KeyLowerVol
456 case vkc == xwindows.VK_VOLUME_UP:
457 baseCode = KeyRaiseVol
458 case vkc == xwindows.VK_MEDIA_NEXT_TRACK:
459 baseCode = KeyMediaNext
460 case vkc == xwindows.VK_MEDIA_PREV_TRACK:
461 baseCode = KeyMediaPrev
462 case vkc == xwindows.VK_MEDIA_STOP:
463 baseCode = KeyMediaStop
464 case vkc == xwindows.VK_MEDIA_PLAY_PAUSE:
465 baseCode = KeyMediaPlayPause
466 case vkc == xwindows.VK_OEM_1:
467 baseCode = ';'
468 case vkc == xwindows.VK_OEM_PLUS:
469 baseCode = '+'
470 case vkc == xwindows.VK_OEM_COMMA:
471 baseCode = ','
472 case vkc == xwindows.VK_OEM_MINUS:
473 baseCode = '-'
474 case vkc == xwindows.VK_OEM_PERIOD:
475 baseCode = '.'
476 case vkc == xwindows.VK_OEM_2:
477 baseCode = '/'
478 case vkc == xwindows.VK_OEM_3:
479 baseCode = '`'
480 case vkc == xwindows.VK_OEM_4:
481 baseCode = '['
482 case vkc == xwindows.VK_OEM_5:
483 baseCode = '\\'
484 case vkc == xwindows.VK_OEM_6:
485 baseCode = ']'
486 case vkc == xwindows.VK_OEM_7:
487 baseCode = '\''
488 }
489
490 if utf16.IsSurrogate(r) {
491 if state != nil {
492 state.utf16Buf[0] = r
493 state.utf16Half = true
494 }
495 return nil
496 }
497
498 // AltGr is left ctrl + right alt. On non-US keyboards, this is used to type
499 // special characters and produce printable events.
500 // XXX: Should this be a KeyMod?
501 altGr := cks&(xwindows.LEFT_CTRL_PRESSED|xwindows.RIGHT_ALT_PRESSED) == xwindows.LEFT_CTRL_PRESSED|xwindows.RIGHT_ALT_PRESSED
502
503 var text string
504 keyCode := baseCode
505 if !unicode.IsControl(r) {
506 rw := utf8.EncodeRune(utf8Buf[:], r)
507 keyCode, _ = utf8.DecodeRune(utf8Buf[:rw])
508 if unicode.IsPrint(keyCode) && (cks == 0 ||
509 cks == xwindows.SHIFT_PRESSED ||
510 cks == xwindows.CAPSLOCK_ON ||
511 altGr) {
512 // If the control key state is 0, shift is pressed, or caps lock
513 // then the key event is a printable event i.e. [text] is not empty.
514 text = string(keyCode)
515 }
516 }
517
518 key.Code = keyCode
519 key.Text = text
520 key.Mod = translateControlKeyState(cks)
521 key.BaseCode = baseCode
522 key = ensureKeyCase(key, cks)
523 if keyDown {
524 return KeyPressEvent(key)
525 }
526
527 return KeyReleaseEvent(key)
528 }
529
530 // ensureKeyCase ensures that the key's text is in the correct case based on the
531 // control key state.
532 func ensureKeyCase(key Key, cks uint32) Key {
533 if len(key.Text) == 0 {
534 return key
535 }
536
537 hasShift := cks&xwindows.SHIFT_PRESSED != 0
538 hasCaps := cks&xwindows.CAPSLOCK_ON != 0
539 if hasShift || hasCaps {
540 if unicode.IsLower(key.Code) {
541 key.ShiftedCode = unicode.ToUpper(key.Code)
542 key.Text = string(key.ShiftedCode)
543 }
544 } else {
545 if unicode.IsUpper(key.Code) {
546 key.ShiftedCode = unicode.ToLower(key.Code)
547 key.Text = string(key.ShiftedCode)
548 }
549 }
550
551 return key
552 }
553
554 // translateControlKeyState translates the control key state from the Windows
555 // Console API into a Mod bitmask.
556 func translateControlKeyState(cks uint32) (m KeyMod) {
557 if cks&xwindows.LEFT_CTRL_PRESSED != 0 || cks&xwindows.RIGHT_CTRL_PRESSED != 0 {
558 m |= ModCtrl
559 }
560 if cks&xwindows.LEFT_ALT_PRESSED != 0 || cks&xwindows.RIGHT_ALT_PRESSED != 0 {
561 m |= ModAlt
562 }
563 if cks&xwindows.SHIFT_PRESSED != 0 {
564 m |= ModShift
565 }
566 if cks&xwindows.CAPSLOCK_ON != 0 {
567 m |= ModCapsLock
568 }
569 if cks&xwindows.NUMLOCK_ON != 0 {
570 m |= ModNumLock
571 }
572 if cks&xwindows.SCROLLLOCK_ON != 0 {
573 m |= ModScrollLock
574 }
575 return m
576 }
577
578 //nolint:unused
579 func keyEventString(vkc, sc uint16, r rune, keyDown bool, cks uint32, repeatCount uint16) string {
580 var s strings.Builder
581 s.WriteString("vkc: ")
582 s.WriteString(fmt.Sprintf("%d, 0x%02x", vkc, vkc))
583 s.WriteString(", sc: ")
584 s.WriteString(fmt.Sprintf("%d, 0x%02x", sc, sc))
585 s.WriteString(", r: ")
586 s.WriteString(fmt.Sprintf("%q", r))
587 s.WriteString(", down: ")
588 s.WriteString(fmt.Sprintf("%v", keyDown))
589 s.WriteString(", cks: [")
590 if cks&xwindows.LEFT_ALT_PRESSED != 0 {
591 s.WriteString("left alt, ")
592 }
593 if cks&xwindows.RIGHT_ALT_PRESSED != 0 {
594 s.WriteString("right alt, ")
595 }
596 if cks&xwindows.LEFT_CTRL_PRESSED != 0 {
597 s.WriteString("left ctrl, ")
598 }
599 if cks&xwindows.RIGHT_CTRL_PRESSED != 0 {
600 s.WriteString("right ctrl, ")
601 }
602 if cks&xwindows.SHIFT_PRESSED != 0 {
603 s.WriteString("shift, ")
604 }
605 if cks&xwindows.CAPSLOCK_ON != 0 {
606 s.WriteString("caps lock, ")
607 }
608 if cks&xwindows.NUMLOCK_ON != 0 {
609 s.WriteString("num lock, ")
610 }
611 if cks&xwindows.SCROLLLOCK_ON != 0 {
612 s.WriteString("scroll lock, ")
613 }
614 if cks&xwindows.ENHANCED_KEY != 0 {
615 s.WriteString("enhanced key, ")
616 }
617 s.WriteString("], repeat count: ")
618 s.WriteString(fmt.Sprintf("%d", repeatCount))
619 return s.String()
620 }