Repository navigation
Expand file tree
/
Copy pathtscreen.go
More file actions
2005 lines (1805 loc) · 49.7 KB
/
Copy pathtscreen.go
File metadata and controls
2005 lines (1805 loc) · 49.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2026 The TCell Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build (!js && !wasm) || (js && wasm)
// +build !js,!wasm js,wasm
package tcell
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"maps"
"os"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
gencoding "github.com/gdamore/encoding"
"github.com/gdamore/tcell/v3/color"
"github.com/gdamore/tcell/v3/vt"
"golang.org/x/text/encoding"
"golang.org/x/text/transform"
)
// NewTerminfoScreen returns a Screen that uses the stock TTY interface
// and POSIX terminal control, combined with a terminfo description taken from
// the $TERM environment variable. It returns an error if the terminal
// is not supported for any reason.
//
// For terminals that do not support dynamic resize events, the $LINES
// $COLUMNS environment variables can be set to the actual window size,
// otherwise defaults taken from the terminal database are used.
func NewTerminfoScreen(opts ...TerminfoScreenOption) (Screen, error) {
return NewTerminfoScreenFromTty(nil, opts...)
}
type TerminfoScreenOption interface {
apply(*tScreen)
}
// OptColors forces the number of colors, overriding the value
// of the color count that would be detected by the environment.
// If the value is 0, then color is forced off. Other reasonable values
// are 8, 16, 88, 256, or 1<<24. The latter case intrinsically enables
// 24-bit color as well.
type OptColors int
func (o OptColors) apply(t *tScreen) {
t.ncolor = min(int(o), 256)
t.truecolor = o > 256
t.noColor = o == 0
}
// OptTerm overrides the detection of $TERM.
type OptTerm string
func (o OptTerm) apply(t *tScreen) {
t.term = string(o)
}
// OptAltScreen controls whether the alternate screen buffer is used.
// The default is true. The TCELL_ALTSCREEN=disable environment override
// is still honored.
type OptAltScreen bool
func (o OptAltScreen) apply(t *tScreen) {
t.altScreen = bool(o)
}
// OptSanitizeContent enables stripping control characters from content passed
// to Put and PutStr. This is safer, but a little slower than leaving content
// unsanitized.
type OptSanitizeContent bool
func (o OptSanitizeContent) apply(t *tScreen) {
t.cells.sanitizeContent = bool(o)
}
// OptAdvancedKeys enables richer key reporting where supported. In this mode
// key events may include release state, repeat counts, and physical keys, and
// ASCII control letters are reported as KeyRune with ModCtrl instead of
// KeyCtrlA through KeyCtrlZ. Shift-Tab is reported as KeyTab with ModShift,
// rather than KeyBacktab.
type OptAdvancedKeys bool
func (o OptAdvancedKeys) apply(t *tScreen) {
t.advancedKeys = bool(o)
}
// OptKeyboardProtocol forces the keyboard reporting protocol instead of using
// startup negotiation. The zero value forces legacy keyboard reporting.
type OptKeyboardProtocol KeyProtocol
func (o OptKeyboardProtocol) apply(t *tScreen) {
t.forceKeyboardProtocol(KeyProtocol(o))
}
// OptNegotiation controls whether terminal capabilities are negotiated during
// startup. The default is true.
type OptNegotiation bool
func (o OptNegotiation) apply(t *tScreen) {
t.negotiate = bool(o)
}
// OptEscapeTimeout sets how long the input parser waits for bytes that may
// follow an Escape. The default is 50 ms, or 125 ms on Windows. Increasing
// this can accommodate terminals that split escape sequences across delayed
// reads, at the cost of delaying a standalone Escape by the same amount. A
// positive TCELL_ESCDELAY environment variable, expressed in milliseconds,
// overrides this setting. Values less than or equal to zero use the default.
type OptEscapeTimeout time.Duration
func (o OptEscapeTimeout) apply(t *tScreen) {
if o > 0 {
t.escapeTimeout = time.Duration(o)
}
}
// OptControlStringLimit sets the maximum inbound control-string payload size
// accepted from the terminal before the parser drops the sequence. This limits
// OSC and XDA strings, including OSC 52 clipboard strings; OSC 52 is the
// protocol used for writing clipboard data through the terminal. The default is
// 64 KiB; a value of 0 disables the limit.
type OptControlStringLimit int
func (o OptControlStringLimit) apply(t *tScreen) {
t.controlStringLimit = max(int(o), 0)
}
// Some terminal escapes that are basically universal.
// Final bytes and parameters for the CSI sequences that csi builds.
const (
csiSGR = 'm' // select graphic rendition
csiCUP = 'H' // cursor position: row, column (1-based)
sgrFg8 = 30 // plus a color below 8
sgrBg8 = 40 // plus a color below 8
sgrFgExt = 38 // extended foreground, followed by sgrColor256 or sgrColorRGB
sgrBgExt = 48 // extended background, followed by sgrColor256 or sgrColorRGB
sgrColor256 = 5 // followed by a palette index
sgrColorRGB = 2 // followed by red, green, blue
)
// We would really like to be able to use private mode queries for some of
// these but generally we've found that support for queries is not always present,
// even when the private modes can be controlled. It appears that *all* terminals
// will happily swallow the escapes that they do not recognize, with the small annoyance
// in "st" where it prints error messages to its stderr (which is usually not visible
// to the user unless they started it from another terminal session). But apart from
// the complaint to stderr from "st", everything else is fine.
const (
enableAutoMargin = "\x1b[?7h" // dec private mode 7
setCursorPosition = "\x1b[%[1]d;%[2]dH"
sgr0 = "\x1b[m" // attrOff
bold = "\x1b[1m"
dim = "\x1b[2m"
italic = "\x1b[3m"
underline = "\x1b[4m"
blink = "\x1b[5m"
reverse = "\x1b[7m"
strikeThrough = "\x1b[9m"
clear = "\x1b[H\x1b[J"
doubleUnder = "\x1b[4:2m"
curlyUnder = "\x1b[4:3m"
dottedUnder = "\x1b[4:4m"
dashedUnder = "\x1b[4:5m"
underColor = "\x1b[58:5:%dm"
underRGB = "\x1b[58:2::%d:%d:%dm"
underFg = "\x1b[59m"
enableAltChars = "\x1b(B\x1b)0" // set G0 as US-ASCII, G1 as DEC line drawing
startAltChars = "\x0e" // aka Shift-Out
endAltChars = "\x0f" // aka Shift-In
enterCA = "\x1b[?1049h" // alternate screen
exitCA = "\x1b[?1049l" // alternate screen
enterKeypad = "\x1b[?1h\x1b=" // Note mode 1 might not be supported everywhere
exitKeypad = "\x1b[?1l\x1b>" // Also mode 1
requestWindowSize = "\x1b[18t" // For modern terminals
requestPixelSize = "\x1b[14t" // Text area in pixels, for when the tty does not know it
requestPrimaryDA = "\x1b[c" // Request primary device attributes
requestExtAttr = "\x1b[>q" // Request extended attribute (emulator name and version)
setClipboard = "\x1b]52;c;%s\x1b\\" // Clipboard content is base64
notifyDesktop9 = "\x1b]9;%[2]s\x1b\\" // Args are title, body (but OSC 9 only has body)
notifyDesktop777 = "\x1b]777;notify;%s;%s\x1b\\" // Most commonly supported
queryKittyKbd = "\x1b[?u" // Query for Kitty keyboard support
enableKittyKbd = "\x1b[=1u" // Technically this pushes
enableKittyKbdAdv = "\x1b[=31u" // disambiguation, events, alternate keys, all keys, text
disableKittyKbd = "\x1b[=0u" // Technically this means pop previous mode
queryXTermKbd = "\x1b[?4m" // Query for XTerm modify other keys support
enableXTermKbd = "\x1b[>4;2m" // Enable modify other keys protocol
disableXTermKbd = "\x1b[>4;0m" // Disable modify other keys protocol
)
// NewTerminfoScreenFromTty returns a Screen using a custom Tty implementation.
// If the passed in tty is nil, then a reasonable default (typically /dev/tty)
// is presumed, at least on UNIX hosts. (Windows hosts will typically fail this
// call altogether.)
func NewTerminfoScreenFromTty(tty Tty, opts ...TerminfoScreenOption) (Screen, error) {
t := &tScreen{
tty: tty,
altScreen: true,
negotiate: true,
controlStringLimit: defaultControlStringLimit,
escapeTimeout: platformEscapeTimeout(),
}
t.prepareCursorStyles()
t.prepareExtendedOSC()
t.buildAcsMap()
t.resizeQ = make(chan bool, 1)
t.fallback = make(map[rune]string)
maps.Copy(t.fallback, RuneFallbacks)
for _, o := range opts {
o.apply(t)
}
return &baseScreen{screenImpl: t}, nil
}
// tScreen represents a screen backed by a terminfo implementation.
type tScreen struct {
tty Tty
h int
w int
fini bool
cells CellBuffer
buffering bool // true if we are collecting writes to buf instead of sending directly to out
buf bytes.Buffer
curstyle Style
style Style
resizeQ chan bool
quit chan struct{}
keyQ chan []byte
cx int
cy int
cls bool // clear screen
cursorx int
cursory int
acs map[rune]string
charset string
encoder transform.Transformer // nil for UTF-8
asciiSuperset bool // the encoder passes ASCII through unchanged
decoder transform.Transformer
fallback map[rune]string
ncolor int
colors map[color.Color]color.Color
palette []color.Color
truecolor bool
noColor bool
legacy bool
hasClipboard bool // true if OSC 52 reported via DA1
finiOnce sync.Once
initFiniLock sync.Mutex
enterUrl string
exitUrl string
setWinSize string
cursorStyles map[CursorStyle]string
cursorStyle CursorStyle
cursorColor color.Color
cursorRGB string
cursorFg string
stopQ chan struct{}
eventQ chan Event
initQ chan Event
initted bool
running bool
startTime time.Time
wg sync.WaitGroup
eventWg sync.WaitGroup
mouseFlags MouseFlags
consoleMouse consoleMouse
pasteEnabled bool
focusEnabled bool
setTitle string
saveTitle string
restoreTitle string
title string
setClipboard string
notifyDesktop string
termName string
termVers string
term string // value from $TERM
altScreen bool
inlineResize bool
haveMouse bool
haveMouseSgr bool
haveKittyKbd bool
haveWin32Kbd bool
haveXTermKbd bool
forcedKbd KeyProtocol
forceKbd bool
negotiate bool
mouseDisabled bool
advancedKeys bool
controlStringLimit int
escapeTimeout time.Duration
input *inputParser
compat struct {
mouseUnsupported bool
mousePixelUnsupported bool
focusUnsupported bool
clipboardReadUnsupported bool
}
sync.Mutex
}
func (t *tScreen) useAltScreen() bool {
return t.altScreen && os.Getenv("TCELL_ALTSCREEN") != "disable"
}
func validKeyboardProtocol(p KeyProtocol) bool {
switch p {
case LegacyKeyboard, KittyKeyboard, Win32Keyboard, XTermKeyboard:
return true
default:
return false
}
}
func parseKeyboardProtocol(s string) (KeyProtocol, bool) {
switch s {
case "legacy":
return LegacyKeyboard, true
case "kitty":
return KittyKeyboard, true
case "win32":
return Win32Keyboard, true
case "xterm":
return XTermKeyboard, true
default:
return LegacyKeyboard, false
}
}
func (t *tScreen) forceKeyboardProtocol(p KeyProtocol) bool {
if !validKeyboardProtocol(p) {
return false
}
t.forcedKbd = p
t.forceKbd = true
return true
}
func (t *tScreen) applyKeyboardProtocolOverride() {
if !t.forceKbd {
return
}
t.haveKittyKbd = t.forcedKbd == KittyKeyboard
t.haveWin32Kbd = t.forcedKbd == Win32Keyboard
t.haveXTermKbd = t.forcedKbd == XTermKeyboard
}
func (t *tScreen) applyEnvironmentOverrides() {
if delay, err := strconv.Atoi(os.Getenv("TCELL_ESCDELAY")); err == nil && delay > 0 {
t.escapeTimeout = time.Duration(delay) * time.Millisecond
}
switch os.Getenv("TCELL_KEYBOARD_PROTOCOL") {
case "auto":
t.forceKbd = false
case "":
default:
if p, ok := parseKeyboardProtocol(os.Getenv("TCELL_KEYBOARD_PROTOCOL")); ok {
t.forceKeyboardProtocol(p)
}
}
switch os.Getenv("TCELL_NEGOTIATE") {
case "auto":
t.negotiate = true
case "disable":
t.negotiate = false
}
t.mouseDisabled = os.Getenv("TCELL_MOUSE") == "disable"
}
func (t *tScreen) Init() error {
t.initFiniLock.Lock()
defer t.initFiniLock.Unlock()
t.Lock()
if t.fini {
t.Unlock()
return errors.New("screen finalized")
}
if t.running {
t.Unlock()
return errors.New("already initialized")
}
t.Unlock()
if e := t.initialize(); e != nil {
return e
}
t.startTime = time.Now()
t.keyQ = make(chan []byte, 10)
t.charset = getCharset()
if enc := GetEncoding(t.charset); enc != nil {
// UTF-8 needs no encoder; drawCell writes valid UTF-8 as is.
if enc != gencoding.UTF8 && enc != encoding.Nop {
t.encoder = enc.NewEncoder()
t.asciiSuperset = isASCIISuperset(enc)
}
t.decoder = enc.NewDecoder()
} else {
return ErrNoCharset
}
// environment overrides
w := 80
h := 24
if i, _ := strconv.Atoi(os.Getenv("LINES")); i != 0 {
h = i
}
if i, _ := strconv.Atoi(os.Getenv("COLUMNS")); i != 0 {
w = i
}
if t.term == "" {
t.term = os.Getenv("TERM")
}
nterm := t.term
if t.ncolor == 0 && !t.noColor {
cterm := os.Getenv("COLORTERM")
// On Windows, enable 24-bit color by default (all terminals there are 24-bit capable)
if runtime.GOOS == "windows" {
t.truecolor = true
t.ncolor = 256
} else if slices.Contains([]string{"truecolor", "direct", "24bit"}, cterm) || strings.HasSuffix(nterm, "-direct") || strings.HasSuffix(nterm, "-truecolor") {
t.truecolor = true
t.ncolor = 256 // base 8-bit palette
} else if strings.HasSuffix(nterm, "-256color") || strings.Contains(cterm, "256") {
t.ncolor = 256
} else if strings.HasSuffix(nterm, "-88color") {
t.ncolor = 88
} else if strings.HasSuffix(nterm, "-16color") {
t.ncolor = 16
} else if strings.Contains(nterm, "color") || cterm != "" {
t.ncolor = 8
} else if strings.Contains(nterm, "mono") || strings.HasSuffix(nterm, "-m") { // monochrome variants
t.ncolor = 0
} else if strings.Contains(nterm, "ansi") || slices.Contains([]string{"dtterm", "xterm", "aixterm", "linux"}, nterm) {
t.ncolor = 8
} else if strings.HasPrefix(nterm, "vt") || nterm == "sun" {
// legacy DEC VT 100/220 etc. family. (technically the VT525 can do ANSI, but they should set to ansi)
t.ncolor = 0
} else {
// best guess - this covers all the modern variants like ghostty,
t.ncolor = 256
}
if os.Getenv("NO_COLOR") != "" {
t.truecolor = false
t.ncolor = 0
t.noColor = true
}
// A user who wants to have his themes honored can set this environment variable.
if os.Getenv("TCELL_TRUECOLOR") == "disable" {
t.truecolor = false
}
}
if strings.HasPrefix(nterm, "vt") || strings.Contains(nterm, "ansi") || nterm == "linux" || nterm == "sun" || nterm == "sun-color" {
// these terminals are "legacy" and not expected to support most OSC functions
t.legacy = true
}
t.applyEnvironmentOverrides()
t.initted = false
t.quit = make(chan struct{})
t.initQ = make(chan Event, 32)
t.eventQ = make(chan Event, 128)
t.input = newInputParser(t.filterEvents())
t.input.advanced = t.advancedKeys
t.input.controlStringMax = t.controlStringLimit
t.input.SetEscapeTimeout(t.escapeTimeout)
t.Lock()
t.cx = -1
t.cy = -1
t.style = StyleDefault
t.cells.Resize(w, h)
t.cursorx = -1
t.cursory = -1
t.resize()
t.Unlock()
if err := t.engage(); err != nil {
return err
}
// clip to reasonable limits
nColors := min(t.ncolor, 256)
t.colors = make(map[color.Color]color.Color, nColors)
t.palette = make([]color.Color, nColors)
for i := range nColors {
t.palette[i] = color.PaletteColor(i)
// identity map for our builtin colors
t.colors[color.PaletteColor(i)] = color.PaletteColor(i)
}
return nil
}
func (t *tScreen) processInitQ() {
// NB: called with lock held
if t.initted {
return
}
expire := time.After(time.Second)
for {
select {
case <-expire:
t.initted = true
return
case ev := <-t.initQ:
switch ev := ev.(type) {
case *eventPrimaryAttributes:
if ev.Color && t.ncolor == 0 && !t.noColor {
t.ncolor = 8
}
if ev.Clipboard && t.setClipboard == "" {
t.setClipboard = setClipboard
}
t.hasClipboard = ev.Clipboard
t.initted = true
return
case *eventTermName:
// terminal specific overrides
t.termName = ev.Name
t.termVers = ev.Version
switch ev.Name {
case "iTerm2":
// Some terminals can use OSC 9. Unfortunately we can only discover
// them using this means. It appears that pretty much all of them
// except iTerm2 also support more standard OSC 777, and it seems like
// only Kitty has its OSC 99 thing, but it also does OSC 777 well.
t.notifyDesktop = notifyDesktop9
}
case *eventPrivateMode:
switch ev.Mode {
case vt.PmResizeReports:
t.inlineResize = ev.Status.Changeable()
case vt.PmMouseSgr:
t.haveMouseSgr = ev.Status.Changeable()
case vt.PmMouseButton:
t.haveMouse = ev.Status.Changeable()
case vt.PmWin32Input:
t.haveWin32Kbd = ev.Status.Changeable()
}
case *eventKittyKbdMode:
t.haveKittyKbd = true
case *eventXTermKbdMode:
t.haveXTermKbd = true
}
}
}
}
func (t *tScreen) filterEvents() chan Event {
inQ := make(chan Event, 128)
t.eventWg.Add(1)
go func() {
defer t.eventWg.Done()
for {
var ev Event
select {
case ev = <-inQ:
case <-t.quit:
return
}
switch ev.(type) {
case *eventTermName, *eventPrimaryAttributes, *eventPrivateMode, *eventKittyKbdMode, *eventXTermKbdMode:
select {
case t.initQ <- ev:
default:
}
default:
select {
case t.eventQ <- ev:
case <-t.quit:
return
}
}
}
}()
return inQ
}
func (t *tScreen) prepareExtendedOSC() {
if t.legacy {
return
}
// OSC 8 is for enter/exit URL.
t.enterUrl = "\x1b]8;%[2]s;%[1]s\x1b\\"
t.exitUrl = "\x1b]8;;\x1b\\"
// CSI .. t is for window operations.
t.setWinSize = "\x1b[8;%[2]d;%[1]dt"
t.saveTitle = "\x1b[22;2t"
t.restoreTitle = "\x1b[23;2t"
// this also tries to request that UTF-8 is allowed in the title
t.setTitle = "\x1b[>2t\x1b]2;%s\x1b\\"
// OSC 52 is for saving to the clipboard.
// this string takes a base64 string and sends it to the clipboard.
// it will also be able to retrieve the clipboard using "?" as the
// sent string, when we support that.
t.setClipboard = setClipboard
// OSC 777 is the desktop notification supported by a variety of
// newer terminals. (There was also OSC 9 and OSC 99, but they
// are not as widely deployed, and OSC 9 is not unique.)
t.notifyDesktop = notifyDesktop777
}
func (t *tScreen) prepareCursorStyles() {
t.cursorStyles = map[CursorStyle]string{
CursorStyleDefault: "\x1b[0 q",
CursorStyleBlinkingBlock: "\x1b[1 q",
CursorStyleSteadyBlock: "\x1b[2 q",
CursorStyleBlinkingUnderline: "\x1b[3 q",
CursorStyleSteadyUnderline: "\x1b[4 q",
CursorStyleBlinkingBar: "\x1b[5 q",
CursorStyleSteadyBar: "\x1b[6 q",
}
if t.legacy {
return
}
if t.cursorRGB == "" {
t.cursorRGB = "\x1b]12;#%02x%02x%02x\007"
t.cursorFg = "\x1b]112\007"
}
}
func (t *tScreen) Fini() {
t.initFiniLock.Lock()
defer t.initFiniLock.Unlock()
// Ensure that enough time passes for terminals to finish sending
// their initial response (gnome-terminal sends terminal dimensions
// asynchronously later than the response to primary DA for some reason.)
if time.Since(t.startTime) < 50*time.Millisecond {
time.Sleep(time.Millisecond * 50)
}
t.finiOnce.Do(t.finish)
}
func (t *tScreen) finish() {
t.Lock()
t.fini = true
t.Unlock()
close(t.quit)
t.finalize()
}
func (t *tScreen) SetStyle(style Style) {
t.Lock()
if !t.fini {
t.style = style
}
t.Unlock()
}
func (t *tScreen) encodeStr(s string) []byte {
var dstBuf [128]byte
var buf []byte
nb := dstBuf[:]
dst := 0
var err error
if enc := t.encoder; enc != nil {
enc.Reset()
dst, _, err = enc.Transform(nb, []byte(s), true)
}
if err != nil || dst == 0 || nb[0] == '\x1a' {
// Combining characters are elided
r, _ := utf8.DecodeRuneInString(s)
if len(buf) == 0 {
if acs, ok := t.acs[r]; ok {
buf = append(buf, []byte(acs)...)
} else if fb, ok := t.fallback[r]; ok {
buf = append(buf, []byte(fb)...)
} else {
buf = append(buf, '?')
}
}
} else {
buf = append(buf, nb[:dst]...)
}
return buf
}
// isASCIISuperset reports whether enc encodes the 7-bit ASCII range as
// itself, as ISO 8859, KOI8 and most other encodings do (EBCDIC does not).
func isASCIISuperset(enc encoding.Encoding) bool {
ascii := make([]byte, utf8.RuneSelf)
for i := range ascii {
ascii[i] = byte(i)
}
out, err := enc.NewEncoder().Bytes(ascii)
return err == nil && bytes.Equal(out, ascii)
}
func isASCII(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] >= utf8.RuneSelf {
return false
}
}
return true
}
// resolvePalette looks up a color to obtain the palette entry for it.
func (t *tScreen) resolvePalette(c Color) Color {
if v, ok := t.colors[c]; ok {
return v
}
v := color.Find(c, t.palette)
t.colors[c] = v
return v
}
// sendFgBg sends the foreground and background. It is assumed that sgr0
// was already emitted prior to calling this (so colors are already in default).
func (t *tScreen) sendFgBg(fg Color, bg Color, attr AttrMask) AttrMask {
if t.Colors() == 0 {
// foreground vs background, we calculate luminance
// and possibly do a reverse video
if !fg.Valid() {
return attr
}
v, ok := t.colors[fg]
if !ok {
v = color.Find(fg, []Color{ColorBlack, ColorWhite})
t.colors[fg] = v
}
switch v {
case ColorWhite:
return attr
case ColorBlack:
return attr ^ AttrReverse
}
}
if t.truecolor {
if fg.IsRGB() && bg.IsRGB() {
r1, g1, b1 := fg.RGB()
r2, g2, b2 := bg.RGB()
t.csi(csiSGR, sgrFgExt, sgrColorRGB, int(r1), int(g1), int(b1), sgrBgExt, sgrColorRGB, int(r2), int(g2), int(b2))
return attr
}
if fg.IsRGB() {
r, g, b := fg.RGB()
t.csi(csiSGR, sgrFgExt, sgrColorRGB, int(r), int(g), int(b))
fg = ColorDefault
}
if bg.IsRGB() {
r, g, b := bg.RGB()
t.csi(csiSGR, sgrBgExt, sgrColorRGB, int(r), int(g), int(b))
bg = ColorDefault
}
}
if fg.Valid() {
fg = t.resolvePalette(fg)
fgc := fg & 0xffffff
if fgc < 8 {
t.csi(csiSGR, sgrFg8+int(fgc))
} else if fgc < 256 {
t.csi(csiSGR, sgrFgExt, sgrColor256, int(fgc))
}
}
if bg.Valid() {
bg = t.resolvePalette(bg)
bgc := bg & 0xffffff
if bgc < 8 {
t.csi(csiSGR, sgrBg8+int(bgc))
} else if bgc < 256 {
t.csi(csiSGR, sgrBgExt, sgrColor256, int(bgc))
}
}
return attr
}
// emitAttrs dumps prints the attributes, aside from underline that is special
// The assumption is that sgr0 was already printed ahead of this.
func (t *tScreen) emitAttrs(attrs AttrMask) {
if attrs&AttrBold != 0 {
t.Print(bold)
}
if attrs&AttrReverse != 0 {
t.Print(reverse)
}
if attrs&AttrBlink != 0 {
t.Print(blink)
}
if attrs&AttrDim != 0 {
t.Print(dim)
}
if attrs&AttrItalic != 0 {
t.Print(italic)
}
if attrs&AttrStrikeThrough != 0 {
t.Print(strikeThrough)
}
}
// emitUl dumps prints the underline, which may be colored.
// The assumption is that sgr0 was already printed ahead of this.
func (t *tScreen) emitUnderline(us UnderlineStyle, uc Color) {
if us != UnderlineStyleNone {
if t.legacy {
t.Print(underline)
return
}
// NB: under color should have been reset by sgr0
if uc.IsRGB() {
r, g, b := uc.RGB()
uc = t.resolvePalette(uc)
t.Printf(underColor, uc&0xff)
t.Printf(underRGB, r, g, b)
} else if uc.Valid() {
t.Printf(underColor, uc&0xff)
}
t.Print(underline) // to ensure everyone gets at least a basic underline
switch us {
case UnderlineStyleDouble:
t.Print(doubleUnder)
case UnderlineStyleCurly:
t.Print(curlyUnder)
case UnderlineStyleDotted:
t.Print(dottedUnder)
case UnderlineStyleDashed:
t.Print(dashedUnder)
}
}
}
// emitUrl either emits a url (OSC 8), or if the string is empty
// then the OSC 8 to exit the URL. It should only be called if we
// either have a new URL, or need to exit an old one, as it always emits
// the OSC 8 sequence (if OSC 8 is supported).
func (t *tScreen) emitUrl(u urlInfo) {
if t.enterUrl != "" {
if u.url != "" {
t.Printf(t.enterUrl, u.url, u.id)
} else {
t.Print(t.exitUrl)
}
}
}
// urlNeedsEmission reports whether a hyperlink transition has any wire effect.
// Url ids can be staged before the Url itself, and id-only transitions have no
// OSC 8 representation of their own.
func urlNeedsEmission(oldUrl, newUrl urlInfo) bool {
return oldUrl != newUrl && (oldUrl.url != "" || newUrl.url != "")
}
func (t *tScreen) drawCell(x, y int) int {
// Check Dirty first: most cells are clean, and Get copies the style.
if !t.cells.Dirty(x, y) {
_, _, width := t.cells.Get(x, y)
return width
}
str, style, width := t.cells.Get(x, y)
if t.cy != y || t.cx != x {
t.csi(csiCUP, y+1, x+1)
t.cx = x
t.cy = y
}
if style == StyleDefault {
style = t.style
}
if style != t.curstyle {
fg, bg, attrs := style.fg, style.bg, style.attrs
t.Print(sgr0)
attrs = t.sendFgBg(fg, bg, attrs)
t.emitAttrs(attrs)
t.emitUnderline(style.ulStyle, style.ulColor)
var newUrl urlInfo
var oldUrl urlInfo
if t.curstyle.url != nil {
oldUrl = *t.curstyle.url
}
if style.url != nil {
newUrl = *style.url
}
// URL string can be long, so don't send it unless we really need to.
if urlNeedsEmission(oldUrl, newUrl) {
t.emitUrl(newUrl)
}
t.curstyle = style
}
// now emit runes - taking care to not overrun width with a
// wide character, and to ensure that we emit exactly one regular
// character followed up by any residual combing characters
if width < 1 {
width = 1
}
// Skip the encoder (and its allocations) for text it would pass through
// unchanged.
switch {
case str[0] == encoding.ASCIISub:
// The encoder path treats SUB as unencodable and draws the fallback.
str = string(t.encodeStr(str))
case t.encoder == nil && utf8.ValidString(str):
// UTF-8 is written as is.
case t.asciiSuperset && isASCII(str):
// The encoding writes ASCII as itself.
default:
str = string(t.encodeStr(str))
}
if width > 1 && str == "?" {
// No FullWidth character support
str = "? "
t.cx = -1
}
if x > t.w-width {
// too wide to fit; emit a single space instead
width = 1
str = " "
}
if width > 1 && x+width < t.w {
// Clobber over any content in the next cell.
// This fixes a problem with some terminals where overwriting two
// adjacent single cells with a wide rune would leave an image
// of the second cell. This is a workaround for buggy terminals.
t.Print(" \b\b")
}
t.Print(str)
t.cx += width
t.cells.SetDirty(x, y, false)
if width > 1 && len([]rune(str)) > 1 {
t.cx = -1
}
return width
}
func (t *tScreen) ShowCursor(x, y int) {
t.Lock()
if t.fini {
t.Unlock()
return
}
t.cursorx = x
t.cursory = y
t.Unlock()
}
func (t *tScreen) SetCursor(cs CursorStyle, cc Color) {
t.Lock()
if t.fini {