Debian Codegraph @

src/tui/light.go

raw
1 package tui
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "os"
8 "regexp"
9 "strconv"
10 "strings"
11 "sync"
12 "time"
13 "unicode/utf8"
14
15 "github.com/junegunn/fzf/src/util"
16
17 "golang.org/x/term"
18 )
19
20 const (
21 defaultWidth = 80
22 defaultHeight = 24
23
24 defaultEscDelay = 100
25 escPollInterval = 5
26 offsetPollTries = 10
27 queryTimeout = 500 * time.Millisecond
28 maxInputBuffer = 1024 * 1024
29 escapeLookback = 256
30 )
31
32 const DefaultTtyDevice string = "/dev/tty"
33
34 var offsetRegexp = regexp.MustCompile("\x00?\x1b\\[([0-9]+);([0-9]+)R")
35 var offsetRegexpBegin = regexp.MustCompile("^\x1b\\[[0-9]+;[0-9]+R")
36
37 // DECRPM reply to the DECRQM query for bracketed paste mode. Ps is 1 or 3 when
38 // the mode was already set, 2 or 4 when reset, 0 when the terminal does not
39 // recognize the mode.
40 var pasteModeRegexp = regexp.MustCompile("\x00?\x1b\\[\\?2004;([0-4])\\$y")
41 var pasteModeRegexpBegin = regexp.MustCompile("^\x1b\\[\\?2004;[0-4]\\$y")
42
43 // A report to ask the terminal for, and the reply to recognize it by.
44 type termQuery struct {
45 seq string
46 reply *regexp.Regexp
47 }
48
49 var offsetQuery = termQuery{"6n", offsetRegexp}
50 var pasteModeQuery = termQuery{"?2004$p", pasteModeRegexp}
51
52 // What we ask the terminal at startup, in the order the queries go out.
53 // A terminal answers them in that order, so the cursor position query is last
54 // and also ends the wait: every terminal fzf supports answers it, so once its
55 // reply arrives, a query still unanswered is one the terminal does not know
56 // rather than one we stopped waiting for too early.
57 //
58 // Terminals that don't support the paste mode query (DECRQM) might leave
59 // 'p' on the screen. To handle such cases, we query the position before and
60 // after it, compare them, and clean the artifact if they don't match.
61 //
62 // Reference: https://ansicode.eversources.app/en/sequence/decrqm
63 var startupQueries = []termQuery{offsetQuery, pasteModeQuery, offsetQuery}
64
65 func (r *LightRenderer) Bell() {
66 r.flushRaw("\a")
67 }
68
69 func (r *LightRenderer) PassThrough(str string) {
70 r.queued.WriteString("\x1b7" + str + "\x1b8")
71 r.invalidateSGR()
72 }
73
74 func (r *LightRenderer) stderr(str string) {
75 r.stderrInternal(str, true, "")
76 }
77
78 const DIM string = "\x1b[2m"
79 const CR string = DIM + "␍"
80 const LF string = DIM + "␊"
81
82 type getCharResult int
83
84 const (
85 getCharSuccess getCharResult = iota
86 getCharError
87 getCharCancelled
88 )
89
90 func (r getCharResult) ok() bool {
91 return r == getCharSuccess
92 }
93
94 func (r *LightRenderer) stderrInternal(str string, allowNLCR bool, resetCode string) {
95 bytes := []byte(str)
96 runes := []rune{}
97 for len(bytes) > 0 {
98 r, sz := utf8.DecodeRune(bytes)
99 nlcr := r == '\n' || r == '\r'
100 isC1 := r >= 0x80 && r <= 0x9F
101 if (r >= 32 && !isC1) || r == '\x1b' || nlcr {
102 if nlcr && !allowNLCR {
103 if r == '\r' {
104 runes = append(runes, []rune(CR+resetCode)...)
105 } else {
106 runes = append(runes, []rune(LF+resetCode)...)
107 }
108 } else if r != utf8.RuneError {
109 runes = append(runes, r)
110 }
111 }
112 bytes = bytes[sz:]
113 }
114 r.queued.WriteString(string(runes))
115 }
116
117 func (r *LightRenderer) csi(code string) string {
118 fullcode := "\x1b[" + code
119 r.stderr(fullcode)
120 return fullcode
121 }
122
123 // setSGR emits the given SGR sequence only when the terminal is not already
124 // in that state. Sequences built by csiColor start with a reset parameter,
125 // so each of them fully determines the state on its own. The zero value of
126 // r.sgr never matches a sequence, so the first update after Init, Resume, or
127 // invalidateSGR is always emitted.
128 func (r *LightRenderer) setSGR(code string) {
129 if code != r.sgr {
130 r.stderr(code)
131 r.sgr = code
132 }
133 }
134
135 // invalidateSGR marks the terminal SGR state as unknown, e.g. after raw
136 // output that may have changed it behind the renderer's back.
137 func (r *LightRenderer) invalidateSGR() {
138 r.sgr = ""
139 }
140
141 func (r *LightRenderer) flush() {
142 if r.queued.Len() > 0 {
143 // Leave the terminal in the default SGR state between frames
144 r.setSGR("\x1b[0m")
145 // Wrap the frame in synchronized update mode (2026) so that the
146 // terminal applies it atomically. Terminals without support ignore
147 // the unknown private mode and behave as before.
148 raw := "\x1b[?2026h\x1b[?7l\x1b[?25l" + r.queued.String()
149 if r.showCursor {
150 raw += "\x1b[?25h"
151 }
152 raw += "\x1b[?7h\x1b[?2026l"
153 r.flushRaw(raw)
154 r.queued.Reset()
155 }
156 }
157
158 func (r *LightRenderer) flushRaw(sequence string) {
159 fmt.Fprint(r.ttyout, sequence)
160 }
161
162 // Light renderer
163 type LightRenderer struct {
164 theme *ColorTheme
165 mouse bool
166 forceBlack bool
167 clearOnExit bool
168 prevDownTime time.Time
169 clicks [][2]int
170 ttyin *os.File
171 ttyout *os.File
172 cancel func()
173 buffer []byte
174 origState *term.State
175 width int
176 height int
177 yoffset int
178 xoffset int
179 tabstop int
180 escDelay int
181 fullscreen bool
182 upOneLine bool
183 queued strings.Builder
184 sgr string
185 y int
186 x int
187 maxHeightFunc func(int) int
188 showCursor bool
189 mutex sync.Mutex
190
191 // Whether bracketed paste was already on before we enabled it. Nil when
192 // the terminal did not answer the query.
193 pasteWasSet *bool
194
195 // Windows only
196 ttyinChannel chan byte
197 inHandle uintptr
198 outHandle uintptr
199 origStateInput uint32
200 origStateOutput uint32
201 }
202
203 type LightWindow struct {
204 renderer *LightRenderer
205 colored bool
206 windowType WindowType
207 border BorderStyle
208 top int
209 left int
210 width int
211 height int
212 posx int
213 posy int
214 tabstop int
215 fg Color
216 bg Color
217 wrapSign string
218 wrapSignWidth int
219 }
220
221 func NewLightRenderer(ttyDefault string, ttyin *os.File, theme *ColorTheme, forceBlack bool, mouse bool, tabstop int, clearOnExit bool, fullscreen bool, maxHeightFunc func(int) int) (Renderer, error) {
222 out, err := openTtyOut(ttyDefault)
223 if err != nil {
224 out = os.Stderr
225 }
226 r := LightRenderer{
227 theme: theme,
228 forceBlack: forceBlack,
229 mouse: mouse,
230 clearOnExit: clearOnExit,
231 ttyin: ttyin,
232 ttyout: out,
233 yoffset: 0,
234 tabstop: tabstop,
235 fullscreen: fullscreen,
236 upOneLine: false,
237 maxHeightFunc: maxHeightFunc,
238 showCursor: true}
239 return &r, nil
240 }
241
242 func repeat(r rune, times int) string {
243 if times > 0 {
244 return strings.Repeat(string(r), times)
245 }
246 return ""
247 }
248
249 func atoi(s string, defaultValue int) int {
250 value, err := strconv.Atoi(s)
251 if err != nil {
252 return defaultValue
253 }
254 return value
255 }
256
257 func (r *LightRenderer) Init() error {
258 r.escDelay = atoi(os.Getenv("ESCDELAY"), defaultEscDelay)
259
260 if err := r.initPlatform(); err != nil {
261 return err
262 }
263 r.updateTerminalSize()
264
265 if r.fullscreen {
266 r.smcup()
267 }
268
269 // Ask everything in one round trip, before the offset is needed.
270 y, x, pasteWasSet := r.queryStartup()
271 r.pasteWasSet = pasteWasSet
272
273 if !r.fullscreen {
274 r.mouse = r.mouse && y >= 0
275 // When --no-clear is used for repetitive relaunching, there is a small
276 // time frame between fzf processes where the user keystrokes are not
277 // captured by either of fzf process which can cause x offset to be
278 // increased and we're left with unwanted extra new line.
279 if x > 0 && r.clearOnExit {
280 r.upOneLine = true
281 r.xoffset = x
282 r.makeSpace()
283 }
284 // We assume that --no-clear is used for repetitive relaunching of fzf.
285 // So we do not clear the lower bottom of the screen.
286 if r.clearOnExit {
287 r.csi("J")
288 }
289 for i := 1; i < r.MaxY(); i++ {
290 r.makeSpace()
291 }
292 }
293
294 r.enableModes()
295 r.csi(fmt.Sprintf("%dA", r.MaxY()-1))
296 r.csi("G")
297 r.csi("K")
298 if !r.clearOnExit && !r.fullscreen {
299 r.stderr("\x1b7") // DECSC: save cursor position
300 }
301 if !r.fullscreen && r.mouse {
302 r.yoffset, _ = r.findOffset()
303 }
304 return nil
305 }
306
307 func (r *LightRenderer) Resize(maxHeightFunc func(int) int) {
308 r.maxHeightFunc = maxHeightFunc
309 }
310
311 func (r *LightRenderer) makeSpace() {
312 r.stderr("\n")
313 r.csi("G")
314 }
315
316 func (r *LightRenderer) move(y int, x int) {
317 if r.y < y {
318 r.csi(fmt.Sprintf("%dB", y-r.y))
319 } else if r.y > y {
320 r.csi(fmt.Sprintf("%dA", r.y-y))
321 }
322 if x == 0 {
323 r.stderr("\r")
324 } else {
325 r.csi(fmt.Sprintf("%dG", x+1))
326 }
327 r.y = y
328 r.x = x
329 }
330
331 func (r *LightRenderer) origin() {
332 r.move(0, 0)
333 }
334
335 func getEnv(name string, defaultValue int) int {
336 env := os.Getenv(name)
337 if len(env) == 0 {
338 return defaultValue
339 }
340 return atoi(env, defaultValue)
341 }
342
343 // Bytes of a CSI sequence: parameter and intermediate bytes continue it, a
344 // final byte ends it. Order is not enforced. Strictness would only make fzf
345 // give up on a sequence it could have framed.
346 //
347 // https://vt100.net/emu/dec_ansi_parser
348 func csiContinues(b byte) bool { return b >= 0x20 && b <= 0x3f }
349 func csiFinal(b byte) bool { return b >= 0x40 && b <= 0x7e }
350
351 // incompleteEscape reports whether the buffer ends in an escape sequence that
352 // has not been terminated yet. The read loop keeps waiting in that case, so the
353 // parser is never handed a fragment to guess at.
354 func incompleteEscape(buffer []byte) bool {
355 // Only the tail can hold a sequence still arriving. This runs once per byte
356 // read, so scanning all of a large paste would make the read quadratic.
357 tail := buffer
358 if len(tail) > escapeLookback {
359 tail = tail[len(tail)-escapeLookback:]
360 }
361 start := bytes.LastIndexByte(tail, Esc.Byte())
362 if start < 0 || len(tail)-start < 2 {
363 return false
364 }
365 switch tail[start+1] {
366 case '[':
367 for _, b := range tail[start+2:] {
368 if csiFinal(b) {
369 return false
370 }
371 if !csiContinues(b) {
372 return false // malformed, do not wait for a terminator
373 }
374 }
375 return true
376 case 'O':
377 return len(tail)-start < 3
378 }
379 return false
380 }
381
382 func (r *LightRenderer) getBytes(cancellable bool) ([]byte, getCharResult, error) {
383 return r.getBytesInternal(cancellable, r.buffer, false)
384 }
385
386 func (r *LightRenderer) getBytesInternal(cancellable bool, buffer []byte, nonblock bool) ([]byte, getCharResult, error) {
387 c, result := r.getch(cancellable, nonblock)
388 if result == getCharCancelled {
389 return buffer, getCharCancelled, nil
390 }
391 if !nonblock && !result.ok() {
392 r.Close()
393 return nil, getCharError, errors.New("failed to read " + DefaultTtyDevice)
394 }
395
396 retries := 0
397 if c == Esc.Int() || nonblock {
398 retries = r.escDelay / escPollInterval
399 }
400 // A non-blocking read that found nothing has no byte to record. Recording
401 // one would put a NUL in the middle of a reply still being assembled.
402 if result.ok() {
403 buffer = append(buffer, byte(c))
404 }
405
406 pc := c
407 for {
408 c, result = r.getch(false, true)
409 if !result.ok() {
410 if retries > 0 {
411 retries--
412 time.Sleep(escPollInterval * time.Millisecond)
413 continue
414 }
415 break
416 } else if c == Esc.Int() && pc != c {
417 retries = r.escDelay / escPollInterval
418 } else {
419 retries = 0
420 }
421 buffer = append(buffer, byte(c))
422 // Keep waiting while a sequence is still arriving. Dropping the budget
423 // after every byte left fzf parsing whatever the read happened to end on.
424 // Past the introducer this is not the ESC key, so the wait costs no
425 // Escape latency and ESCDELAY=0 must not reduce it to nothing.
426 if retries == 0 && incompleteEscape(buffer) {
427 retries = max(r.escDelay, defaultEscDelay) / escPollInterval
428 }
429 pc = c
430
431 // This should never happen under normal conditions,
432 // so terminate fzf immediately.
433 if len(buffer) > maxInputBuffer {
434 r.Close()
435 return nil, getCharError, fmt.Errorf("input buffer overflow (%d): %v", len(buffer), buffer)
436 }
437 }
438
439 return buffer, getCharSuccess, nil
440 }
441
442 func (r *LightRenderer) GetChar(cancellable bool) Event {
443 var err error
444 var result getCharResult
445 if len(r.buffer) == 0 {
446 r.buffer, result, err = r.getBytes(cancellable)
447 if err != nil {
448 return Event{Fatal, 0, nil}
449 }
450 if result == getCharCancelled {
451 return Event{Invalid, 0, nil}
452 }
453 }
454 if len(r.buffer) == 0 {
455 return Event{Fatal, 0, nil}
456 }
457
458 sz := 1
459 defer func() {
460 r.buffer = r.buffer[sz:]
461 }()
462
463 switch r.buffer[0] {
464 case CtrlC.Byte():
465 return Event{CtrlC, 0, nil}
466 case CtrlG.Byte():
467 return Event{CtrlG, 0, nil}
468 case CtrlQ.Byte():
469 return Event{CtrlQ, 0, nil}
470 case 127:
471 return Event{Backspace, 0, nil}
472 case 8:
473 return Event{CtrlBackspace, 0, nil}
474 case 0:
475 return Event{CtrlSpace, 0, nil}
476 case 28:
477 return Event{CtrlBackSlash, 0, nil}
478 case 29:
479 return Event{CtrlRightBracket, 0, nil}
480 case 30:
481 return Event{CtrlCaret, 0, nil}
482 case 31:
483 return Event{CtrlSlash, 0, nil}
484 case Esc.Byte():
485 ev := r.escSequence(&sz)
486 // Second chance
487 if ev.Type == Invalid {
488 r.buffer, result, err = r.getBytes(true)
489 if err != nil {
490 return Event{Fatal, 0, nil}
491 }
492 if result == getCharCancelled {
493 return Event{Invalid, 0, nil}
494 }
495
496 ev = r.escSequence(&sz)
497 }
498 return ev
499 }
500
501 // CTRL-A ~ CTRL-Z
502 if r.buffer[0] <= CtrlZ.Byte() {
503 return Event{EventType(r.buffer[0]), 0, nil}
504 }
505 char, rsz := utf8.DecodeRune(r.buffer)
506 if char == utf8.RuneError {
507 return Event{Esc, 0, nil}
508 }
509 sz = rsz
510 return Event{Rune, char, nil}
511 }
512
513 func (r *LightRenderer) CancelGetChar() {
514 r.mutex.Lock()
515 if r.cancel != nil {
516 r.cancel()
517 r.cancel = nil
518 }
519 r.mutex.Unlock()
520 }
521
522 func (r *LightRenderer) setCancel(f func()) {
523 r.mutex.Lock()
524 r.cancel = f
525 r.mutex.Unlock()
526 }
527
528 func (r *LightRenderer) escSequence(sz *int) Event {
529 if len(r.buffer) < 2 {
530 return Event{Esc, 0, nil}
531 }
532
533 loc := offsetRegexpBegin.FindIndex(r.buffer)
534 if loc != nil && loc[0] == 0 {
535 *sz = loc[1]
536 return Event{Invalid, 0, nil}
537 }
538
539 loc = pasteModeRegexpBegin.FindIndex(r.buffer)
540 if loc != nil && loc[0] == 0 {
541 *sz = loc[1]
542 return Event{Invalid, 0, nil}
543 }
544
545 *sz = 2
546 if r.buffer[1] == 8 {
547 return Event{CtrlAltBackspace, 0, nil}
548 }
549 if r.buffer[1] >= 1 && r.buffer[1] <= 'z'-'a'+1 {
550 return CtrlAltKey(rune(r.buffer[1] + 'a' - 1))
551 }
552 alt := false
553 if len(r.buffer) > 2 && r.buffer[1] == Esc.Byte() {
554 r.buffer = r.buffer[1:]
555 alt = true
556 }
557 switch r.buffer[1] {
558 case Esc.Byte():
559 return Event{Esc, 0, nil}
560 case 127:
561 return Event{AltBackspace, 0, nil}
562 case '[', 'O':
563 if len(r.buffer) < 3 {
564 return Event{Invalid, 0, nil}
565 }
566 *sz = 3
567 switch r.buffer[2] {
568 case 'D':
569 if alt {
570 return Event{AltLeft, 0, nil}
571 }
572 return Event{Left, 0, nil}
573 case 'C':
574 if alt {
575 // Ugh..
576 return Event{AltRight, 0, nil}
577 }
578 return Event{Right, 0, nil}
579 case 'B':
580 if alt {
581 return Event{AltDown, 0, nil}
582 }
583 return Event{Down, 0, nil}
584 case 'A':
585 if alt {
586 return Event{AltUp, 0, nil}
587 }
588 return Event{Up, 0, nil}
589 case 'Z':
590 return Event{ShiftTab, 0, nil}
591 case 'H':
592 return Event{Home, 0, nil}
593 case 'F':
594 return Event{End, 0, nil}
595 case '<':
596 return r.mouseSequence(sz)
597 case 'P':
598 return Event{F1, 0, nil}
599 case 'Q':
600 return Event{F2, 0, nil}
601 case 'R':
602 return Event{F3, 0, nil}
603 case 'S':
604 return Event{F4, 0, nil}
605 case '1', '2', '3', '4', '5', '6', '7', '8':
606 if len(r.buffer) < 4 {
607 return Event{Invalid, 0, nil}
608 }
609 *sz = 4
610 switch r.buffer[2] {
611 case '2':
612 if r.buffer[3] == '~' {
613 return Event{Insert, 0, nil}
614 }
615 if len(r.buffer) > 4 && r.buffer[4] == '~' {
616 *sz = 5
617 switch r.buffer[3] {
618 case '0':
619 return Event{F9, 0, nil}
620 case '1':
621 return Event{F10, 0, nil}
622 case '3':
623 return Event{F11, 0, nil}
624 case '4':
625 return Event{F12, 0, nil}
626 }
627 }
628 // Bracketed paste mode: \e[200~ ... \e[201~
629 if len(r.buffer) > 5 && r.buffer[3] == '0' && (r.buffer[4] == '0' || r.buffer[4] == '1') && r.buffer[5] == '~' {
630 *sz = 6
631 if r.buffer[4] == '0' {
632 return Event{BracketedPasteBegin, 0, nil}
633 }
634 return Event{BracketedPasteEnd, 0, nil}
635 }
636 return Event{Invalid, 0, nil} // INS
637 case '3':
638 if r.buffer[3] == '~' {
639 return Event{Delete, 0, nil}
640 }
641 if len(r.buffer) == 7 && r.buffer[6] == '~' && r.buffer[4] == '1' {
642 *sz = 7
643 switch r.buffer[5] {
644 case '0':
645 return Event{AltShiftDelete, 0, nil}
646 case '1':
647 return Event{AltDelete, 0, nil}
648 case '2':
649 return Event{AltShiftDelete, 0, nil}
650 case '3':
651 return Event{CtrlAltDelete, 0, nil}
652 case '4':
653 return Event{CtrlAltShiftDelete, 0, nil}
654 case '5':
655 return Event{CtrlAltDelete, 0, nil}
656 case '6':
657 return Event{CtrlAltShiftDelete, 0, nil}
658 }
659 }
660 if len(r.buffer) == 6 && r.buffer[5] == '~' {
661 *sz = 6
662 switch r.buffer[4] {
663 case '2':
664 return Event{ShiftDelete, 0, nil}
665 case '3':
666 return Event{AltDelete, 0, nil}
667 case '4':
668 return Event{AltShiftDelete, 0, nil}
669 case '5':
670 return Event{CtrlDelete, 0, nil}
671 case '6':
672 return Event{CtrlShiftDelete, 0, nil}
673 case '7':
674 return Event{CtrlAltDelete, 0, nil}
675 case '8':
676 return Event{CtrlAltShiftDelete, 0, nil}
677 case '9':
678 return Event{AltDelete, 0, nil}
679 }
680 }
681 return Event{Invalid, 0, nil}
682 case '4':
683 return Event{End, 0, nil}
684 case '5':
685 if r.buffer[3] == '~' {
686 return Event{PageUp, 0, nil}
687 }
688 if len(r.buffer) == 7 && r.buffer[6] == '~' && r.buffer[4] == '1' {
689 *sz = 7
690 switch r.buffer[5] {
691 case '0':
692 return Event{AltShiftPageUp, 0, nil}
693 case '1':
694 return Event{AltPageUp, 0, nil}
695 case '2':
696 return Event{AltShiftPageUp, 0, nil}
697 case '3':
698 return Event{CtrlAltPageUp, 0, nil}
699 case '4':
700 return Event{CtrlAltShiftPageUp, 0, nil}
701 case '5':
702 return Event{CtrlAltPageUp, 0, nil}
703 case '6':
704 return Event{CtrlAltShiftPageUp, 0, nil}
705 }
706 }
707 if len(r.buffer) == 6 && r.buffer[5] == '~' {
708 *sz = 6
709 switch r.buffer[4] {
710 case '2':
711 return Event{ShiftPageUp, 0, nil}
712 case '3':
713 return Event{AltPageUp, 0, nil}
714 case '4':
715 return Event{AltShiftPageUp, 0, nil}
716 case '5':
717 return Event{CtrlPageUp, 0, nil}
718 case '6':
719 return Event{CtrlShiftPageUp, 0, nil}
720 case '7':
721 return Event{CtrlAltPageUp, 0, nil}
722 case '8':
723 return Event{CtrlAltShiftPageUp, 0, nil}
724 case '9':
725 return Event{AltPageUp, 0, nil}
726 }
727 }
728 return Event{Invalid, 0, nil}
729 case '6':
730 if r.buffer[3] == '~' {
731 return Event{PageDown, 0, nil}
732 }
733 if len(r.buffer) == 7 && r.buffer[6] == '~' && r.buffer[4] == '1' {
734 *sz = 7
735 switch r.buffer[5] {
736 case '0':
737 return Event{AltShiftPageDown, 0, nil}
738 case '1':
739 return Event{AltPageDown, 0, nil}
740 case '2':
741 return Event{AltShiftPageDown, 0, nil}
742 case '3':
743 return Event{CtrlAltPageDown, 0, nil}
744 case '4':
745 return Event{CtrlAltShiftPageDown, 0, nil}
746 case '5':
747 return Event{CtrlAltPageDown, 0, nil}
748 case '6':
749 return Event{CtrlAltShiftPageDown, 0, nil}
750 }
751 }
752 if len(r.buffer) == 6 && r.buffer[5] == '~' {
753 *sz = 6
754 switch r.buffer[4] {
755 case '2':
756 return Event{ShiftPageDown, 0, nil}
757 case '3':
758 return Event{AltPageDown, 0, nil}
759 case '4':
760 return Event{AltShiftPageDown, 0, nil}
761 case '5':
762 return Event{CtrlPageDown, 0, nil}
763 case '6':
764 return Event{CtrlShiftPageDown, 0, nil}
765 case '7':
766 return Event{CtrlAltPageDown, 0, nil}
767 case '8':
768 return Event{CtrlAltShiftPageDown, 0, nil}
769 case '9':
770 return Event{AltPageDown, 0, nil}
771 }
772 }
773 return Event{Invalid, 0, nil}
774 case '7':
775 return Event{Home, 0, nil}
776 case '8':
777 return Event{End, 0, nil}
778 case '1':
779 switch r.buffer[3] {
780 case '~':
781 return Event{Home, 0, nil}
782 case '1', '2', '3', '4', '5', '7', '8', '9':
783 if len(r.buffer) == 5 && r.buffer[4] == '~' {
784 *sz = 5
785 switch r.buffer[3] {
786 case '1':
787 return Event{F1, 0, nil}
788 case '2':
789 return Event{F2, 0, nil}
790 case '3':
791 return Event{F3, 0, nil}
792 case '4':
793 return Event{F4, 0, nil}
794 case '5':
795 return Event{F5, 0, nil}
796 case '7':
797 return Event{F6, 0, nil}
798 case '8':
799 return Event{F7, 0, nil}
800 case '9':
801 return Event{F8, 0, nil}
802 }
803 }
804 return Event{Invalid, 0, nil}
805 case ';':
806 if len(r.buffer) < 6 {
807 return Event{Invalid, 0, nil}
808 }
809 *sz = 6
810 switch r.buffer[4] {
811 case '1', '2', '3', '4', '5', '6', '7', '8', '9':
812 // Kitty iTerm2 WezTerm
813 // ARROW "\e[1;1D"
814 // SHIFT-ARROW "\e[1;2D"
815 // ALT-SHIFT-ARROW "\e[1;4D" "\e[1;10D" "\e[1;4D"
816 // CTRL-SHIFT-ARROW "\e[1;6D" N/A
817 // CMD-SHIFT-ARROW "\e[1;10D" N/A N/A ("\e[1;2D")
818 ctrl := bytes.IndexByte([]byte{'5', '6', '7', '8'}, r.buffer[4]) >= 0
819 alt := bytes.IndexByte([]byte{'3', '4', '7', '8'}, r.buffer[4]) >= 0
820 shift := bytes.IndexByte([]byte{'2', '4', '6', '8'}, r.buffer[4]) >= 0
821 char := r.buffer[5]
822 if r.buffer[4] == '9' {
823 ctrl = false
824 alt = true
825 shift = false
826 if len(r.buffer) < 6 {
827 return Event{Invalid, 0, nil}
828 }
829 *sz = 6
830 char = r.buffer[5]
831 } else if r.buffer[4] == '1' && bytes.IndexByte([]byte{'0', '1', '2', '3', '4', '5', '6'}, r.buffer[5]) >= 0 {
832 ctrl = bytes.IndexByte([]byte{'3', '4', '5', '6'}, r.buffer[5]) >= 0
833 alt = true
834 shift = bytes.IndexByte([]byte{'0', '2', '4', '6'}, r.buffer[5]) >= 0
835 if len(r.buffer) < 7 {
836 return Event{Invalid, 0, nil}
837 }
838 *sz = 7
839 char = r.buffer[6]
840 }
841 ctrlShift := ctrl && shift
842 ctrlAlt := ctrl && alt
843 altShift := alt && shift
844 ctrlAltShift := ctrl && alt && shift
845 switch char {
846 case 'A':
847 if ctrlAltShift {
848 return Event{CtrlAltShiftUp, 0, nil}
849 }
850 if ctrlAlt {
851 return Event{CtrlAltUp, 0, nil}
852 }
853 if ctrlShift {
854 return Event{CtrlShiftUp, 0, nil}
855 }
856 if altShift {
857 return Event{AltShiftUp, 0, nil}
858 }
859 if ctrl {
860 return Event{CtrlUp, 0, nil}
861 }
862 if alt {
863 return Event{AltUp, 0, nil}
864 }
865 if shift {
866 return Event{ShiftUp, 0, nil}
867 }
868 return Event{Up, 0, nil}
869 case 'B':
870 if ctrlAltShift {
871 return Event{CtrlAltShiftDown, 0, nil}
872 }
873 if ctrlAlt {
874 return Event{CtrlAltDown, 0, nil}
875 }
876 if ctrlShift {
877 return Event{CtrlShiftDown, 0, nil}
878 }
879 if altShift {
880 return Event{AltShiftDown, 0, nil}
881 }
882 if ctrl {
883 return Event{CtrlDown, 0, nil}
884 }
885 if alt {
886 return Event{AltDown, 0, nil}
887 }
888 if shift {
889 return Event{ShiftDown, 0, nil}
890 }
891 return Event{Down, 0, nil}
892 case 'C':
893 if ctrlAltShift {
894 return Event{CtrlAltShiftRight, 0, nil}
895 }
896 if ctrlAlt {
897 return Event{CtrlAltRight, 0, nil}
898 }
899 if ctrlShift {
900 return Event{CtrlShiftRight, 0, nil}
901 }
902 if altShift {
903 return Event{AltShiftRight, 0, nil}
904 }
905 if ctrl {
906 return Event{CtrlRight, 0, nil}
907 }
908 if shift {
909 return Event{ShiftRight, 0, nil}
910 }
911 if alt {
912 return Event{AltRight, 0, nil}
913 }
914 return Event{Right, 0, nil}
915 case 'D':
916 if ctrlAltShift {
917 return Event{CtrlAltShiftLeft, 0, nil}
918 }
919 if ctrlAlt {
920 return Event{CtrlAltLeft, 0, nil}
921 }
922 if ctrlShift {
923 return Event{CtrlShiftLeft, 0, nil}
924 }
925 if altShift {
926 return Event{AltShiftLeft, 0, nil}
927 }
928 if ctrl {
929 return Event{CtrlLeft, 0, nil}
930 }
931 if alt {
932 return Event{AltLeft, 0, nil}
933 }
934 if shift {
935 return Event{ShiftLeft, 0, nil}
936 }
937 return Event{Left, 0, nil}
938 case 'H':
939 if ctrlAltShift {
940 return Event{CtrlAltShiftHome, 0, nil}
941 }
942 if ctrlAlt {
943 return Event{CtrlAltHome, 0, nil}
944 }
945 if ctrlShift {
946 return Event{CtrlShiftHome, 0, nil}
947 }
948 if altShift {
949 return Event{AltShiftHome, 0, nil}
950 }
951 if ctrl {
952 return Event{CtrlHome, 0, nil}
953 }
954 if alt {
955 return Event{AltHome, 0, nil}
956 }
957 if shift {
958 return Event{ShiftHome, 0, nil}
959 }
960 return Event{Home, 0, nil}
961 case 'F':
962 if ctrlAltShift {
963 return Event{CtrlAltShiftEnd, 0, nil}
964 }
965 if ctrlAlt {
966 return Event{CtrlAltEnd, 0, nil}
967 }
968 if ctrlShift {
969 return Event{CtrlShiftEnd, 0, nil}
970 }
971 if altShift {
972 return Event{AltShiftEnd, 0, nil}
973 }
974 if ctrl {
975 return Event{CtrlEnd, 0, nil}
976 }
977 if alt {
978 return Event{AltEnd, 0, nil}
979 }
980 if shift {
981 return Event{ShiftEnd, 0, nil}
982 }
983 return Event{End, 0, nil}
984 }
985 } // r.buffer[4]
986 } // r.buffer[3]
987 } // r.buffer[2]
988 } // r.buffer[2]
989 } // r.buffer[1]
990 rest := bytes.NewBuffer(r.buffer[1:])
991 c, size, err := rest.ReadRune()
992 if err == nil {
993 *sz = 1 + size
994 return AltKey(c)
995 }
996 return Event{Invalid, 0, nil}
997 }
998
999 // https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Mouse-Tracking
1000 func (r *LightRenderer) mouseSequence(sz *int) Event {
1001 // "\e[<0;0;0M"
1002 if len(r.buffer) < 9 || !r.mouse {
1003 return Event{Invalid, 0, nil}
1004 }
1005
1006 rest := r.buffer[*sz:]
1007 end := bytes.IndexAny(rest, "mM")
1008 if end == -1 {
1009 return Event{Invalid, 0, nil}
1010 }
1011
1012 elems := strings.SplitN(string(rest[:end]), ";", 3)
1013 if len(elems) != 3 {
1014 return Event{Invalid, 0, nil}
1015 }
1016
1017 t := atoi(elems[0], -1)
1018 x := atoi(elems[1], -1) - 1
1019 y := atoi(elems[2], -1) - 1 - r.yoffset
1020 if t < 0 || x < 0 {
1021 return Event{Invalid, 0, nil}
1022 }
1023 *sz += end + 1
1024
1025 down := rest[end] == 'M'
1026
1027 scroll := 0
1028 wheel := t >= 64
1029 if wheel {
1030 t -= 64
1031 // SGR wheel button codes: 64=up, 65=down, 66=left, 67=right
1032 switch t & 0b11 {
1033 case 0:
1034 scroll = 1
1035 case 1:
1036 scroll = -1
1037 }
1038 }
1039
1040 // middle := t & 0b1
1041 left := t&0b11 == 0
1042 ctrl := t&0b10000 > 0
1043 alt := t&0b01000 > 0
1044 shift := t&0b00100 > 0
1045 drag := t&0b100000 > 0 // 32
1046
1047 if wheel {
1048 return Event{Mouse, 0, &MouseEvent{y, x, scroll, false, false, false, ctrl, alt, shift}}
1049 }
1050
1051 double := false
1052 if down && !drag {
1053 now := time.Now()
1054 if !left { // Right double click is not allowed
1055 r.clicks = [][2]int{}
1056 } else if now.Sub(r.prevDownTime) < doubleClickDuration {
1057 r.clicks = append(r.clicks, [2]int{x, y})
1058 } else {
1059 r.clicks = [][2]int{{x, y}}
1060 }
1061 r.prevDownTime = now
1062 } else {
1063 n := len(r.clicks)
1064 if len(r.clicks) > 1 && r.clicks[n-2][0] == r.clicks[n-1][0] && r.clicks[n-2][1] == r.clicks[n-1][1] &&
1065 time.Since(r.prevDownTime) < doubleClickDuration {
1066 double = true
1067 if double {
1068 r.clicks = [][2]int{}
1069 }
1070 }
1071 }
1072 return Event{Mouse, 0, &MouseEvent{y, x, 0, left, down, double, ctrl, alt, shift}}
1073 }
1074
1075 func (r *LightRenderer) smcup() {
1076 r.flush()
1077 r.flushRaw("\x1b[?1049h")
1078 }
1079
1080 func (r *LightRenderer) rmcup() {
1081 r.flush()
1082 r.flushRaw("\x1b[?1049l")
1083 }
1084
1085 func (r *LightRenderer) Pause(clear bool) {
1086 r.disableModes()
1087 r.restoreTerminal()
1088 if clear {
1089 if r.fullscreen {
1090 r.rmcup()
1091 } else {
1092 r.smcup()
1093 r.csi("H")
1094 }
1095 r.flush()
1096 }
1097 }
1098
1099 func (r *LightRenderer) enableModes() {
1100 if r.mouse {
1101 r.csi("?1000h")
1102 r.csi("?1002h")
1103 r.csi("?1006h")
1104 }
1105 r.csi("?2004h") // Enable bracketed paste mode
1106 }
1107
1108 func (r *LightRenderer) disableMouse() {
1109 if r.mouse {
1110 r.csi("?1000l")
1111 r.csi("?1002l")
1112 r.csi("?1006l")
1113 }
1114 }
1115
1116 func (r *LightRenderer) disableModes() {
1117 r.disableMouse()
1118 // Put bracketed paste back the way we found it. A shell that runs fzf from
1119 // a line editor widget re-enables the mode only when the editor starts, so
1120 // forcing it off here would leave it off for the rest of the session.
1121 // Terminals that did not answer the query fall back to disabling, which is
1122 // what fzf has always done.
1123 if r.pasteWasSet != nil && *r.pasteWasSet {
1124 r.csi("?2004h")
1125 } else {
1126 r.csi("?2004l")
1127 }
1128 }
1129
1130 func (r *LightRenderer) Resume(clear bool, sigcont bool) {
1131 r.setupTerminal()
1132 // The programs that ran in the meantime may have left the terminal in an
1133 // arbitrary SGR state
1134 r.invalidateSGR()
1135 if clear {
1136 if r.fullscreen {
1137 r.smcup()
1138 } else {
1139 r.rmcup()
1140 }
1141 r.enableModes()
1142 r.flush()
1143 } else if sigcont && !r.fullscreen && r.mouse {
1144 // NOTE: SIGCONT (Coming back from CTRL-Z):
1145 // It's highly likely that the offset we obtained at the beginning is
1146 // no longer correct, so we simply disable mouse input.
1147 r.disableMouse()
1148 r.mouse = false
1149 }
1150 }
1151
1152 func (r *LightRenderer) Clear() {
1153 if r.fullscreen {
1154 r.csi("H")
1155 }
1156 r.origin()
1157 r.csi("J")
1158 r.flush()
1159 }
1160
1161 func (r *LightRenderer) NeedScrollbarRedraw() bool {
1162 return false
1163 }
1164
1165 func (r *LightRenderer) ShouldEmitResizeEvent() bool {
1166 return false
1167 }
1168
1169 func (r *LightRenderer) RefreshWindows(windows []Window) {
1170 r.flush()
1171 }
1172
1173 func (r *LightRenderer) Refresh() {
1174 r.updateTerminalSize()
1175 }
1176
1177 func (r *LightRenderer) Close() {
1178 if r.clearOnExit {
1179 if r.fullscreen {
1180 r.rmcup()
1181 } else {
1182 r.origin()
1183 // Erase our own area first, then step back onto the line the
1184 // prompt was on, so nothing on that line is touched
1185 r.csi("J")
1186 if r.upOneLine {
1187 r.csi("A")
1188 r.csi(fmt.Sprintf("%dG", r.xoffset+1))
1189 }
1190 }
1191 } else if !r.fullscreen {
1192 r.stderr("\x1b8") // DECRC: restore cursor position
1193 }
1194 if !r.showCursor {
1195 r.csi("?25h")
1196 }
1197 r.disableModes()
1198 r.flush()
1199 r.restoreTerminal()
1200 r.closePlatform()
1201 }
1202
1203 func (r *LightRenderer) Top() int {
1204 return r.yoffset
1205 }
1206
1207 func (r *LightRenderer) MaxX() int {
1208 return r.width
1209 }
1210
1211 func (r *LightRenderer) MaxY() int {
1212 if r.height == 0 {
1213 r.updateTerminalSize()
1214 }
1215 return r.height
1216 }
1217
1218 func (r *LightRenderer) NewWindow(top int, left int, width int, height int, windowType WindowType, borderStyle BorderStyle, erase bool) Window {
1219 width = max(0, width)
1220 height = max(0, height)
1221 w := &LightWindow{
1222 renderer: r,
1223 colored: r.theme.Colored,
1224 windowType: windowType,
1225 border: borderStyle,
1226 top: top,
1227 left: left,
1228 width: width,
1229 height: height,
1230 tabstop: r.tabstop,
1231 fg: colDefault,
1232 bg: colDefault}
1233 switch windowType {
1234 case WindowBase:
1235 w.fg = r.theme.Fg.Color
1236 w.bg = r.theme.Bg.Color
1237 case WindowList:
1238 w.fg = r.theme.ListFg.Color
1239 w.bg = r.theme.ListBg.Color
1240 case WindowInput:
1241 w.fg = r.theme.Input.Color
1242 w.bg = r.theme.InputBg.Color
1243 case WindowHeader:
1244 w.fg = r.theme.Header.Color
1245 w.bg = r.theme.HeaderBg.Color
1246 case WindowFooter:
1247 w.fg = r.theme.Footer.Color
1248 w.bg = r.theme.FooterBg.Color
1249 case WindowPreview:
1250 w.fg = r.theme.PreviewFg.Color
1251 w.bg = r.theme.PreviewBg.Color
1252 }
1253 if erase && !w.bg.IsDefault() && w.border.shape != BorderNone && w.height > 0 {
1254 // fzf --color bg:blue --border --padding 1,2
1255 w.Erase()
1256 }
1257 w.drawBorder(false)
1258 return w
1259 }
1260
1261 func (w *LightWindow) DrawBorder() {
1262 w.drawBorder(false)
1263 }
1264
1265 func (w *LightWindow) DrawHBorder() {
1266 w.drawBorder(true)
1267 }
1268
1269 // drawHLine fills row `row` with `line` between optional left/right caps.
1270 // A zero rune means "no cap"; caps are placed at the very edges of `w`.
1271 func (w *LightWindow) drawHLine(row int, line, leftCap, rightCap rune, color ColorPair) {
1272 w.Move(row, 0)
1273 hw := runeWidth(line)
1274 width := w.width
1275 if leftCap != 0 {
1276 w.CPrint(color, string(leftCap))
1277 width -= runeWidth(leftCap)
1278 }
1279 if rightCap != 0 {
1280 width -= runeWidth(rightCap)
1281 }
1282 if width < 0 {
1283 width = 0
1284 }
1285 inner := width / hw
1286 rem := width - inner*hw
1287 w.CPrint(color, repeat(line, inner)+repeat(' ', rem))
1288 if rightCap != 0 {
1289 w.CPrint(color, string(rightCap))
1290 }
1291 }
1292
1293 func (w *LightWindow) DrawHSeparator(row int, windowType WindowType, useBottom bool) {
1294 if w.height == 0 {
1295 return
1296 }
1297 shape := w.border.shape
1298 if shape == BorderNone {
1299 return
1300 }
1301 color := BorderColor(windowType)
1302 line := w.border.top
1303 if useBottom {
1304 line = w.border.bottom
1305 }
1306 var leftCap, rightCap rune
1307 if shape.HasLeft() {
1308 leftCap = w.border.leftMid
1309 }
1310 if shape.HasRight() {
1311 rightCap = w.border.rightMid
1312 }
1313 w.drawHLine(row, line, leftCap, rightCap, color)
1314 }
1315
1316 func (w *LightWindow) PaintSectionFrame(topContent, bottomContent int, windowType WindowType, edge SectionEdge) {
1317 if w.height == 0 || w.border.shape == BorderNone {
1318 return
1319 }
1320 color := BorderColor(windowType)
1321 shape := w.border.shape
1322 hasLeft := shape.HasLeft()
1323 hasRight := shape.HasRight()
1324 rightW := runeWidth(w.border.right)
1325 // Content rows: overpaint left/right verticals + their 1-char margin.
1326 for row := topContent; row <= bottomContent; row++ {
1327 if hasLeft {
1328 w.Move(row, 0)
1329 w.CPrint(color, string(w.border.left)+" ")
1330 }
1331 if hasRight {
1332 w.Move(row, w.width-rightW-1)
1333 w.CPrint(color, " "+string(w.border.right))
1334 }
1335 }
1336 if edge == SectionEdgeTop && shape.HasTop() {
1337 var leftCap, rightCap rune
1338 if hasLeft {
1339 leftCap = w.border.topLeft
1340 }
1341 if hasRight {
1342 rightCap = w.border.topRight
1343 }
1344 w.drawHLine(0, w.border.top, leftCap, rightCap, color)
1345 }
1346 if edge == SectionEdgeBottom && shape.HasBottom() {
1347 var leftCap, rightCap rune
1348 if hasLeft {
1349 leftCap = w.border.bottomLeft
1350 }
1351 if hasRight {
1352 rightCap = w.border.bottomRight
1353 }
1354 w.drawHLine(w.height-1, w.border.bottom, leftCap, rightCap, color)
1355 }
1356 }
1357
1358 func (w *LightWindow) drawBorder(onlyHorizontal bool) {
1359 if w.height == 0 {
1360 return
1361 }
1362 shape := w.border.shape
1363 if shape == BorderNone {
1364 return
1365 }
1366 color := BorderColor(w.windowType)
1367 hasLeft := shape.HasLeft()
1368 hasRight := shape.HasRight()
1369
1370 if shape.HasTop() {
1371 var leftCap, rightCap rune
1372 if hasLeft {
1373 leftCap = w.border.topLeft
1374 }
1375 if hasRight {
1376 rightCap = w.border.topRight
1377 }
1378 w.drawHLine(0, w.border.top, leftCap, rightCap, color)
1379 }
1380 if !onlyHorizontal && (hasLeft || hasRight) {
1381 vw := runeWidth(w.border.left)
1382 for y := 0; y < w.height; y++ {
1383 // Corner rows are already painted by drawHLine above / below.
1384 if (y == 0 && shape.HasTop()) || (y == w.height-1 && shape.HasBottom()) {
1385 continue
1386 }
1387 if hasLeft {
1388 w.Move(y, 0)
1389 w.CPrint(color, string(w.border.left)+" ")
1390 }
1391 if hasRight {
1392 w.Move(y, w.width-vw-1)
1393 w.CPrint(color, " "+string(w.border.right))
1394 }
1395 }
1396 }
1397 if shape.HasBottom() {
1398 var leftCap, rightCap rune
1399 if hasLeft {
1400 leftCap = w.border.bottomLeft
1401 }
1402 if hasRight {
1403 rightCap = w.border.bottomRight
1404 }
1405 w.drawHLine(w.height-1, w.border.bottom, leftCap, rightCap, color)
1406 }
1407 }
1408
1409 func (w *LightWindow) stderrInternal(str string, allowNLCR bool, resetCode string) {
1410 w.renderer.stderrInternal(str, allowNLCR, resetCode)
1411 }
1412
1413 func (w *LightWindow) Top() int {
1414 return w.top
1415 }
1416
1417 func (w *LightWindow) Left() int {
1418 return w.left
1419 }
1420
1421 func (w *LightWindow) Width() int {
1422 return w.width
1423 }
1424
1425 func (w *LightWindow) Height() int {
1426 return w.height
1427 }
1428
1429 func (w *LightWindow) Refresh() {
1430 }
1431
1432 func (w *LightWindow) X() int {
1433 return w.posx
1434 }
1435
1436 func (w *LightWindow) Y() int {
1437 return w.posy
1438 }
1439
1440 func (w *LightWindow) EncloseX(x int) bool {
1441 return x >= w.left && x < (w.left+w.width)
1442 }
1443
1444 func (w *LightWindow) EncloseY(y int) bool {
1445 return y >= w.top && y < (w.top+w.height)
1446 }
1447
1448 func (w *LightWindow) Enclose(y int, x int) bool {
1449 return w.EncloseX(x) && w.EncloseY(y)
1450 }
1451
1452 func (w *LightWindow) Move(y int, x int) {
1453 w.posx = x
1454 w.posy = y
1455
1456 w.renderer.move(w.Top()+y, w.Left()+x)
1457 }
1458
1459 func (w *LightWindow) MoveAndClear(y int, x int) {
1460 w.Move(y, x)
1461 // We should not delete preview window on the right
1462 // csi("K")
1463 w.Print(repeat(' ', w.width-x))
1464 w.Move(y, x)
1465 }
1466
1467 func attrCodes(attr Attr) []string {
1468 codes := []string{}
1469 if (attr & AttrClear) > 0 {
1470 return codes
1471 }
1472 if (attr&Bold) > 0 || (attr&BoldForce) > 0 {
1473 codes = append(codes, "1")
1474 }
1475 if (attr & Dim) > 0 {
1476 codes = append(codes, "2")
1477 }
1478 if (attr & Italic) > 0 {
1479 codes = append(codes, "3")
1480 }
1481 if (attr & Underline) > 0 {
1482 switch attr.UnderlineStyle() {
1483 case UlStyleDouble:
1484 codes = append(codes, "4:2")
1485 case UlStyleCurly:
1486 codes = append(codes, "4:3")
1487 case UlStyleDotted:
1488 codes = append(codes, "4:4")
1489 case UlStyleDashed:
1490 codes = append(codes, "4:5")
1491 default:
1492 codes = append(codes, "4")
1493 }
1494 }
1495 if (attr & Blink) > 0 {
1496 codes = append(codes, "5")
1497 }
1498 if (attr & Reverse) > 0 {
1499 codes = append(codes, "7")
1500 }
1501 if (attr & StrikeThrough) > 0 {
1502 codes = append(codes, "9")
1503 }
1504 return codes
1505 }
1506
1507 func colorCodes(fg Color, bg Color) []string {
1508 codes := []string{}
1509 appendCode := func(c Color, offset int) {
1510 if c == colDefault {
1511 return
1512 }
1513 if c.is24() {
1514 r := (c >> 16) & 0xff
1515 g := (c >> 8) & 0xff
1516 b := (c) & 0xff
1517 codes = append(codes, fmt.Sprintf("%d;2;%d;%d;%d", 38+offset, r, g, b))
1518 } else if c >= colBlack && c <= colWhite {
1519 codes = append(codes, fmt.Sprintf("%d", int(c)+30+offset))
1520 } else if c > colWhite && c < 16 {
1521 codes = append(codes, fmt.Sprintf("%d", int(c)+90+offset-8))
1522 } else if c >= 16 && c < 256 {
1523 codes = append(codes, fmt.Sprintf("%d;5;%d", 38+offset, c))
1524 }
1525 }
1526 appendCode(fg, 0)
1527 appendCode(bg, 10)
1528 return codes
1529 }
1530
1531 func ulColorCode(c Color) string {
1532 if c == colDefault {
1533 return ""
1534 }
1535 if c.is24() {
1536 r := (c >> 16) & 0xff
1537 g := (c >> 8) & 0xff
1538 b := (c) & 0xff
1539 return fmt.Sprintf("58;2;%d;%d;%d", r, g, b)
1540 }
1541 if c >= 0 && c < 256 {
1542 return fmt.Sprintf("58;5;%d", c)
1543 }
1544 return ""
1545 }
1546
1547 // csiColor builds the SGR sequence for the given colors and attributes
1548 // without emitting it. The sequence starts with a reset parameter, so it
1549 // fully determines the SGR state on its own.
1550 func (w *LightWindow) csiColor(fg Color, bg Color, ul Color, attr Attr) (bool, string) {
1551 codes := append(attrCodes(attr), colorCodes(fg, bg)...)
1552 if ulCode := ulColorCode(ul); ulCode != "" {
1553 codes = append(codes, ulCode)
1554 }
1555 if len(codes) == 0 {
1556 return false, "\x1b[0m"
1557 }
1558 return true, "\x1b[;" + strings.Join(codes, ";") + "m"
1559 }
1560
1561 func (w *LightWindow) Print(text string) {
1562 w.cprint2(colDefault, w.bg, AttrRegular, text)
1563 }
1564
1565 func cleanse(str string) string {
1566 return strings.ReplaceAll(str, "\x1b", "")
1567 }
1568
1569 func (w *LightWindow) CPrint(pair ColorPair, text string) {
1570 _, code := w.csiColor(pair.Fg(), pair.Bg(), pair.Ul(), pair.Attr())
1571 w.renderer.setSGR(code)
1572 w.stderrInternal(cleanse(text), false, code)
1573 }
1574
1575 func (w *LightWindow) cprint2(fg Color, bg Color, attr Attr, text string) {
1576 _, code := w.csiColor(fg, bg, colDefault, attr)
1577 w.renderer.setSGR(code)
1578 w.stderrInternal(cleanse(text), false, code)
1579 }
1580
1581 func (w *LightWindow) fill(str string, resetCode string) FillReturn {
1582 allLines := strings.Split(str, "\n")
1583 for i, line := range allLines {
1584 lines := WrapLine(line, w.posx, w.width, w.tabstop, w.wrapSignWidth)
1585 for j, wl := range lines {
1586 if w.posx < w.width {
1587 w.stderrInternal(wl.Text, false, resetCode)
1588 w.posx += wl.DisplayWidth
1589 }
1590
1591 // Wrap line
1592 if j < len(lines)-1 || i < len(allLines)-1 {
1593 if w.posy+1 >= w.height {
1594 return FillSuspend
1595 }
1596 w.MoveAndClear(w.posy, w.posx)
1597 w.Move(w.posy+1, 0)
1598 w.renderer.setSGR(resetCode)
1599 if len(lines) > 1 {
1600 sign := w.wrapSign
1601 width := w.wrapSignWidth
1602 if width > w.width {
1603 runes, truncatedWidth := util.Truncate(w.wrapSign, w.width)
1604 sign = string(runes)
1605 width = truncatedWidth
1606 }
1607 w.stderrInternal(DIM+sign, false, resetCode)
1608 w.renderer.invalidateSGR()
1609 w.renderer.setSGR(resetCode)
1610 w.Move(w.posy, width)
1611 }
1612 }
1613 }
1614 }
1615 if w.posx >= w.Width() {
1616 if w.posy+1 >= w.height {
1617 return FillSuspend
1618 }
1619 w.Move(w.posy+1, 0)
1620 w.renderer.setSGR(resetCode)
1621 return FillNextLine
1622 }
1623 return FillContinue
1624 }
1625
1626 func (w *LightWindow) setBg() string {
1627 // The plain reset code for the default background is still required to
1628 // clear the dim attribute after ␍ in the preview window
1629 // e.g. printf "foo\rbar" | fzf --ansi --preview 'printf "foo\rbar"'
1630 _, code := w.csiColor(colDefault, w.bg, colDefault, AttrRegular)
1631 w.renderer.setSGR(code)
1632 return code
1633 }
1634
1635 func (w *LightWindow) LinkBegin(uri string, params string) {
1636 w.renderer.queued.WriteString("\x1b]8;" + params + ";" + uri + "\x1b\\")
1637 }
1638
1639 func (w *LightWindow) LinkEnd() {
1640 w.renderer.queued.WriteString("\x1b]8;;\x1b\\")
1641 }
1642
1643 func (w *LightWindow) Fill(text string) FillReturn {
1644 w.Move(w.posy, w.posx)
1645 code := w.setBg()
1646 return w.fill(text, code)
1647 }
1648
1649 func (w *LightWindow) CFill(fg Color, bg Color, ul Color, attr Attr, text string) FillReturn {
1650 w.Move(w.posy, w.posx)
1651 if fg == colDefault {
1652 fg = w.fg
1653 }
1654 if bg == colDefault {
1655 bg = w.bg
1656 }
1657 if hasColors, resetCode := w.csiColor(fg, bg, ul, attr); hasColors {
1658 w.renderer.setSGR(resetCode)
1659 return w.fill(text, resetCode)
1660 }
1661 return w.fill(text, w.setBg())
1662 }
1663
1664 func (w *LightWindow) FinishFill() {
1665 if w.posy < w.height {
1666 w.MoveAndClear(w.posy, w.posx)
1667 }
1668 for y := w.posy + 1; y < w.height; y++ {
1669 w.MoveAndClear(y, 0)
1670 }
1671 }
1672
1673 func (w *LightWindow) Erase() {
1674 w.DrawBorder()
1675 w.Move(0, 0)
1676 w.FinishFill()
1677 w.Move(0, 0)
1678 }
1679
1680 func (w *LightWindow) EraseMaybe() bool {
1681 return false
1682 }
1683
1684 func (w *LightWindow) SetWrapSign(sign string, width int) {
1685 w.wrapSign = sign
1686 w.wrapSignWidth = width
1687 }
1688
1689 func (r *LightRenderer) HideCursor() {
1690 r.showCursor = false
1691 r.csi("?25l")
1692 }
1693
1694 func (r *LightRenderer) ShowCursor() {
1695 r.showCursor = true
1696 r.csi("?25h")
1697 }