Debian Codegraph @

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

raw
1 // Copyright 2020 The TCell Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use 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 terminfo
16
17 import (
18 "bytes"
19 "errors"
20 "fmt"
21 "io"
22 "os"
23 "strconv"
24 "strings"
25 "sync"
26 "time"
27 )
28
29 var (
30 // ErrTermNotFound indicates that a suitable terminal entry could
31 // not be found. This can result from either not having TERM set,
32 // or from the TERM failing to support certain minimal functionality,
33 // in particular absolute cursor addressability (the cup capability)
34 // is required. For example, legacy "adm3" lacks this capability,
35 // whereas the slightly newer "adm3a" supports it. This failure
36 // occurs most often with "dumb".
37 ErrTermNotFound = errors.New("terminal entry not found")
38 )
39
40 // Terminfo represents a terminfo entry. Note that we use friendly names
41 // in Go, but when we write out JSON, we use the same names as terminfo.
42 // The name, aliases and smous, rmous fields do not come from terminfo directly.
43 type Terminfo struct {
44 Name string
45 Aliases []string
46 Columns int // cols
47 Lines int // lines
48 Colors int // colors
49 Bell string // bell
50 Clear string // clear
51 EnterCA string // smcup
52 ExitCA string // rmcup
53 ShowCursor string // cnorm
54 HideCursor string // civis
55 AttrOff string // sgr0
56 Underline string // smul
57 Bold string // bold
58 Blink string // blink
59 Reverse string // rev
60 Dim string // dim
61 Italic string // sitm
62 EnterKeypad string // smkx
63 ExitKeypad string // rmkx
64 SetFg string // setaf
65 SetBg string // setab
66 ResetFgBg string // op
67 SetCursor string // cup
68 CursorBack1 string // cub1
69 CursorUp1 string // cuu1
70 PadChar string // pad
71 KeyBackspace string // kbs
72 KeyF1 string // kf1
73 KeyF2 string // kf2
74 KeyF3 string // kf3
75 KeyF4 string // kf4
76 KeyF5 string // kf5
77 KeyF6 string // kf6
78 KeyF7 string // kf7
79 KeyF8 string // kf8
80 KeyF9 string // kf9
81 KeyF10 string // kf10
82 KeyF11 string // kf11
83 KeyF12 string // kf12
84 KeyF13 string // kf13
85 KeyF14 string // kf14
86 KeyF15 string // kf15
87 KeyF16 string // kf16
88 KeyF17 string // kf17
89 KeyF18 string // kf18
90 KeyF19 string // kf19
91 KeyF20 string // kf20
92 KeyF21 string // kf21
93 KeyF22 string // kf22
94 KeyF23 string // kf23
95 KeyF24 string // kf24
96 KeyF25 string // kf25
97 KeyF26 string // kf26
98 KeyF27 string // kf27
99 KeyF28 string // kf28
100 KeyF29 string // kf29
101 KeyF30 string // kf30
102 KeyF31 string // kf31
103 KeyF32 string // kf32
104 KeyF33 string // kf33
105 KeyF34 string // kf34
106 KeyF35 string // kf35
107 KeyF36 string // kf36
108 KeyF37 string // kf37
109 KeyF38 string // kf38
110 KeyF39 string // kf39
111 KeyF40 string // kf40
112 KeyF41 string // kf41
113 KeyF42 string // kf42
114 KeyF43 string // kf43
115 KeyF44 string // kf44
116 KeyF45 string // kf45
117 KeyF46 string // kf46
118 KeyF47 string // kf47
119 KeyF48 string // kf48
120 KeyF49 string // kf49
121 KeyF50 string // kf50
122 KeyF51 string // kf51
123 KeyF52 string // kf52
124 KeyF53 string // kf53
125 KeyF54 string // kf54
126 KeyF55 string // kf55
127 KeyF56 string // kf56
128 KeyF57 string // kf57
129 KeyF58 string // kf58
130 KeyF59 string // kf59
131 KeyF60 string // kf60
132 KeyF61 string // kf61
133 KeyF62 string // kf62
134 KeyF63 string // kf63
135 KeyF64 string // kf64
136 KeyInsert string // kich1
137 KeyDelete string // kdch1
138 KeyHome string // khome
139 KeyEnd string // kend
140 KeyHelp string // khlp
141 KeyPgUp string // kpp
142 KeyPgDn string // knp
143 KeyUp string // kcuu1
144 KeyDown string // kcud1
145 KeyLeft string // kcub1
146 KeyRight string // kcuf1
147 KeyBacktab string // kcbt
148 KeyExit string // kext
149 KeyClear string // kclr
150 KeyPrint string // kprt
151 KeyCancel string // kcan
152 Mouse string // kmous
153 MouseMode string // XM
154 AltChars string // acsc
155 EnterAcs string // smacs
156 ExitAcs string // rmacs
157 EnableAcs string // enacs
158 KeyShfRight string // kRIT
159 KeyShfLeft string // kLFT
160 KeyShfHome string // kHOM
161 KeyShfEnd string // kEND
162 KeyShfInsert string // kIC
163 KeyShfDelete string // kDC
164
165 // These are non-standard extensions to terminfo. This includes
166 // true color support, and some additional keys. Its kind of bizarre
167 // that shifted variants of left and right exist, but not up and down.
168 // Terminal support for these are going to vary amongst XTerm
169 // emulations, so don't depend too much on them in your application.
170
171 StrikeThrough string // smxx
172 SetFgBg string // setfgbg
173 SetFgBgRGB string // setfgbgrgb
174 SetFgRGB string // setfrgb
175 SetBgRGB string // setbrgb
176 KeyShfUp string // shift-up
177 KeyShfDown string // shift-down
178 KeyShfPgUp string // shift-kpp
179 KeyShfPgDn string // shift-knp
180 KeyCtrlUp string // ctrl-up
181 KeyCtrlDown string // ctrl-left
182 KeyCtrlRight string // ctrl-right
183 KeyCtrlLeft string // ctrl-left
184 KeyMetaUp string // meta-up
185 KeyMetaDown string // meta-left
186 KeyMetaRight string // meta-right
187 KeyMetaLeft string // meta-left
188 KeyAltUp string // alt-up
189 KeyAltDown string // alt-left
190 KeyAltRight string // alt-right
191 KeyAltLeft string // alt-left
192 KeyCtrlHome string
193 KeyCtrlEnd string
194 KeyMetaHome string
195 KeyMetaEnd string
196 KeyAltHome string
197 KeyAltEnd string
198 KeyAltShfUp string
199 KeyAltShfDown string
200 KeyAltShfLeft string
201 KeyAltShfRight string
202 KeyMetaShfUp string
203 KeyMetaShfDown string
204 KeyMetaShfLeft string
205 KeyMetaShfRight string
206 KeyCtrlShfUp string
207 KeyCtrlShfDown string
208 KeyCtrlShfLeft string
209 KeyCtrlShfRight string
210 KeyCtrlShfHome string
211 KeyCtrlShfEnd string
212 KeyAltShfHome string
213 KeyAltShfEnd string
214 KeyMetaShfHome string
215 KeyMetaShfEnd string
216 Modifiers int
217 TrueColor bool // true if the terminal supports direct color
218 }
219
220 const (
221 ModifiersNone = 0
222 ModifiersXTerm = 1
223 ModifiersDynamic = 2
224 )
225
226 type stackElem struct {
227 s string
228 i int
229 isStr bool
230 isInt bool
231 }
232
233 type stack []stackElem
234
235 func (st stack) Push(v string) stack {
236 e := stackElem{
237 s: v,
238 isStr: true,
239 }
240 return append(st, e)
241 }
242
243 func (st stack) Pop() (string, stack) {
244 v := ""
245 if len(st) > 0 {
246 e := st[len(st)-1]
247 st = st[:len(st)-1]
248 if e.isStr {
249 v = e.s
250 } else {
251 v = strconv.Itoa(e.i)
252 }
253 }
254 return v, st
255 }
256
257 func (st stack) PopInt() (int, stack) {
258 if len(st) > 0 {
259 e := st[len(st)-1]
260 st = st[:len(st)-1]
261 if e.isInt {
262 return e.i, st
263 } else if e.isStr {
264 // If the string that was pushed was the representation
265 // of a number e.g. '123', then return the number. If the
266 // conversion doesn't work, assume the string pushed was
267 // intended to return, as an int, the ascii representation
268 // of the (one and only) character.
269 i, err := strconv.Atoi(e.s)
270 if err == nil {
271 return i, st
272 } else if len(e.s) >= 1 {
273 return int(e.s[0]), st
274 }
275 }
276 }
277 return 0, st
278 }
279
280 func (st stack) PopBool() (bool, stack) {
281 if len(st) > 0 {
282 e := st[len(st)-1]
283 st = st[:len(st)-1]
284 if e.isStr {
285 if e.s == "1" {
286 return true, st
287 }
288 return false, st
289 } else if e.i == 1 {
290 return true, st
291 } else {
292 return false, st
293 }
294 }
295 return false, st
296 }
297
298 func (st stack) PushInt(i int) stack {
299 e := stackElem{
300 i: i,
301 isInt: true,
302 }
303 return append(st, e)
304 }
305
306 func (st stack) PushBool(i bool) stack {
307 if i {
308 return st.PushInt(1)
309 }
310 return st.PushInt(0)
311 }
312
313 // static vars
314 var svars [26]string
315
316 // paramsBuffer handles some persistent state for TParam. Technically we
317 // could probably dispense with this, but caching buffer arrays gives us
318 // a nice little performance boost. Furthermore, we know that TParam is
319 // rarely (never?) called re-entrantly, so we can just reuse the same
320 // buffers, making it thread-safe by stashing a lock.
321 type paramsBuffer struct {
322 out bytes.Buffer
323 buf bytes.Buffer
324 lk sync.Mutex
325 }
326
327 // Start initializes the params buffer with the initial string data.
328 // It also locks the paramsBuffer. The caller must call End() when
329 // finished.
330 func (pb *paramsBuffer) Start(s string) {
331 pb.lk.Lock()
332 pb.out.Reset()
333 pb.buf.Reset()
334 pb.buf.WriteString(s)
335 }
336
337 // End returns the final output from TParam, but it also releases the lock.
338 func (pb *paramsBuffer) End() string {
339 s := pb.out.String()
340 pb.lk.Unlock()
341 return s
342 }
343
344 // NextCh returns the next input character to the expander.
345 func (pb *paramsBuffer) NextCh() (byte, error) {
346 return pb.buf.ReadByte()
347 }
348
349 // PutCh "emits" (rather schedules for output) a single byte character.
350 func (pb *paramsBuffer) PutCh(ch byte) {
351 pb.out.WriteByte(ch)
352 }
353
354 // PutString schedules a string for output.
355 func (pb *paramsBuffer) PutString(s string) {
356 pb.out.WriteString(s)
357 }
358
359 var pb = &paramsBuffer{}
360
361 // TParm takes a terminfo parameterized string, such as setaf or cup, and
362 // evaluates the string, and returns the result with the parameter
363 // applied.
364 func (t *Terminfo) TParm(s string, p ...int) string {
365 var stk stack
366 var a, b string
367 var ai, bi int
368 var ab bool
369 var dvars [26]string
370 var params [9]int
371
372 pb.Start(s)
373
374 // make sure we always have 9 parameters -- makes it easier
375 // later to skip checks
376 for i := 0; i < len(params) && i < len(p); i++ {
377 params[i] = p[i]
378 }
379
380 nest := 0
381
382 for {
383
384 ch, err := pb.NextCh()
385 if err != nil {
386 break
387 }
388
389 if ch != '%' {
390 pb.PutCh(ch)
391 continue
392 }
393
394 ch, err = pb.NextCh()
395 if err != nil {
396 // XXX Error
397 break
398 }
399
400 switch ch {
401 case '%': // quoted %
402 pb.PutCh(ch)
403
404 case 'i': // increment both parameters (ANSI cup support)
405 params[0]++
406 params[1]++
407
408 case 'c', 's':
409 // NB: these, and 'd' below are special cased for
410 // efficiency. They could be handled by the richer
411 // format support below, less efficiently.
412 a, stk = stk.Pop()
413 pb.PutString(a)
414
415 case 'd':
416 ai, stk = stk.PopInt()
417 pb.PutString(strconv.Itoa(ai))
418
419 case '0', '1', '2', '3', '4', 'x', 'X', 'o', ':':
420 // This is pretty suboptimal, but this is rarely used.
421 // None of the mainstream terminals use any of this,
422 // and it would surprise me if this code is ever
423 // executed outside of test cases.
424 f := "%"
425 if ch == ':' {
426 ch, _ = pb.NextCh()
427 }
428 f += string(ch)
429 for ch == '+' || ch == '-' || ch == '#' || ch == ' ' {
430 ch, _ = pb.NextCh()
431 f += string(ch)
432 }
433 for (ch >= '0' && ch <= '9') || ch == '.' {
434 ch, _ = pb.NextCh()
435 f += string(ch)
436 }
437 switch ch {
438 case 'd', 'x', 'X', 'o':
439 ai, stk = stk.PopInt()
440 pb.PutString(fmt.Sprintf(f, ai))
441 case 'c', 's':
442 a, stk = stk.Pop()
443 pb.PutString(fmt.Sprintf(f, a))
444 }
445
446 case 'p': // push parameter
447 ch, _ = pb.NextCh()
448 ai = int(ch - '1')
449 if ai >= 0 && ai < len(params) {
450 stk = stk.PushInt(params[ai])
451 } else {
452 stk = stk.PushInt(0)
453 }
454
455 case 'P': // pop & store variable
456 ch, _ = pb.NextCh()
457 if ch >= 'A' && ch <= 'Z' {
458 svars[int(ch-'A')], stk = stk.Pop()
459 } else if ch >= 'a' && ch <= 'z' {
460 dvars[int(ch-'a')], stk = stk.Pop()
461 }
462
463 case 'g': // recall & push variable
464 ch, _ = pb.NextCh()
465 if ch >= 'A' && ch <= 'Z' {
466 stk = stk.Push(svars[int(ch-'A')])
467 } else if ch >= 'a' && ch <= 'z' {
468 stk = stk.Push(dvars[int(ch-'a')])
469 }
470
471 case '\'': // push(char)
472 ch, _ = pb.NextCh()
473 pb.NextCh() // must be ' but we don't check
474 stk = stk.Push(string(ch))
475
476 case '{': // push(int)
477 ai = 0
478 ch, _ = pb.NextCh()
479 for ch >= '0' && ch <= '9' {
480 ai *= 10
481 ai += int(ch - '0')
482 ch, _ = pb.NextCh()
483 }
484 // ch must be '}' but no verification
485 stk = stk.PushInt(ai)
486
487 case 'l': // push(strlen(pop))
488 a, stk = stk.Pop()
489 stk = stk.PushInt(len(a))
490
491 case '+':
492 bi, stk = stk.PopInt()
493 ai, stk = stk.PopInt()
494 stk = stk.PushInt(ai + bi)
495
496 case '-':
497 bi, stk = stk.PopInt()
498 ai, stk = stk.PopInt()
499 stk = stk.PushInt(ai - bi)
500
501 case '*':
502 bi, stk = stk.PopInt()
503 ai, stk = stk.PopInt()
504 stk = stk.PushInt(ai * bi)
505
506 case '/':
507 bi, stk = stk.PopInt()
508 ai, stk = stk.PopInt()
509 if bi != 0 {
510 stk = stk.PushInt(ai / bi)
511 } else {
512 stk = stk.PushInt(0)
513 }
514
515 case 'm': // push(pop mod pop)
516 bi, stk = stk.PopInt()
517 ai, stk = stk.PopInt()
518 if bi != 0 {
519 stk = stk.PushInt(ai % bi)
520 } else {
521 stk = stk.PushInt(0)
522 }
523
524 case '&': // AND
525 bi, stk = stk.PopInt()
526 ai, stk = stk.PopInt()
527 stk = stk.PushInt(ai & bi)
528
529 case '|': // OR
530 bi, stk = stk.PopInt()
531 ai, stk = stk.PopInt()
532 stk = stk.PushInt(ai | bi)
533
534 case '^': // XOR
535 bi, stk = stk.PopInt()
536 ai, stk = stk.PopInt()
537 stk = stk.PushInt(ai ^ bi)
538
539 case '~': // bit complement
540 ai, stk = stk.PopInt()
541 stk = stk.PushInt(ai ^ -1)
542
543 case '!': // logical NOT
544 ai, stk = stk.PopInt()
545 stk = stk.PushBool(ai != 0)
546
547 case '=': // numeric compare or string compare
548 b, stk = stk.Pop()
549 a, stk = stk.Pop()
550 stk = stk.PushBool(a == b)
551
552 case '>': // greater than, numeric
553 bi, stk = stk.PopInt()
554 ai, stk = stk.PopInt()
555 stk = stk.PushBool(ai > bi)
556
557 case '<': // less than, numeric
558 bi, stk = stk.PopInt()
559 ai, stk = stk.PopInt()
560 stk = stk.PushBool(ai < bi)
561
562 case '?': // start conditional
563
564 case 't':
565 ab, stk = stk.PopBool()
566 if ab {
567 // just keep going
568 break
569 }
570 nest = 0
571 ifloop:
572 // this loop consumes everything until we hit our else,
573 // or the end of the conditional
574 for {
575 ch, err = pb.NextCh()
576 if err != nil {
577 break
578 }
579 if ch != '%' {
580 continue
581 }
582 ch, _ = pb.NextCh()
583 switch ch {
584 case ';':
585 if nest == 0 {
586 break ifloop
587 }
588 nest--
589 case '?':
590 nest++
591 case 'e':
592 if nest == 0 {
593 break ifloop
594 }
595 }
596 }
597
598 case 'e':
599 // if we got here, it means we didn't use the else
600 // in the 't' case above, and we should skip until
601 // the end of the conditional
602 nest = 0
603 elloop:
604 for {
605 ch, err = pb.NextCh()
606 if err != nil {
607 break
608 }
609 if ch != '%' {
610 continue
611 }
612 ch, _ = pb.NextCh()
613 switch ch {
614 case ';':
615 if nest == 0 {
616 break elloop
617 }
618 nest--
619 case '?':
620 nest++
621 }
622 }
623
624 case ';': // endif
625
626 }
627 }
628
629 return pb.End()
630 }
631
632 // TPuts emits the string to the writer, but expands inline padding
633 // indications (of the form $<[delay]> where [delay] is msec) to
634 // a suitable time (unless the terminfo string indicates this isn't needed
635 // by specifying npc - no padding). All Terminfo based strings should be
636 // emitted using this function.
637 func (t *Terminfo) TPuts(w io.Writer, s string) {
638 for {
639 beg := strings.Index(s, "$<")
640 if beg < 0 {
641 // Most strings don't need padding, which is good news!
642 io.WriteString(w, s)
643 return
644 }
645 io.WriteString(w, s[:beg])
646 s = s[beg+2:]
647 end := strings.Index(s, ">")
648 if end < 0 {
649 // unterminated.. just emit bytes unadulterated
650 io.WriteString(w, "$<"+s)
651 return
652 }
653 val := s[:end]
654 s = s[end+1:]
655 padus := 0
656 unit := time.Millisecond
657 dot := false
658 loop:
659 for i := range val {
660 switch val[i] {
661 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
662 padus *= 10
663 padus += int(val[i] - '0')
664 if dot {
665 unit /= 10
666 }
667 case '.':
668 if !dot {
669 dot = true
670 } else {
671 break loop
672 }
673 default:
674 break loop
675 }
676 }
677
678 // Curses historically uses padding to achieve "fine grained"
679 // delays. We have much better clocks these days, and so we
680 // do not rely on padding but simply sleep a bit.
681 if len(t.PadChar) > 0 {
682 time.Sleep(unit * time.Duration(padus))
683 }
684 }
685 }
686
687 // TGoto returns a string suitable for addressing the cursor at the given
688 // row and column. The origin 0, 0 is in the upper left corner of the screen.
689 func (t *Terminfo) TGoto(col, row int) string {
690 return t.TParm(t.SetCursor, row, col)
691 }
692
693 // TColor returns a string corresponding to the given foreground and background
694 // colors. Either fg or bg can be set to -1 to elide.
695 func (t *Terminfo) TColor(fi, bi int) string {
696 rv := ""
697 // As a special case, we map bright colors to lower versions if the
698 // color table only holds 8. For the remaining 240 colors, the user
699 // is out of luck. Someday we could create a mapping table, but its
700 // not worth it.
701 if t.Colors == 8 {
702 if fi > 7 && fi < 16 {
703 fi -= 8
704 }
705 if bi > 7 && bi < 16 {
706 bi -= 8
707 }
708 }
709 if t.Colors > fi && fi >= 0 {
710 rv += t.TParm(t.SetFg, fi)
711 }
712 if t.Colors > bi && bi >= 0 {
713 rv += t.TParm(t.SetBg, bi)
714 }
715 return rv
716 }
717
718 var (
719 dblock sync.Mutex
720 terminfos = make(map[string]*Terminfo)
721 aliases = make(map[string]string)
722 )
723
724 // AddTerminfo can be called to register a new Terminfo entry.
725 func AddTerminfo(t *Terminfo) {
726 dblock.Lock()
727 terminfos[t.Name] = t
728 for _, x := range t.Aliases {
729 terminfos[x] = t
730 }
731 dblock.Unlock()
732 }
733
734 // LookupTerminfo attempts to find a definition for the named $TERM.
735 func LookupTerminfo(name string) (*Terminfo, error) {
736 if name == "" {
737 // else on windows: index out of bounds
738 // on the name[0] reference below
739 return nil, ErrTermNotFound
740 }
741
742 addtruecolor := false
743 switch os.Getenv("COLORTERM") {
744 case "truecolor", "24bit", "24-bit":
745 addtruecolor = true
746 }
747 dblock.Lock()
748 t := terminfos[name]
749 dblock.Unlock()
750
751 // If the name ends in -truecolor, then fabricate an entry
752 // from the corresponding -256color, -color, or bare terminal.
753 if t != nil && t.TrueColor {
754 addtruecolor = true
755 } else if t == nil && strings.HasSuffix(name, "-truecolor") {
756
757 suffixes := []string{
758 "-256color",
759 "-88color",
760 "-color",
761 "",
762 }
763 base := name[:len(name)-len("-truecolor")]
764 for _, s := range suffixes {
765 if t, _ = LookupTerminfo(base + s); t != nil {
766 addtruecolor = true
767 break
768 }
769 }
770 }
771
772 if t == nil {
773 return nil, ErrTermNotFound
774 }
775
776 switch os.Getenv("TCELL_TRUECOLOR") {
777 case "":
778 case "disable":
779 addtruecolor = false
780 default:
781 addtruecolor = true
782 }
783
784 // If the user has requested 24-bit color with $COLORTERM, then
785 // amend the value (unless already present). This means we don't
786 // need to have a value present.
787 if addtruecolor &&
788 t.SetFgBgRGB == "" &&
789 t.SetFgRGB == "" &&
790 t.SetBgRGB == "" {
791
792 // Supply vanilla ISO 8613-6:1994 24-bit color sequences.
793 t.SetFgRGB = "\x1b[38;2;%p1%d;%p2%d;%p3%dm"
794 t.SetBgRGB = "\x1b[48;2;%p1%d;%p2%d;%p3%dm"
795 t.SetFgBgRGB = "\x1b[38;2;%p1%d;%p2%d;%p3%d;" +
796 "48;2;%p4%d;%p5%d;%p6%dm"
797 }
798
799 return t, nil
800 }