-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathvaxis.go
More file actions
1709 lines (1583 loc) · 44.5 KB
/
vaxis.go
File metadata and controls
1709 lines (1583 loc) · 44.5 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
// Package vaxis is a terminal user interface for modern terminals
package vaxis
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io"
"os"
"os/signal"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/containerd/console"
"git.sr.ht/~rockorager/vaxis/ansi"
"git.sr.ht/~rockorager/vaxis/log"
)
type capabilities struct {
synchronizedUpdate bool
unicodeCore bool
noZWJ bool // a terminal may support shaped emoji but not ZWJ
rgb bool
kittyGraphics bool
kittyKeyboard bool
styledUnderlines bool
sixels bool
colorThemeUpdates bool
reportSizeChars bool
reportSizePixels bool
osc4 bool
osc10 bool
osc11 bool
osc176 bool
inBandResize bool
explicitWidth bool
sgrPixels bool
}
type cursorState struct {
row int
col int
style CursorStyle
visible bool
}
// Options are the runtime options which must be supplied to a new [Vaxis]
// object at instantiation
type Options struct {
// DisableKittyKeyboard disables the use of the Kitty Keyboard protocol.
// By default, if support is detected the protocol will be used.
DisableKittyKeyboard bool
// Deprecated Use CSIuBitMask instead
//
// ReportKeyboardEvents will report key release and key repeat events if
// KittyKeyboardProtocol is enabled and supported by the terminal
ReportKeyboardEvents bool
// The size of the event queue channel. This will default to 1024 to
// prevent any blocking on writes.
EventQueueSize int
// Disable mouse events
DisableMouse bool
// WithTTY passes an absolute path to use for the TTY Vaxis will draw
// on. If the file is not a TTY, an error will be returned when calling
// New
WithTTY string
// NoSignals causes Vaxis to not install any signal handlers
NoSignals bool
// CSIuBitMask is the bit mask to use for CSIu key encoding, when
// available. This has no effect if DisableKittyKeyboard is true
CSIuBitMask CSIuBitMask
// WithConsole provides the ability to use a custom console.
WithConsole console.Console
// EnableSGRPixels provides pixel level precision of mouse movement. This has
// no effect if DisableMouse is true
EnableSGRPixels bool
}
type CSIuBitMask int
const (
CSIuDisambiguate CSIuBitMask = 1 << iota
CSIuReportEvents
CSIuAlternateKeys
CSIuAllKeys
CSIuAssociatedText
)
type Vaxis struct {
queue chan Event
console console.Console
parser *ansi.Parser
tw *writer
screenNext *screen
screenLast *screen
graphicsNext []*placement
graphicsLast []*placement
mouseShapeNext MouseShape
mouseShapeLast MouseShape
appIDLast appID
pastePending bool
chClipboard chan string
chSigWinSz chan os.Signal
chSigKill chan os.Signal
chCursorPos chan [2]int
chQuit chan bool
winSize Resize
nextSize Resize
chSizeDone chan bool
caps capabilities
graphicsProtocol int
graphicsIDNext uint64
reqCursorPos int32
charCache map[string]int
cursorNext cursorState
cursorLast cursorState
closed bool
refresh bool
kittyFlags int
disableMouse bool
chFg chan string
chBg chan string
chColor chan string
userCursorStyle CursorStyle
xtwinops bool
withTty string
withConsole console.Console
termID terminalID
renders int
elapsed time.Duration
mu sync.Mutex
resize int32
noSignals bool
}
// New creates a new [Vaxis] instance. Calling New will query the underlying
// terminal for supported features and enter the alternate screen
func New(opts Options) (*Vaxis, error) {
switch os.Getenv("VAXIS_LOG_LEVEL") {
case "trace":
log.SetLevel(log.LevelTrace)
log.SetOutput(os.Stderr)
case "debug":
log.SetLevel(log.LevelDebug)
log.SetOutput(os.Stderr)
case "info":
log.SetLevel(log.LevelInfo)
log.SetOutput(os.Stderr)
case "warn":
log.SetLevel(log.LevelWarn)
log.SetOutput(os.Stderr)
case "error":
log.SetLevel(log.LevelError)
log.SetOutput(os.Stderr)
}
// Let's give some deadline for our queries responding. If they don't,
// it means the terminal doesn't respond to Primary Device Attributes
// and that is a problem
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
var err error
vx := &Vaxis{
kittyFlags: int(CSIuDisambiguate),
}
if opts.CSIuBitMask > CSIuDisambiguate {
vx.kittyFlags = int(opts.CSIuBitMask)
}
if opts.ReportKeyboardEvents {
vx.kittyFlags |= int(CSIuReportEvents)
}
if opts.EventQueueSize < 1 {
opts.EventQueueSize = 1024
}
if opts.DisableMouse {
vx.disableMouse = true
}
vx.noSignals = opts.NoSignals
var tgts []*os.File
switch {
case opts.WithConsole != nil:
vx.withConsole = opts.WithConsole
case opts.WithTTY != "":
vx.withTty = opts.WithTTY
f, err := os.OpenFile(opts.WithTTY, os.O_RDWR, 0)
if err != nil {
return nil, err
}
tgts = []*os.File{f}
default:
f, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
tgts = []*os.File{os.Stderr, os.Stdout, os.Stdin}
break
}
tgts = []*os.File{f, os.Stderr, os.Stdout, os.Stdin}
}
vx.queue = make(chan Event, opts.EventQueueSize)
vx.screenNext = newScreen()
vx.screenLast = newScreen()
vx.chClipboard = make(chan string)
vx.chSigWinSz = make(chan os.Signal, 1)
vx.chSigKill = make(chan os.Signal, 1)
vx.chCursorPos = make(chan [2]int)
vx.chQuit = make(chan bool)
vx.chSizeDone = make(chan bool, 1)
vx.charCache = make(map[string]int, 256)
vx.chFg = make(chan string, 1)
vx.chBg = make(chan string, 1)
vx.chColor = make(chan string, 1)
err = vx.openTty(tgts)
if err != nil {
return nil, err
}
vx.sendQueries()
outer:
for {
select {
case <-ctx.Done():
log.Warn("terminal did not respond to DA1 query")
break outer
case ev := <-vx.queue:
switch ev := ev.(type) {
case primaryDeviceAttribute:
break outer
case capabilitySixel:
log.Info("[capability] Sixel graphics")
vx.mu.Lock()
vx.caps.sixels = true
if vx.graphicsProtocol < sixelGraphics {
vx.graphicsProtocol = sixelGraphics
}
vx.mu.Unlock()
case capabilityOsc4:
log.Info("[capability] OSC 4 supported")
vx.mu.Lock()
vx.caps.osc4 = true
vx.mu.Unlock()
case capabilityOsc10:
log.Info("[capability] OSC 10 supported")
vx.mu.Lock()
vx.caps.osc10 = true
vx.mu.Unlock()
case capabilityOsc11:
log.Info("[capability] OSC 11 supported")
vx.mu.Lock()
vx.caps.osc11 = true
vx.mu.Unlock()
case synchronizedUpdates:
log.Info("[capability] Synchronized updates")
vx.mu.Lock()
vx.caps.synchronizedUpdate = true
vx.mu.Unlock()
case unicodeCoreCap:
log.Info("[capability] Unicode core")
vx.mu.Lock()
vx.caps.unicodeCore = true
vx.mu.Unlock()
case notifyColorChange:
log.Info("[capability] Color theme notifications")
vx.mu.Lock()
vx.caps.colorThemeUpdates = true
vx.mu.Unlock()
case kittyKeyboard:
log.Info("[capability] Kitty keyboard")
if opts.DisableKittyKeyboard {
continue
}
vx.mu.Lock()
vx.caps.kittyKeyboard = true
vx.mu.Unlock()
case styledUnderlines:
log.Info("[capability] Styled underlines")
vx.mu.Lock()
vx.caps.styledUnderlines = true
vx.mu.Unlock()
case truecolor:
log.Info("[capability] RGB")
vx.mu.Lock()
vx.caps.rgb = true
vx.mu.Unlock()
case kittyGraphics:
log.Info("[capability] Kitty graphics supported")
vx.mu.Lock()
vx.caps.kittyGraphics = true
if vx.graphicsProtocol < kitty {
vx.graphicsProtocol = kitty
}
vx.mu.Unlock()
case textAreaPix:
log.Info("[capability] Report screen size: pixels")
vx.mu.Lock()
vx.caps.reportSizePixels = true
vx.mu.Unlock()
case textAreaChar:
log.Info("[capability] Report screen size: characters")
vx.mu.Lock()
vx.caps.reportSizeChars = true
vx.mu.Unlock()
case appID:
log.Info("[capability] OSC 176 supported")
vx.mu.Lock()
vx.caps.osc176 = true
vx.appIDLast = ev
vx.mu.Unlock()
case terminalID:
vx.mu.Lock()
vx.termID = ev
vx.mu.Unlock()
case inBandResizeEvents:
vx.mu.Lock()
vx.caps.inBandResize = true
vx.mu.Unlock()
case capabilitySgrPixels:
log.Info("[capability] SGR Pixels supported")
if !opts.EnableSGRPixels {
continue
}
vx.mu.Lock()
vx.caps.sgrPixels = true
vx.mu.Unlock()
}
}
}
vx.enterAltScreen()
vx.enableModes()
if !vx.noSignals {
vx.setupSignals()
}
vx.applyQuirks()
switch os.Getenv("VAXIS_GRAPHICS") {
case "none":
vx.graphicsProtocol = noGraphics
case "full":
vx.graphicsProtocol = fullBlock
case "half":
vx.graphicsProtocol = halfBlock
case "sixel":
vx.graphicsProtocol = sixelGraphics
case "kitty":
vx.graphicsProtocol = kitty
default:
// Use highest quality block renderer by default. Users will
// need to fallback on their own if not supported
if vx.graphicsProtocol < halfBlock {
vx.graphicsProtocol = halfBlock
}
}
ws, err := vx.reportWinsize()
if err != nil {
return nil, err
}
if ws.XPixel == 0 || ws.YPixel == 0 {
log.Debug("pixel size not reported, setting graphics protocol to half block")
vx.graphicsProtocol = halfBlock
}
vx.screenNext.resize(ws.Cols, ws.Rows)
vx.screenLast.resize(ws.Cols, ws.Rows)
vx.winSize = ws
// Set the next style to be a CursorBlock by default.
vx.cursorNext.style = CursorBlock
vx.PostEvent(vx.winSize)
return vx, nil
}
// PostEvent inserts an event into the [Vaxis] event loop
func (vx *Vaxis) PostEvent(ev Event) {
log.Debug("[event] %#v", ev)
select {
case vx.queue <- ev:
return
default:
log.Warn("Event dropped: %T", ev)
}
}
// PostEventBlocking inserts an event into the [Vaxis] event loop. The call will
// block if the queue is full. This method should only be used from a different
// goroutine than the main thread.
func (vx *Vaxis) PostEventBlocking(ev Event) {
vx.queue <- ev
}
// SyncFunc queues a function to be called from the main thread. vaxis will call
// the function when the event is received in the main thread either through
// PollEvent or Events. A Redraw event will be sent to the host application
// after the function is completed
func (vx *Vaxis) SyncFunc(fn func()) {
vx.PostEvent(SyncFunc(fn))
}
// PollEvent blocks until there is an Event, and returns that Event
func (vx *Vaxis) PollEvent() Event {
ev, ok := <-vx.queue
if !ok {
return QuitEvent{}
}
return ev
}
// Events returns the channel of events.
func (vx *Vaxis) Events() chan Event {
return vx.queue
}
// Close shuts down the event loops and returns the terminal to it's original
// state
func (vx *Vaxis) Close() {
if vx.closed {
return
}
vx.PostEvent(QuitEvent{})
vx.closed = true
defer close(vx.chQuit)
vx.Suspend()
vx.console.Close()
log.Info("Renders: %d", vx.renders)
if vx.renders != 0 {
log.Info("Time/render: %s", vx.elapsed/time.Duration(vx.renders))
}
log.Info("Cached characters: %d", len(vx.charCache))
}
// Resize manually triggers a resize event. Normally, vaxis listens to SIGWINCH
// for resize events, however in some use cases a manual resize trigger may be
// needed
func (vx *Vaxis) Resize() {
atomicStore(&vx.resize, true)
vx.PostEvent(Redraw{})
}
// Render renders the model's content to the terminal
func (vx *Vaxis) Render() {
if atomicLoad(&vx.resize) {
defer atomicStore(&vx.resize, false)
ws, err := vx.reportWinsize()
if err != nil {
log.Error("couldn't report winsize: %v", err)
return
}
if ws.Cols != vx.winSize.Cols || ws.Rows != vx.winSize.Rows {
vx.screenNext.resize(ws.Cols, ws.Rows)
vx.screenLast.resize(ws.Cols, ws.Rows)
vx.winSize = ws
vx.refresh = true
vx.PostEvent(vx.winSize)
return
}
}
start := time.Now()
// defer renderBuf.Reset()
vx.render()
_, _ = vx.tw.Flush()
// updating cursor state has to be after Flush, we check state change in
// flush.
vx.cursorLast = vx.cursorNext
vx.elapsed += time.Since(start)
vx.renders += 1
vx.refresh = false
}
// Refresh forces a full render of the entire screen. Traditionally, this should
// be bound to Ctrl+l
func (vx *Vaxis) Refresh() {
vx.refresh = true
vx.Render()
}
func (vx *Vaxis) render() {
vx.mu.Lock()
defer vx.mu.Unlock()
var (
reposition = true
cursor Style
)
outerLast:
// Delete any placements we don't have this round
for _, p1 := range vx.graphicsLast {
// Delete all previous placements on a refresh
if vx.refresh {
p1.deleteFn(vx.tw)
continue
}
for _, p2 := range vx.graphicsNext {
if samePlacement(p1, p2) {
continue outerLast
}
}
p1.deleteFn(vx.tw)
}
if vx.refresh {
vx.graphicsLast = []*placement{}
}
outerNew:
// draw new placements
for _, p1 := range vx.graphicsNext {
for _, p2 := range vx.graphicsLast {
if samePlacement(p1, p2) {
// don't write existing placements
continue outerNew
}
}
vx.tw.writeCUP(p1.row+1, p1.col+1)
p1.writeTo(vx.tw)
}
// Save this frame as the last frame
vx.graphicsLast = vx.graphicsNext
if vx.mouseShapeLast != vx.mouseShapeNext {
_, _ = vx.tw.WriteString(tparm(mouseShape, vx.mouseShapeNext))
vx.mouseShapeLast = vx.mouseShapeNext
}
for row := range vx.screenNext.buf {
reposition = true
for col := 0; col < len(vx.screenNext.buf[row]); col += 1 {
next := vx.screenNext.buf[row][col]
if next.sixel {
vx.screenLast.buf[row][col].sixel = true
reposition = true
continue
}
if next == vx.screenLast.buf[row][col] && !vx.refresh {
reposition = true
// Advance the column by the width of this
// character
skip := vx.advance(next)
// skip := advance(next.Content)
for i := 1; i < skip+1; i += 1 {
if col+i >= len(vx.screenNext.buf[row]) {
break
}
// null out any cells we end up skipping
vx.screenLast.buf[row][col+i] = Cell{}
}
col += skip
continue
}
vx.screenLast.buf[row][col] = next
if reposition {
if cursor.Hyperlink != "" {
cursor.Hyperlink = ""
vx.tw.writeOSC8("", "")
}
vx.tw.writeCUP(row+1, col+1)
reposition = false
}
// TODO Optimizations
// 1. We could save two bytes when both FG and BG change
// by combining into a single sequence. It saves one
// "\x1b" and one "m". It adds a lot of complexity
// though
//
// 2. We could save some more bytes when FG, BG, and Attr
// all change. Lots of complexity to add this
if cursor.Foreground != next.Foreground {
fg := next.Foreground
ps := fg.Params()
if !vx.caps.rgb {
ps = fg.asIndex().Params()
}
switch len(ps) {
case 0:
_, _ = vx.tw.WriteString(fgReset)
case 1:
switch {
case ps[0] < 8:
_, _ = vx.tw.WriteString(fgIndexedSeq[int(ps[0])])
case ps[0] < 16:
_, _ = vx.tw.WriteString(fgBrightSeq[int(ps[0]-8)])
default:
vx.tw.writeSGRIndexed(38, ps[0])
}
case 3:
vx.tw.writeSGRRGB(38, ps[0], ps[1], ps[2])
}
}
if cursor.Background != next.Background {
bg := next.Background
ps := bg.Params()
if !vx.caps.rgb {
ps = bg.asIndex().Params()
}
switch len(ps) {
case 0:
_, _ = vx.tw.WriteString(bgReset)
case 1:
switch {
case ps[0] < 8:
_, _ = vx.tw.WriteString(bgIndexedSeq[int(ps[0])])
case ps[0] < 16:
_, _ = vx.tw.WriteString(bgBrightSeq[int(ps[0]-8)])
default:
vx.tw.writeSGRIndexed(48, ps[0])
}
case 3:
vx.tw.writeSGRRGB(48, ps[0], ps[1], ps[2])
}
}
if vx.caps.styledUnderlines {
if cursor.UnderlineColor != next.UnderlineColor {
ul := next.UnderlineColor
ps := ul.Params()
if !vx.caps.rgb {
ps = ul.asIndex().Params()
}
switch len(ps) {
case 0:
_, _ = vx.tw.WriteString(ulColorReset)
case 1:
vx.tw.writeSGRIndexed(58, ps[0])
case 3:
vx.tw.writeSGRRGB(58, ps[0], ps[1], ps[2])
}
}
}
if cursor.Attribute != next.Attribute {
attr := cursor.Attribute
// find the ones that have changed
dAttr := attr ^ next.Attribute
// If the bit is changed and in next, it was
// turned on
on := dAttr & next.Attribute
if on&AttrBold != 0 {
_, _ = vx.tw.WriteString(boldSet)
}
if on&AttrDim != 0 {
_, _ = vx.tw.WriteString(dimSet)
}
if on&AttrItalic != 0 {
_, _ = vx.tw.WriteString(italicSet)
}
if on&AttrBlink != 0 {
_, _ = vx.tw.WriteString(blinkSet)
}
if on&AttrReverse != 0 {
_, _ = vx.tw.WriteString(reverseSet)
}
if on&AttrInvisible != 0 {
_, _ = vx.tw.WriteString(hiddenSet)
}
if on&AttrStrikethrough != 0 {
_, _ = vx.tw.WriteString(strikethroughSet)
}
// If the bit is changed and is in previous, it
// was turned off
off := dAttr & attr
if off&AttrBold != 0 {
// Normal intensity isn't in terminfo
_, _ = vx.tw.WriteString(boldDimReset)
// Normal intensity turns off dim. If it
// should be on, let's turn it back on
if next.Attribute&AttrDim != 0 {
_, _ = vx.tw.WriteString(dimSet)
}
}
if off&AttrDim != 0 {
// Normal intensity isn't in terminfo
_, _ = vx.tw.WriteString(boldDimReset)
// Normal intensity turns off bold. If it
// should be on, let's turn it back on
if next.Attribute&AttrBold != 0 {
_, _ = vx.tw.WriteString(boldSet)
}
}
if off&AttrItalic != 0 {
_, _ = vx.tw.WriteString(italicReset)
}
if off&AttrBlink != 0 {
// turn off blink isn't in terminfo
_, _ = vx.tw.WriteString(blinkReset)
}
if off&AttrReverse != 0 {
_, _ = vx.tw.WriteString(reverseReset)
}
if off&AttrInvisible != 0 {
// turn off invisible isn't in terminfo
_, _ = vx.tw.WriteString(hiddenReset)
}
if off&AttrStrikethrough != 0 {
_, _ = vx.tw.WriteString(strikethroughReset)
}
}
if cursor.UnderlineStyle != next.UnderlineStyle {
ulStyle := next.UnderlineStyle
switch vx.caps.styledUnderlines {
case true:
vx.tw.writeUnderlineStyle(ulStyle)
case false:
switch ulStyle {
case UnderlineOff:
_, _ = vx.tw.WriteString(underlineReset)
default:
// Fallback to single underlines
_, _ = vx.tw.WriteString(underlineSet)
}
}
}
if cursor.Hyperlink != next.Hyperlink {
link := next.Hyperlink
linkPs := next.HyperlinkParams
if link == "" {
linkPs = ""
}
vx.tw.writeOSC8(linkPs, link)
}
cursor = next.Style
if next.Width == 0 {
next.Width = vx.characterWidth(next.Grapheme)
}
switch {
case next.Width == 0:
_, _ = vx.tw.WriteString(" ")
case next.Width > 1 && vx.caps.explicitWidth:
vx.tw.writeExplicitWidth(next.Width, next.Grapheme)
default:
_, _ = vx.tw.WriteString(next.Grapheme)
}
skip := vx.advance(next)
for i := 1; i < skip+1; i += 1 {
if col+i >= len(vx.screenNext.buf[row]) {
break
}
// null out any cells we end up skipping
vx.screenLast.buf[row][col+i] = Cell{}
}
col += skip
}
}
if cursor.Hyperlink != "" {
vx.tw.writeOSC8("", "")
}
if vx.cursorNext.visible && !vx.cursorLast.visible {
_, _ = vx.tw.WriteString(vx.showCursor())
}
}
func (vx *Vaxis) handleSequence(seq ansi.Sequence) {
log.Trace("[stdin] sequence: %s", seq)
switch seq := seq.(type) {
case ansi.Print:
key := decodeKey(seq)
if vx.pastePending {
key.EventType = EventPaste
}
vx.PostEventBlocking(key)
case ansi.C0:
key := decodeKey(seq)
if vx.pastePending {
key.EventType = EventPaste
}
vx.PostEventBlocking(key)
case ansi.ESC:
key := decodeKey(seq)
if vx.pastePending {
key.EventType = EventPaste
}
vx.PostEventBlocking(key)
case ansi.SS3:
key := decodeKey(seq)
if vx.pastePending {
key.EventType = EventPaste
}
vx.PostEventBlocking(key)
case ansi.CSI:
switch seq.Final {
case 'c':
if len(seq.Intermediate) == 1 && seq.Intermediate[0] == '?' {
for _, ps := range seq.Parameters {
switch ps[0] {
case 4:
vx.PostEventBlocking(capabilitySixel{})
}
}
vx.PostEventBlocking(primaryDeviceAttribute{})
return
}
case 'I':
vx.PostEventBlocking(FocusIn{})
return
case 'O':
vx.PostEventBlocking(FocusOut{})
return
case 'R':
// KeyF1 or DSRCPR
// This could be an F1 key, we need to buffer if we have
// requested a DSRCPR (cursor position report)
//
// Kitty keyboard protocol disambiguates this scenario,
// hopefully people are using that
if atomicLoad(&vx.reqCursorPos) {
atomicStore(&vx.reqCursorPos, false)
if len(seq.Parameters) != 2 {
log.Error("not enough DSRCPR params")
return
}
vx.chCursorPos <- [2]int{
seq.Parameters[0][0],
seq.Parameters[1][0],
}
return
}
case 'S':
if len(seq.Intermediate) == 1 && seq.Intermediate[0] == '?' {
if len(seq.Parameters) < 3 {
break
}
switch seq.Parameters[0][0] {
case 2:
if seq.Parameters[1][0] == 0 {
vx.PostEventBlocking(capabilitySixel{})
}
}
return
}
case 'n':
if len(seq.Intermediate) == 1 && seq.Intermediate[0] == '?' {
if len(seq.Parameters) != 2 {
break
}
switch seq.Parameters[0][0] {
case colorThemeResp: // 997
m := ColorThemeMode(seq.Parameters[1][0])
vx.PostEventBlocking(ColorThemeUpdate{
Mode: m,
})
}
return
}
case 'y':
// DECRPM - DEC Report Mode
if len(seq.Parameters) < 1 {
log.Error("not enough DECRPM params")
return
}
switch seq.Parameters[0][0] {
case 1016:
if len(seq.Parameters) < 2 {
log.Error("not enough DECRPM params")
return
}
switch seq.Parameters[1][0] {
case 1, 2:
vx.PostEventBlocking(capabilitySgrPixels{})
}
case 2026:
if len(seq.Parameters) < 2 {
log.Error("not enough DECRPM params")
return
}
switch seq.Parameters[1][0] {
case 1, 2:
vx.PostEventBlocking(synchronizedUpdates{})
}
case 2027:
if len(seq.Parameters) < 2 {
log.Error("not enough DECRPM params")
return
}
switch seq.Parameters[1][0] {
case 1, 2:
vx.PostEventBlocking(unicodeCoreCap{})
}
case 2031:
if len(seq.Parameters) < 2 {
log.Error("not enough DECRPM params")
return
}
switch seq.Parameters[1][0] {
case 1, 2:
vx.PostEventBlocking(notifyColorChange{})
}
}
return
case 'u':
if len(seq.Intermediate) == 1 && seq.Intermediate[0] == '?' {
vx.PostEventBlocking(kittyKeyboard{})
return
}
case '~':
if len(seq.Intermediate) == 0 {
if len(seq.Parameters) == 0 {
log.Error("[CSI] unknown sequence with final '~'")
return
}
switch seq.Parameters[0][0] {
case 200:
vx.pastePending = true
vx.PostEventBlocking(PasteStartEvent{})
return
case 201:
vx.pastePending = false
vx.PostEventBlocking(PasteEndEvent{})
return
}
}
case 'M', 'm':
mouse, ok := parseMouseEvent(seq, vx.winSize, vx.caps.sgrPixels)
if ok {
vx.PostEventBlocking(mouse)
}
return
case 't':
if len(seq.Parameters) < 3 {
log.Error("[CSI] unknown sequence: %s", seq)
return
}
// CSI <type> ; <height> ; <width> t
typ := seq.Parameters[0][0]
h := seq.Parameters[1][0]
w := seq.Parameters[2][0]
switch typ {
case 4:
vx.mu.Lock()
vx.nextSize.XPixel = w
vx.nextSize.YPixel = h
report := vx.caps.reportSizePixels
vx.mu.Unlock()
if !report {
// Gate on this so we only report this
// once at startup
vx.PostEventBlocking(textAreaPix{})
return
}
case 8:
vx.mu.Lock()
vx.nextSize.Cols = w
vx.nextSize.Rows = h
report := vx.caps.reportSizeChars
vx.mu.Unlock()
if !report {
// Gate on this so we only report this
// once at startup. This also means we
// can set the size directly and won't
// have race conditions
vx.PostEventBlocking(textAreaChar{})
return
}
vx.chSizeDone <- true
case 48:
// CSI <type> ; <height> ; <width> ; <height_pix> ; <width_pix> t
switch len(seq.Parameters) {
case 5:
atomicStore(&vx.resize, true)
vx.mu.Lock()
vx.nextSize.Cols = w
vx.nextSize.Rows = h
vx.nextSize.YPixel = seq.Parameters[3][0]
vx.nextSize.XPixel = seq.Parameters[4][0]
resize := vx.caps.inBandResize
vx.mu.Unlock()
if !resize {
vx.PostEventBlocking(inBandResizeEvents{})
}
vx.Resize()
}
}
return
}