Debian Codegraph @

debian/vendor/github.com/micro-editor/tcell/v2/console_win.go

raw
1 // +build windows
2
3 // Copyright 2020 The TCell Authors
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use file except in compliance with the License.
7 // You may obtain a copy of the license at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 package tcell
18
19 import (
20 "errors"
21 "fmt"
22 "os"
23 "strings"
24 "sync"
25 "syscall"
26 "unicode/utf16"
27 "unsafe"
28 )
29
30 type cScreen struct {
31 in syscall.Handle
32 out syscall.Handle
33 out_buffer []uint16
34 cancelflag syscall.Handle
35 scandone chan struct{}
36 evch chan Event
37 quit chan struct{}
38 curx int
39 cury int
40 style Style
41 clear bool
42 fini bool
43 vten bool
44 truecolor bool
45
46 w int
47 h int
48
49 oscreen consoleInfo
50 ocursor cursorInfo
51 oimode uint32
52 oomode uint32
53 cells CellBuffer
54
55 finiOnce sync.Once
56
57 sync.Mutex
58 }
59
60 var winLock sync.Mutex
61
62 var winPalette = []Color{
63 ColorBlack,
64 ColorMaroon,
65 ColorGreen,
66 ColorNavy,
67 ColorOlive,
68 ColorPurple,
69 ColorTeal,
70 ColorSilver,
71 ColorGray,
72 ColorRed,
73 ColorLime,
74 ColorBlue,
75 ColorYellow,
76 ColorFuchsia,
77 ColorAqua,
78 ColorWhite,
79 }
80
81 var winColors = map[Color]Color{
82 ColorBlack: ColorBlack,
83 ColorMaroon: ColorMaroon,
84 ColorGreen: ColorGreen,
85 ColorNavy: ColorNavy,
86 ColorOlive: ColorOlive,
87 ColorPurple: ColorPurple,
88 ColorTeal: ColorTeal,
89 ColorSilver: ColorSilver,
90 ColorGray: ColorGray,
91 ColorRed: ColorRed,
92 ColorLime: ColorLime,
93 ColorBlue: ColorBlue,
94 ColorYellow: ColorYellow,
95 ColorFuchsia: ColorFuchsia,
96 ColorAqua: ColorAqua,
97 ColorWhite: ColorWhite,
98 }
99
100 var (
101 k32 = syscall.NewLazyDLL("kernel32.dll")
102 u32 = syscall.NewLazyDLL("user32.dll")
103 )
104
105 // We have to bring in the kernel32 and user32 DLLs directly, so we can get
106 // access to some system calls that the core Go API lacks.
107 //
108 // Note that Windows appends some functions with W to indicate that wide
109 // characters (Unicode) are in use. The documentation refers to them
110 // without this suffix, as the resolution is made via preprocessor.
111 var (
112 procReadConsoleInput = k32.NewProc("ReadConsoleInputW")
113 procWaitForMultipleObjects = k32.NewProc("WaitForMultipleObjects")
114 procCreateEvent = k32.NewProc("CreateEventW")
115 procSetEvent = k32.NewProc("SetEvent")
116 procGetConsoleCursorInfo = k32.NewProc("GetConsoleCursorInfo")
117 procSetConsoleCursorInfo = k32.NewProc("SetConsoleCursorInfo")
118 procSetConsoleCursorPosition = k32.NewProc("SetConsoleCursorPosition")
119 procSetConsoleMode = k32.NewProc("SetConsoleMode")
120 procGetConsoleMode = k32.NewProc("GetConsoleMode")
121 procGetConsoleScreenBufferInfo = k32.NewProc("GetConsoleScreenBufferInfo")
122 procFillConsoleOutputAttribute = k32.NewProc("FillConsoleOutputAttribute")
123 procFillConsoleOutputCharacter = k32.NewProc("FillConsoleOutputCharacterW")
124 procSetConsoleWindowInfo = k32.NewProc("SetConsoleWindowInfo")
125 procSetConsoleScreenBufferSize = k32.NewProc("SetConsoleScreenBufferSize")
126 procSetConsoleTextAttribute = k32.NewProc("SetConsoleTextAttribute")
127 procMessageBeep = u32.NewProc("MessageBeep")
128 )
129
130 const (
131 w32Infinite = ^uintptr(0)
132 w32WaitObject0 = uintptr(0)
133 )
134
135 const (
136 // VT100/XTerm escapes understood by the console
137 vtShowCursor = "\x1b[?25h"
138 vtHideCursor = "\x1b[?25l"
139 vtCursorPos = "\x1b[%d;%dH" // Note that it is Y then X
140 vtSgr0 = "\x1b[0m"
141 vtBold = "\x1b[1m"
142 vtUnderline = "\x1b[4m"
143 vtBlink = "\x1b[5m" // Not sure this is processed
144 vtReverse = "\x1b[7m"
145 vtSetFg = "\x1b[38;5;%dm"
146 vtSetBg = "\x1b[48;5;%dm"
147 vtSetFgRGB = "\x1b[38;2;%d;%d;%dm" // RGB
148 vtSetBgRGB = "\x1b[48;2;%d;%d;%dm" // RGB
149 )
150
151 // NewConsoleScreen returns a Screen for the Windows console associated
152 // with the current process. The Screen makes use of the Windows Console
153 // API to display content and read events.
154 func NewConsoleScreen() (Screen, error) {
155 return &cScreen{}, nil
156 }
157
158 func (s *cScreen) Init() error {
159 s.evch = make(chan Event, 10)
160 s.quit = make(chan struct{})
161 s.scandone = make(chan struct{})
162
163 in, e := syscall.Open("CONIN$", syscall.O_RDWR, 0)
164 if e != nil {
165 return e
166 }
167 s.in = in
168 out, e := syscall.Open("CONOUT$", syscall.O_RDWR, 0)
169 if e != nil {
170 syscall.Close(s.in)
171 return e
172 }
173 s.out = out
174
175 s.out_buffer = make([]uint16, 0)
176
177 s.truecolor = true
178
179 // ConEmu handling of colors and scrolling when in terminal
180 // mode is extremely problematic at the best. The color
181 // palette will scroll even though characters do not, when
182 // emiting stuff for the last character. In the future we
183 // might change this to look at specific versions of ConEmu
184 // if they fix the bug.
185 if os.Getenv("ConEmuPID") != "" {
186 s.truecolor = false
187 }
188 switch os.Getenv("TCELL_TRUECOLOR") {
189 case "disable":
190 s.truecolor = false
191 case "enable":
192 s.truecolor = true
193 }
194
195 cf, _, e := procCreateEvent.Call(
196 uintptr(0),
197 uintptr(1),
198 uintptr(0),
199 uintptr(0))
200 if cf == uintptr(0) {
201 return e
202 }
203 s.cancelflag = syscall.Handle(cf)
204
205 s.Lock()
206
207 s.curx = -1
208 s.cury = -1
209 s.style = StyleDefault
210 s.getCursorInfo(&s.ocursor)
211 s.getConsoleInfo(&s.oscreen)
212 s.getOutMode(&s.oomode)
213 s.getInMode(&s.oimode)
214 s.resize()
215
216 s.fini = false
217 s.setInMode(modeResizeEn | modeExtndFlg)
218
219 // 24-bit color is opt-in for now, because we can't figure out
220 // to make it work consistently.
221 if s.truecolor {
222 s.setOutMode(modeVtOutput | modeNoAutoNL | modeCookedOut)
223 var omode uint32
224 s.getOutMode(&omode)
225 if omode&modeVtOutput == modeVtOutput {
226 s.vten = true
227 } else {
228 s.truecolor = false
229 }
230 } else {
231 s.setOutMode(0)
232 }
233
234 s.clearScreen(s.style)
235 s.hideCursor()
236 s.Unlock()
237 go s.scanInput()
238
239 return nil
240 }
241
242 func (s *cScreen) CharacterSet() string {
243 // We are always UTF-16LE on Windows
244 return "UTF-16LE"
245 }
246
247 func (s *cScreen) EnableMouse() {
248 s.setInMode(modeResizeEn | modeMouseEn | modeExtndFlg)
249 }
250
251 func (s *cScreen) DisableMouse() {
252 s.setInMode(modeResizeEn | modeExtndFlg)
253 }
254
255 func (s *cScreen) Fini() {
256 s.finiOnce.Do(s.finish)
257 }
258
259 func (s *cScreen) finish() {
260 s.Lock()
261 s.style = StyleDefault
262 s.curx = -1
263 s.cury = -1
264 s.fini = true
265 s.vten = false
266 s.Unlock()
267
268 s.setCursorInfo(&s.ocursor)
269 s.setInMode(s.oimode)
270 s.setOutMode(s.oomode)
271 s.setBufferSize(int(s.oscreen.size.x), int(s.oscreen.size.y))
272 s.clearScreen(StyleDefault)
273 s.setCursorPos(0, 0)
274 procSetConsoleTextAttribute.Call(
275 uintptr(s.out),
276 uintptr(s.mapStyle(StyleDefault)))
277
278 close(s.quit)
279 procSetEvent.Call(uintptr(s.cancelflag))
280 // Block until scanInput returns; this prevents a race condition on Win 8+
281 // which causes syscall.Close to block until another keypress is read.
282 <-s.scandone
283 syscall.Close(s.in)
284 syscall.Close(s.out)
285 }
286
287 func (s *cScreen) PostEventWait(ev Event) {
288 s.evch <- ev
289 }
290
291 func (s *cScreen) PostEvent(ev Event) error {
292 select {
293 case s.evch <- ev:
294 return nil
295 default:
296 return ErrEventQFull
297 }
298 }
299
300 func (s *cScreen) PollEvent() Event {
301 select {
302 case <-s.quit:
303 return nil
304 case ev := <-s.evch:
305 return ev
306 }
307 }
308
309 type cursorInfo struct {
310 size uint32
311 visible uint32
312 }
313
314 type coord struct {
315 x int16
316 y int16
317 }
318
319 func (c coord) uintptr() uintptr {
320 // little endian, put x first
321 return uintptr(c.x) | (uintptr(c.y) << 16)
322 }
323
324 type rect struct {
325 left int16
326 top int16
327 right int16
328 bottom int16
329 }
330
331 func (s *cScreen) emitVtString(vs string) {
332 esc := utf16.Encode([]rune(vs))
333 s.out_buffer = append(s.out_buffer, esc...)
334 }
335
336 func (s *cScreen) showCursor() {
337 if s.vten {
338 s.emitVtString(vtShowCursor)
339 } else {
340 s.setCursorInfo(&cursorInfo{size: 100, visible: 1})
341 }
342 }
343
344 func (s *cScreen) hideCursor() {
345 if s.vten {
346 s.emitVtString(vtHideCursor)
347 } else {
348 s.setCursorInfo(&cursorInfo{size: 1, visible: 0})
349 }
350 }
351
352 func (s *cScreen) ShowCursor(x, y int) {
353 s.Lock()
354 if !s.fini {
355 s.curx = x
356 s.cury = y
357 }
358 s.doCursor()
359 s.flushOutBuffer()
360 s.Unlock()
361 }
362
363 func (s *cScreen) doCursor() {
364 x, y := s.curx, s.cury
365
366 if x < 0 || y < 0 || x >= s.w || y >= s.h {
367 s.hideCursor()
368 } else {
369 s.setCursorPos(x, y)
370 s.showCursor()
371 }
372 }
373
374 func (s *cScreen) HideCursor() {
375 s.ShowCursor(-1, -1)
376 }
377
378 type inputRecord struct {
379 typ uint16
380 _ uint16
381 data [16]byte
382 }
383
384 const (
385 keyEvent uint16 = 1
386 mouseEvent uint16 = 2
387 resizeEvent uint16 = 4
388 menuEvent uint16 = 8 // don't use
389 focusEvent uint16 = 16 // don't use
390 )
391
392 type mouseRecord struct {
393 x int16
394 y int16
395 btns uint32
396 mod uint32
397 flags uint32
398 }
399
400 const (
401 mouseDoubleClick uint32 = 0x2
402 mouseHWheeled uint32 = 0x8
403 mouseVWheeled uint32 = 0x4
404 mouseMoved uint32 = 0x1
405 )
406
407 type resizeRecord struct {
408 x int16
409 y int16
410 }
411
412 type keyRecord struct {
413 isdown int32
414 repeat uint16
415 kcode uint16
416 scode uint16
417 ch uint16
418 mod uint32
419 }
420
421 const (
422 // Constants per Microsoft. We don't put the modifiers
423 // here.
424 vkCancel = 0x03
425 vkBack = 0x08 // Backspace
426 vkTab = 0x09
427 vkClear = 0x0c
428 vkReturn = 0x0d
429 vkPause = 0x13
430 vkEscape = 0x1b
431 vkSpace = 0x20
432 vkPrior = 0x21 // PgUp
433 vkNext = 0x22 // PgDn
434 vkEnd = 0x23
435 vkHome = 0x24
436 vkLeft = 0x25
437 vkUp = 0x26
438 vkRight = 0x27
439 vkDown = 0x28
440 vkPrint = 0x2a
441 vkPrtScr = 0x2c
442 vkInsert = 0x2d
443 vkDelete = 0x2e
444 vkHelp = 0x2f
445 vkF1 = 0x70
446 vkF2 = 0x71
447 vkF3 = 0x72
448 vkF4 = 0x73
449 vkF5 = 0x74
450 vkF6 = 0x75
451 vkF7 = 0x76
452 vkF8 = 0x77
453 vkF9 = 0x78
454 vkF10 = 0x79
455 vkF11 = 0x7a
456 vkF12 = 0x7b
457 vkF13 = 0x7c
458 vkF14 = 0x7d
459 vkF15 = 0x7e
460 vkF16 = 0x7f
461 vkF17 = 0x80
462 vkF18 = 0x81
463 vkF19 = 0x82
464 vkF20 = 0x83
465 vkF21 = 0x84
466 vkF22 = 0x85
467 vkF23 = 0x86
468 vkF24 = 0x87
469 )
470
471 var vkKeys = map[uint16]Key{
472 vkCancel: KeyCancel,
473 vkBack: KeyBackspace,
474 vkTab: KeyTab,
475 vkClear: KeyClear,
476 vkPause: KeyPause,
477 vkPrint: KeyPrint,
478 vkPrtScr: KeyPrint,
479 vkPrior: KeyPgUp,
480 vkNext: KeyPgDn,
481 vkReturn: KeyEnter,
482 vkEnd: KeyEnd,
483 vkHome: KeyHome,
484 vkLeft: KeyLeft,
485 vkUp: KeyUp,
486 vkRight: KeyRight,
487 vkDown: KeyDown,
488 vkInsert: KeyInsert,
489 vkDelete: KeyDelete,
490 vkHelp: KeyHelp,
491 vkF1: KeyF1,
492 vkF2: KeyF2,
493 vkF3: KeyF3,
494 vkF4: KeyF4,
495 vkF5: KeyF5,
496 vkF6: KeyF6,
497 vkF7: KeyF7,
498 vkF8: KeyF8,
499 vkF9: KeyF9,
500 vkF10: KeyF10,
501 vkF11: KeyF11,
502 vkF12: KeyF12,
503 vkF13: KeyF13,
504 vkF14: KeyF14,
505 vkF15: KeyF15,
506 vkF16: KeyF16,
507 vkF17: KeyF17,
508 vkF18: KeyF18,
509 vkF19: KeyF19,
510 vkF20: KeyF20,
511 vkF21: KeyF21,
512 vkF22: KeyF22,
513 vkF23: KeyF23,
514 vkF24: KeyF24,
515 }
516
517 // NB: All Windows platforms are little endian. We assume this
518 // never, ever change. The following code is endian safe. and does
519 // not use unsafe pointers.
520 func getu32(v []byte) uint32 {
521 return uint32(v[0]) + (uint32(v[1]) << 8) + (uint32(v[2]) << 16) + (uint32(v[3]) << 24)
522 }
523 func geti32(v []byte) int32 {
524 return int32(getu32(v))
525 }
526 func getu16(v []byte) uint16 {
527 return uint16(v[0]) + (uint16(v[1]) << 8)
528 }
529 func geti16(v []byte) int16 {
530 return int16(getu16(v))
531 }
532
533 // Convert windows dwControlKeyState to modifier mask
534 func mod2mask(cks uint32) ModMask {
535 mm := ModNone
536 // Left or right control
537 if (cks & (0x0008 | 0x0004)) != 0 {
538 mm |= ModCtrl
539 }
540 // Left or right alt
541 if (cks & (0x0002 | 0x0001)) != 0 {
542 mm |= ModAlt
543 }
544 // Any shift
545 if (cks & 0x0010) != 0 {
546 mm |= ModShift
547 }
548 return mm
549 }
550
551 func mrec2btns(mbtns, flags uint32) ButtonMask {
552 btns := ButtonNone
553 if mbtns&0x1 != 0 {
554 btns |= Button1
555 }
556 if mbtns&0x2 != 0 {
557 btns |= Button2
558 }
559 if mbtns&0x4 != 0 {
560 btns |= Button3
561 }
562 if mbtns&0x8 != 0 {
563 btns |= Button4
564 }
565 if mbtns&0x10 != 0 {
566 btns |= Button5
567 }
568 if mbtns&0x20 != 0 {
569 btns |= Button6
570 }
571 if mbtns&0x40 != 0 {
572 btns |= Button7
573 }
574 if mbtns&0x80 != 0 {
575 btns |= Button8
576 }
577
578 if flags&mouseVWheeled != 0 {
579 if mbtns&0x80000000 == 0 {
580 btns |= WheelUp
581 } else {
582 btns |= WheelDown
583 }
584 }
585 if flags&mouseHWheeled != 0 {
586 if mbtns&0x80000000 == 0 {
587 btns |= WheelRight
588 } else {
589 btns |= WheelLeft
590 }
591 }
592 return btns
593 }
594
595 func (s *cScreen) getConsoleInput() error {
596 // cancelFlag comes first as WaitForMultipleObjects returns the lowest index
597 // in the event that both events are signalled.
598 waitObjects := []syscall.Handle{s.cancelflag, s.in}
599 // As arrays are contiguous in memory, a pointer to the first object is the
600 // same as a pointer to the array itself.
601 pWaitObjects := unsafe.Pointer(&waitObjects[0])
602
603 rv, _, er := procWaitForMultipleObjects.Call(
604 uintptr(len(waitObjects)),
605 uintptr(pWaitObjects),
606 uintptr(0),
607 w32Infinite)
608 // WaitForMultipleObjects returns WAIT_OBJECT_0 + the index.
609 switch rv {
610 case w32WaitObject0: // s.cancelFlag
611 return errors.New("cancelled")
612 case w32WaitObject0 + 1: // s.in
613 rec := &inputRecord{}
614 var nrec int32
615 rv, _, er := procReadConsoleInput.Call(
616 uintptr(s.in),
617 uintptr(unsafe.Pointer(rec)),
618 uintptr(1),
619 uintptr(unsafe.Pointer(&nrec)))
620 if rv == 0 {
621 return er
622 }
623 if nrec != 1 {
624 return nil
625 }
626 switch rec.typ {
627 case keyEvent:
628 krec := &keyRecord{}
629 krec.isdown = geti32(rec.data[0:])
630 krec.repeat = getu16(rec.data[4:])
631 krec.kcode = getu16(rec.data[6:])
632 krec.scode = getu16(rec.data[8:])
633 krec.ch = getu16(rec.data[10:])
634 krec.mod = getu32(rec.data[12:])
635
636 if krec.isdown == 0 || krec.repeat < 1 {
637 // its a key release event, ignore it
638 return nil
639 }
640 if krec.ch != 0 {
641 // synthesized key code
642 for krec.repeat > 0 {
643 // convert shift+tab to backtab
644 if mod2mask(krec.mod) == ModShift && krec.ch == vkTab {
645 s.PostEventWait(NewEventKey(KeyBacktab, 0,
646 ModNone, ""))
647 } else {
648 s.PostEventWait(NewEventKey(KeyRune, rune(krec.ch),
649 mod2mask(krec.mod), ""))
650 }
651 krec.repeat--
652 }
653 return nil
654 }
655 key := KeyNUL // impossible on Windows
656 ok := false
657 if key, ok = vkKeys[krec.kcode]; !ok {
658 return nil
659 }
660 for krec.repeat > 0 {
661 s.PostEventWait(NewEventKey(key, rune(krec.ch),
662 mod2mask(krec.mod), ""))
663 krec.repeat--
664 }
665
666 case mouseEvent:
667 var mrec mouseRecord
668 mrec.x = geti16(rec.data[0:])
669 mrec.y = geti16(rec.data[2:])
670 mrec.btns = getu32(rec.data[4:])
671 mrec.mod = getu32(rec.data[8:])
672 mrec.flags = getu32(rec.data[12:])
673 btns := mrec2btns(mrec.btns, mrec.flags)
674 // we ignore double click, events are delivered normally
675 s.PostEventWait(NewEventMouse(int(mrec.x), int(mrec.y), btns,
676 mod2mask(mrec.mod), ""))
677
678 case resizeEvent:
679 var rrec resizeRecord
680 rrec.x = geti16(rec.data[0:])
681 rrec.y = geti16(rec.data[2:])
682 s.PostEventWait(NewEventResize(int(rrec.x), int(rrec.y)))
683
684 default:
685 }
686 default:
687 return er
688 }
689
690 return nil
691 }
692
693 func (s *cScreen) scanInput() {
694 for {
695 if e := s.getConsoleInput(); e != nil {
696 close(s.scandone)
697 return
698 }
699 }
700 }
701
702 // Windows console can display 8 characters, in either low or high intensity
703 func (s *cScreen) Colors() int {
704 if s.vten {
705 return 1 << 24
706 }
707 return 16
708 }
709
710 var vgaColors = map[Color]uint16{
711 ColorBlack: 0,
712 ColorMaroon: 0x4,
713 ColorGreen: 0x2,
714 ColorNavy: 0x1,
715 ColorOlive: 0x6,
716 ColorPurple: 0x5,
717 ColorTeal: 0x3,
718 ColorSilver: 0x7,
719 ColorGrey: 0x8,
720 ColorRed: 0xc,
721 ColorLime: 0xa,
722 ColorBlue: 0x9,
723 ColorYellow: 0xe,
724 ColorFuchsia: 0xd,
725 ColorAqua: 0xb,
726 ColorWhite: 0xf,
727 }
728
729 // Windows uses RGB signals
730 func mapColor2RGB(c Color) uint16 {
731 winLock.Lock()
732 if v, ok := winColors[c]; ok {
733 c = v
734 } else {
735 v = FindColor(c, winPalette)
736 winColors[c] = v
737 c = v
738 }
739 winLock.Unlock()
740
741 if vc, ok := vgaColors[c]; ok {
742 return vc
743 }
744 return 0
745 }
746
747 // Map a tcell style to Windows attributes
748 func (s *cScreen) mapStyle(style Style) uint16 {
749 f, b, a := style.Decompose()
750 fa := s.oscreen.attrs & 0xf
751 ba := (s.oscreen.attrs) >> 4 & 0xf
752 if f != ColorDefault && f != ColorReset {
753 fa = mapColor2RGB(f)
754 }
755 if b != ColorDefault && b != ColorReset {
756 ba = mapColor2RGB(b)
757 }
758 var attr uint16
759 // We simulate reverse by doing the color swap ourselves.
760 // Apparently windows cannot really do this except in DBCS
761 // views.
762 if a&AttrReverse != 0 {
763 attr = ba
764 attr |= (fa << 4)
765 } else {
766 attr = fa
767 attr |= (ba << 4)
768 }
769 if a&AttrBold != 0 {
770 attr |= 0x8
771 }
772 if a&AttrDim != 0 {
773 attr &^= 0x8
774 }
775 if a&AttrUnderline != 0 {
776 // Best effort -- doesn't seem to work though.
777 attr |= 0x8000
778 }
779 // Blink is unsupported
780 return attr
781 }
782
783 func (s *cScreen) SetCell(x, y int, style Style, ch ...rune) {
784 if len(ch) > 0 {
785 s.SetContent(x, y, ch[0], ch[1:], style)
786 } else {
787 s.SetContent(x, y, ' ', nil, style)
788 }
789 }
790
791 func (s *cScreen) SetContent(x, y int, mainc rune, combc []rune, style Style) {
792 s.Lock()
793 if !s.fini {
794 s.cells.SetContent(x, y, mainc, combc, style)
795 }
796 s.Unlock()
797 }
798
799 func (s *cScreen) GetContent(x, y int) (rune, []rune, Style, int) {
800 s.Lock()
801 mainc, combc, style, width := s.cells.GetContent(x, y)
802 s.Unlock()
803 return mainc, combc, style, width
804 }
805
806 func (s *cScreen) sendVtStyle(style Style) {
807 esc := &strings.Builder{}
808
809 fg, bg, attrs := style.Decompose()
810
811 esc.WriteString(vtSgr0)
812
813 if attrs&(AttrBold|AttrDim) == AttrBold {
814 esc.WriteString(vtBold)
815 }
816 if attrs&AttrBlink != 0 {
817 esc.WriteString(vtBlink)
818 }
819 if attrs&AttrUnderline != 0 {
820 esc.WriteString(vtUnderline)
821 }
822 if attrs&AttrReverse != 0 {
823 esc.WriteString(vtReverse)
824 }
825 if fg.IsRGB() {
826 r, g, b := fg.RGB()
827 fmt.Fprintf(esc, vtSetFgRGB, r, g, b)
828 } else if fg.Valid() {
829 fmt.Fprintf(esc, vtSetFg, fg&0xff)
830 }
831 if bg.IsRGB() {
832 r, g, b := bg.RGB()
833 fmt.Fprintf(esc, vtSetBgRGB, r, g, b)
834 } else if bg.Valid() {
835 fmt.Fprintf(esc, vtSetBg, bg&0xff)
836 }
837 s.emitVtString(esc.String())
838 }
839
840 func (s *cScreen) writeString(x, y int, style Style, ch []uint16) {
841 // we assume the caller has hidden the cursor
842 if len(ch) == 0 {
843 return
844 }
845 s.setCursorPos(x, y)
846
847 if s.vten {
848 s.sendVtStyle(style)
849 s.out_buffer = append(s.out_buffer, ch...)
850 } else {
851 procSetConsoleTextAttribute.Call(
852 uintptr(s.out),
853 uintptr(s.mapStyle(style)))
854 syscall.WriteConsole(s.out, &ch[0], uint32(len(ch)), nil, nil)
855 }
856 }
857
858 func (s *cScreen) flushOutBuffer() {
859 if len(s.out_buffer) <= 0 {
860 return
861 }
862
863 syscall.WriteConsole(s.out, &s.out_buffer[0], uint32(len(s.out_buffer)), nil, nil)
864 s.out_buffer = s.out_buffer[:0]
865 }
866
867 func (s *cScreen) draw() {
868 // allocate a scratch line bit enough for no combining chars.
869 // if you have combining characters, you may pay for extra allocs.
870 if s.clear {
871 s.clearScreen(s.style)
872 s.clear = false
873 s.cells.Invalidate()
874 }
875 buf := make([]uint16, 0, s.w)
876 wcs := buf[:]
877 lstyle := styleInvalid
878
879 lx, ly := -1, -1
880 ra := make([]rune, 1)
881
882 for y := 0; y < s.h; y++ {
883 for x := 0; x < s.w; x++ {
884 mainc, combc, style, width := s.cells.GetContent(x, y)
885 dirty := s.cells.Dirty(x, y)
886 if style == StyleDefault {
887 style = s.style
888 }
889
890 if !dirty || style != lstyle {
891 // write out any data queued thus far
892 // because we are going to skip over some
893 // cells, or because we need to change styles
894 s.writeString(lx, ly, lstyle, wcs)
895 wcs = buf[0:0]
896 lstyle = StyleDefault
897 if !dirty {
898 continue
899 }
900 }
901 if x > s.w-width {
902 mainc = ' '
903 combc = nil
904 width = 1
905 }
906 if len(wcs) == 0 {
907 lstyle = style
908 lx = x
909 ly = y
910 }
911 ra[0] = mainc
912 wcs = append(wcs, utf16.Encode(ra)...)
913 if len(combc) != 0 {
914 wcs = append(wcs, utf16.Encode(combc)...)
915 }
916 for dx := 0; dx < width; dx++ {
917 s.cells.SetDirty(x+dx, y, false)
918 }
919 x += width - 1
920 }
921 s.writeString(lx, ly, lstyle, wcs)
922 wcs = buf[0:0]
923 lstyle = styleInvalid
924 }
925 }
926
927 func (s *cScreen) Show() {
928 s.Lock()
929 if !s.fini {
930 s.hideCursor()
931 s.resize()
932 s.draw()
933 s.doCursor()
934 s.flushOutBuffer()
935 }
936 s.Unlock()
937 }
938
939 func (s *cScreen) Sync() {
940 s.Lock()
941 if !s.fini {
942 s.cells.Invalidate()
943 s.hideCursor()
944 s.resize()
945 s.draw()
946 s.doCursor()
947 s.flushOutBuffer()
948 }
949 s.Unlock()
950 }
951
952 type consoleInfo struct {
953 size coord
954 pos coord
955 attrs uint16
956 win rect
957 maxsz coord
958 }
959
960 func (s *cScreen) getConsoleInfo(info *consoleInfo) {
961 procGetConsoleScreenBufferInfo.Call(
962 uintptr(s.out),
963 uintptr(unsafe.Pointer(info)))
964 }
965
966 func (s *cScreen) getCursorInfo(info *cursorInfo) {
967 procGetConsoleCursorInfo.Call(
968 uintptr(s.out),
969 uintptr(unsafe.Pointer(info)))
970 }
971
972 func (s *cScreen) setCursorInfo(info *cursorInfo) {
973 procSetConsoleCursorInfo.Call(
974 uintptr(s.out),
975 uintptr(unsafe.Pointer(info)))
976
977 }
978
979 func (s *cScreen) setCursorPos(x, y int) {
980 if s.vten {
981 // Note that the string is Y first. Origin is 1,1.
982 s.emitVtString(fmt.Sprintf(vtCursorPos, y+1, x+1))
983 } else {
984 procSetConsoleCursorPosition.Call(
985 uintptr(s.out),
986 coord{int16(x), int16(y)}.uintptr())
987 }
988 }
989
990 func (s *cScreen) setBufferSize(x, y int) {
991 procSetConsoleScreenBufferSize.Call(
992 uintptr(s.out),
993 coord{int16(x), int16(y)}.uintptr())
994 }
995
996 func (s *cScreen) Size() (int, int) {
997 s.Lock()
998 w, h := s.w, s.h
999 s.Unlock()
1000
1001 return w, h
1002 }
1003
1004 func (s *cScreen) resize() {
1005 info := consoleInfo{}
1006 s.getConsoleInfo(&info)
1007
1008 w := int((info.win.right - info.win.left) + 1)
1009 h := int((info.win.bottom - info.win.top) + 1)
1010
1011 if s.w == w && s.h == h {
1012 return
1013 }
1014
1015 s.cells.Resize(w, h)
1016 s.w = w
1017 s.h = h
1018
1019 s.setBufferSize(w, h)
1020
1021 r := rect{0, 0, int16(w - 1), int16(h - 1)}
1022 procSetConsoleWindowInfo.Call(
1023 uintptr(s.out),
1024 uintptr(1),
1025 uintptr(unsafe.Pointer(&r)))
1026 s.PostEvent(NewEventResize(w, h))
1027 }
1028
1029 func (s *cScreen) Clear() {
1030 s.Fill(' ', s.style)
1031 }
1032
1033 func (s *cScreen) Fill(r rune, style Style) {
1034 s.Lock()
1035 if !s.fini {
1036 s.cells.Fill(r, style)
1037 }
1038 s.Unlock()
1039 }
1040
1041 func (s *cScreen) clearScreen(style Style) {
1042 if s.vten {
1043 s.sendVtStyle(style)
1044 row := strings.Repeat(" ", s.w)
1045 for y := 0; y < s.h; y++ {
1046 s.setCursorPos(0, y)
1047 s.emitVtString(row)
1048 }
1049 s.setCursorPos(0, 0)
1050
1051 } else {
1052 pos := coord{0, 0}
1053 attr := s.mapStyle(style)
1054 x, y := s.w, s.h
1055 scratch := uint32(0)
1056 count := uint32(x * y)
1057
1058 procFillConsoleOutputAttribute.Call(
1059 uintptr(s.out),
1060 uintptr(attr),
1061 uintptr(count),
1062 pos.uintptr(),
1063 uintptr(unsafe.Pointer(&scratch)))
1064 procFillConsoleOutputCharacter.Call(
1065 uintptr(s.out),
1066 uintptr(' '),
1067 uintptr(count),
1068 pos.uintptr(),
1069 uintptr(unsafe.Pointer(&scratch)))
1070 }
1071 }
1072
1073 const (
1074 // Input modes
1075 modeExtndFlg uint32 = 0x0080
1076 modeMouseEn = 0x0010
1077 modeResizeEn = 0x0008
1078 modeCooked = 0x0001
1079 modeVtInput = 0x0200
1080
1081 // Output modes
1082 modeCookedOut uint32 = 0x0001
1083 modeWrapEOL = 0x0002
1084 modeVtOutput = 0x0004
1085 modeNoAutoNL = 0x0008
1086 )
1087
1088 func (s *cScreen) setInMode(mode uint32) error {
1089 rv, _, err := procSetConsoleMode.Call(
1090 uintptr(s.in),
1091 uintptr(mode))
1092 if rv == 0 {
1093 return err
1094 }
1095 return nil
1096 }
1097
1098 func (s *cScreen) setOutMode(mode uint32) error {
1099 rv, _, err := procSetConsoleMode.Call(
1100 uintptr(s.out),
1101 uintptr(mode))
1102 if rv == 0 {
1103 return err
1104 }
1105 return nil
1106 }
1107
1108 func (s *cScreen) getInMode(v *uint32) {
1109 procGetConsoleMode.Call(
1110 uintptr(s.in),
1111 uintptr(unsafe.Pointer(v)))
1112 }
1113
1114 func (s *cScreen) getOutMode(v *uint32) {
1115 procGetConsoleMode.Call(
1116 uintptr(s.out),
1117 uintptr(unsafe.Pointer(v)))
1118 }
1119
1120 func (s *cScreen) SetStyle(style Style) {
1121 s.Lock()
1122 s.style = style
1123 s.Unlock()
1124 }
1125
1126 // No fallback rune support, since we have Unicode. Yay!
1127
1128 func (s *cScreen) RegisterRuneFallback(r rune, subst string) {
1129 }
1130
1131 func (s *cScreen) UnregisterRuneFallback(r rune) {
1132 }
1133
1134 func (s *cScreen) CanDisplay(r rune, checkFallbacks bool) bool {
1135 // We presume we can display anything -- we're Unicode.
1136 // (Sadly this not precisely true. Combinings are especially
1137 // poorly supported under Windows.)
1138 return true
1139 }
1140
1141 func (s *cScreen) HasMouse() bool {
1142 return true
1143 }
1144
1145 func (s *cScreen) Resize(int, int, int, int) {}
1146
1147 func (s *cScreen) HasKey(k Key) bool {
1148 // Microsoft has codes for some keys, but they are unusual,
1149 // so we don't include them. We include all the typical
1150 // 101, 105 key layout keys.
1151 valid := map[Key]bool{
1152 KeyBackspace: true,
1153 KeyTab: true,
1154 KeyEscape: true,
1155 KeyPause: true,
1156 KeyPrint: true,
1157 KeyPgUp: true,
1158 KeyPgDn: true,
1159 KeyEnter: true,
1160 KeyEnd: true,
1161 KeyHome: true,
1162 KeyLeft: true,
1163 KeyUp: true,
1164 KeyRight: true,
1165 KeyDown: true,
1166 KeyInsert: true,
1167 KeyDelete: true,
1168 KeyF1: true,
1169 KeyF2: true,
1170 KeyF3: true,
1171 KeyF4: true,
1172 KeyF5: true,
1173 KeyF6: true,
1174 KeyF7: true,
1175 KeyF8: true,
1176 KeyF9: true,
1177 KeyF10: true,
1178 KeyF11: true,
1179 KeyF12: true,
1180 KeyRune: true,
1181 }
1182
1183 return valid[k]
1184 }
1185
1186 func (s *cScreen) RegisterRawSeq(string) {}
1187 func (s *cScreen) UnregisterRawSeq(string) {}
1188 func (s *cScreen) SetPaste(bool) {}
1189
1190 func (s *cScreen) GetClipboard(string) error {
1191 return errors.New("Not supported on Windows")
1192 }
1193
1194 func (s *cScreen) SetClipboard(string, string) error {
1195 return errors.New("Not supported on Windows")
1196 }
1197
1198 func (s *cScreen) Beep() error {
1199 // A simple beep. If the sound card is not available, the sound is generated
1200 // using the speaker.
1201 //
1202 // Reference:
1203 // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebeep
1204 const simpleBeep = 0xffffffff
1205 if rv, _, err := procMessageBeep.Call(simpleBeep); rv == 0 {
1206 return err
1207 }
1208 return nil
1209 }