light.go
This file
Path
src/tui/light.go
1,877 lines · 46.6 KiB · Go
Last changed by
Fix panic on a read error during the second-chance readJunegunn Choibefore adoption33a3456
History of this fileTake it
1package tui23import (4 "bytes"5 "errors"6 "fmt"7 "os"8 "regexp"9 "strconv"10 "strings"11 "sync"12 "time"13 "unicode/utf8"1415 "github.com/junegunn/fzf/src/util"1617 "golang.org/x/term"18)1920const (21 defaultWidth = 8022 defaultHeight = 242324 defaultEscDelay = 10025 escPollInterval = 526 offsetPollTries = 1027 queryTimeout = 500 * time.Millisecond28 maxInputBuffer = 1024 * 102429 escapeLookback = 25630)3132const DefaultTtyDevice string = "/dev/tty"3334var offsetRegexp = regexp.MustCompile("\x00?\x1b\\[([0-9]+);([0-9]+)R")35var offsetRegexpBegin = regexp.MustCompile("^\x1b\\[[0-9]+;[0-9]+R")3637// DECRPM reply to the DECRQM query for bracketed paste mode. Ps is 1 or 3 when38// the mode was already set, 2 or 4 when reset, 0 when the terminal does not39// recognize the mode.40var pasteModeRegexp = regexp.MustCompile("\x00?\x1b\\[\\?2004;([0-4])\\$y")41var pasteModeRegexpBegin = regexp.MustCompile("^\x1b\\[\\?2004;[0-4]\\$y")4243// A report to ask the terminal for, and the reply to recognize it by.44type termQuery struct {45 seq string46 reply *regexp.Regexp47}4849var offsetQuery = termQuery{"6n", offsetRegexp}50var pasteModeQuery = termQuery{"?2004$p", pasteModeRegexp}5152// 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 last54// and also ends the wait: every terminal fzf supports answers it, so once its55// reply arrives, a query still unanswered is one the terminal does not know56// rather than one we stopped waiting for too early.57//58// Terminals that don't support the paste mode query (DECRQM) might leave59// 'p' on the screen. To handle such cases, we query the position before and60// after it, compare them, and clean the artifact if they don't match.61//62// Reference: https://ansicode.eversources.app/en/sequence/decrqm63var startupQueries = []termQuery{offsetQuery, pasteModeQuery, offsetQuery}6465func (r *LightRenderer) Bell() {66 r.flushRaw("\a")67}6869func (r *LightRenderer) PassThrough(str string) {70 r.queued.WriteString("\x1b7" + str + "\x1b8")71 r.invalidateSGR()72}7374func (r *LightRenderer) stderr(str string) {75 r.stderrInternal(str, true, "")76}7778const DIM string = "\x1b[2m"79const CR string = DIM + "␍"80const LF string = DIM + "␊"8182type getCharResult int8384const (85 getCharSuccess getCharResult = iota86 getCharError87 getCharCancelled88)8990func (r getCharResult) ok() bool {91 return r == getCharSuccess92}9394func (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 <= 0x9F101 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}116117func (r *LightRenderer) csi(code string) string {118 fullcode := "\x1b[" + code119 r.stderr(fullcode)120 return fullcode121}122123// setSGR emits the given SGR sequence only when the terminal is not already124// 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 of126// r.sgr never matches a sequence, so the first update after Init, Resume, or127// invalidateSGR is always emitted.128func (r *LightRenderer) setSGR(code string) {129 if code != r.sgr {130 r.stderr(code)131 r.sgr = code132 }133}134135// invalidateSGR marks the terminal SGR state as unknown, e.g. after raw136// output that may have changed it behind the renderer's back.137func (r *LightRenderer) invalidateSGR() {138 r.sgr = ""139}140141func (r *LightRenderer) flush() {142 if r.queued.Len() > 0 {143 // Leave the terminal in the default SGR state between frames144 r.setSGR("\x1b[0m")145 // Wrap the frame in synchronized update mode (2026) so that the146 // terminal applies it atomically. Terminals without support ignore147 // 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}157158func (r *LightRenderer) flushRaw(sequence string) {159 fmt.Fprint(r.ttyout, sequence)160}161162// Light renderer163type LightRenderer struct {164 theme *ColorTheme165 mouse bool166 forceBlack bool167 clearOnExit bool168 prevDownTime time.Time169 clicks [][2]int170 ttyin *os.File171 ttyout *os.File172 cancel func()173 buffer []byte174 origState *term.State175 width int176 height int177 yoffset int178 xoffset int179 tabstop int180 escDelay int181 fullscreen bool182 upOneLine bool183 queued strings.Builder184 sgr string185 y int186 x int187 maxHeightFunc func(int) int188 showCursor bool189 mutex sync.Mutex190191 // Whether bracketed paste was already on before we enabled it. Nil when192 // the terminal did not answer the query.193 pasteWasSet *bool194195 // Windows only196 ttyinChannel chan byte197 inHandle uintptr198 outHandle uintptr199 origStateInput uint32200 origStateOutput uint32201}202203type LightWindow struct {204 renderer *LightRenderer205 colored bool206 windowType WindowType207 border BorderStyle208 top int209 left int210 width int211 height int212 posx int213 posy int214 tabstop int215 fg Color216 bg Color217 wrapSign string218 wrapSignWidth int219}220221func 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.Stderr225 }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, nil240}241242func repeat(r rune, times int) string {243 if times > 0 {244 return strings.Repeat(string(r), times)245 }246 return ""247}248249func atoi(s string, defaultValue int) int {250 value, err := strconv.Atoi(s)251 if err != nil {252 return defaultValue253 }254 return value255}256257func (r *LightRenderer) Init() error {258 r.escDelay = atoi(os.Getenv("ESCDELAY"), defaultEscDelay)259260 if err := r.initPlatform(); err != nil {261 return err262 }263 r.updateTerminalSize()264265 if r.fullscreen {266 r.smcup()267 }268269 // Ask everything in one round trip, before the offset is needed.270 y, x, pasteWasSet := r.queryStartup()271 r.pasteWasSet = pasteWasSet272273 if !r.fullscreen {274 r.mouse = r.mouse && y >= 0275 // When --no-clear is used for repetitive relaunching, there is a small276 // time frame between fzf processes where the user keystrokes are not277 // captured by either of fzf process which can cause x offset to be278 // increased and we're left with unwanted extra new line.279 if x > 0 && r.clearOnExit {280 r.upOneLine = true281 r.xoffset = x282 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 }293294 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 position300 }301 if !r.fullscreen && r.mouse {302 r.yoffset, _ = r.findOffset()303 }304 return nil305}306307func (r *LightRenderer) Resize(maxHeightFunc func(int) int) {308 r.maxHeightFunc = maxHeightFunc309}310311func (r *LightRenderer) makeSpace() {312 r.stderr("\n")313 r.csi("G")314}315316func (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 = y328 r.x = x329}330331func (r *LightRenderer) origin() {332 r.move(0, 0)333}334335func getEnv(name string, defaultValue int) int {336 env := os.Getenv(name)337 if len(env) == 0 {338 return defaultValue339 }340 return atoi(env, defaultValue)341}342343// Bytes of a CSI sequence: parameter and intermediate bytes continue it, a344// final byte ends it. Order is not enforced. Strictness would only make fzf345// give up on a sequence it could have framed.346//347// https://vt100.net/emu/dec_ansi_parser348func csiContinues(b byte) bool { return b >= 0x20 && b <= 0x3f }349func csiFinal(b byte) bool { return b >= 0x40 && b <= 0x7e }350351// csiEnd returns the length of the CSI or SS3 sequence at the start of the352// buffer, 0 if it has no final byte yet, or -1 if it is malformed.353func csiEnd(buffer []byte) int {354 digits := true355 for i := 2; i < len(buffer); i++ {356 b := buffer[i]357 // rxvt ends keys with $ after at least one digit, as in \e[7$ for358 // SHIFT-HOME and \e[23$ for SHIFT-F11. Elsewhere $ is an intermediate byte.359 if csiFinal(b) || b == '$' && digits && i > 2 {360 return i + 1361 }362 if !csiContinues(b) {363 return -1364 }365 digits = digits && b >= '0' && b <= '9'366 }367 return 0368}369370// stringEnd returns the length of the string sequence (DCS, OSC or APC) at the371// start of the buffer, or 0 while nothing has ended it. A terminator is372// included, an ESC that introduces another sequence is not.373func stringEnd(buffer []byte) int {374 if len(buffer) < 2 {375 return 0376 }377 // Every one of them ends with ST. BEL ends an OSC as well, because xterm has378 // always allowed it, but stopping at a BEL inside a DCS or APC payload would379 // frame only its first half and leave the rest to be typed into the query.380 bel := buffer[1] == ']'381 for i := 2; i < len(buffer); i++ {382 switch buffer[i] {383 case '\a':384 if bel {385 return i + 1386 }387 case Esc.Byte():388 if i+1 == len(buffer) {389 return 0 // ST may still be arriving390 }391 if buffer[i+1] == '\\' {392 return i + 2393 }394 // Any other ESC ends the string and introduces a sequence of its395 // own, so frame only what precedes it and leave the ESC to be396 // parsed again. Scanning past it would swallow that sequence too.397 return i398 }399 }400 return 0401}402403// rxvtKeyEnd reports whether the byte ends a key such as \e[7~ for Home.404// rxvt marks modifiers with the final byte: $ for SHIFT, ^ for CTRL, @ for both.405func rxvtKeyEnd(b byte) bool {406 return b == '~' || b == '$' || b == '^' || b == '@'407}408409// csiIntroducer reports whether the byte after ESC starts a sequence that is410// framed by a final byte. The parser routes CSI and SS3 through the same411// parameterized subcases, so both are framed by csiEnd.412func csiIntroducer(b byte) bool {413 return b == '[' || b == 'O'414}415416// stringIntroducer reports whether the byte after ESC starts a string sequence.417// Only the three that terminals reply with: OSC for colors, title and clipboard,418// DCS for XTVERSION, DECRQSS and XTGETTCAP, APC for Kitty graphics. Nothing419// sends SOS or PM.420func stringIntroducer(b byte) bool {421 switch b {422 case 'P', ']', '_':423 return true424 }425 return false426}427428// stringReply reports whether a framed string sequence starts the way a429// terminal's reply does. Its introducer is also ALT-], ALT-P or ALT-_, and typed430// text after one, ended by CTRL-G or another key, frames like a reply when it431// all arrives in one read.432func stringReply(buffer []byte) bool {433 payload := buffer[2:]434 switch buffer[1] {435 case ']': // Ps ; ...436 i := 0437 for i < len(payload) && payload[i] >= '0' && payload[i] <= '9' {438 i++439 }440 return i > 0 && i < len(payload) && payload[i] == ';'441 case 'P': // >| or !| for the version, [01]$r or [01]+r for settings442 if len(payload) < 2 {443 return false444 }445 if payload[1] == '|' {446 return payload[0] == '>' || payload[0] == '!'447 }448 return len(payload) >= 3 && (payload[0] == '0' || payload[0] == '1') &&449 (payload[1] == '$' || payload[1] == '+') && payload[2] == 'r'450 case '_': // G, then key=value451 return len(payload) >= 3 && payload[0] == 'G' &&452 (payload[1] >= 'a' && payload[1] <= 'z' || payload[1] >= 'A' && payload[1] <= 'Z') &&453 payload[2] == '='454 }455 return false456}457458// stillArriving reports whether the CSI or SS3 sequence at the start of the459// buffer may still be completed by more input. It must be the only one in the buffer:460// whatever follows it, another sequence or a byte that ended it, means it is not461// waiting for anything.462func stillArriving(buffer []byte) bool {463 return bytes.IndexByte(buffer[1:], Esc.Byte()) < 0 && incompleteEscape(buffer)464}465466// incompleteEscape reports whether the buffer ends in a CSI or SS3 sequence that467// has not been terminated yet. The read loop keeps waiting while it does, so a468// fragment reaches the parser only once that wait has run out. A string sequence469// is never waited for, because its introducer is also ALT-], ALT-P or ALT-_.470func incompleteEscape(buffer []byte) bool {471 // Only the tail can hold a sequence still arriving. This runs once per byte472 // read, so scanning all of a large paste would make the read quadratic.473 tail := buffer474 if len(tail) > escapeLookback {475 tail = tail[len(tail)-escapeLookback:]476 }477 start := bytes.LastIndexByte(tail, Esc.Byte())478 if start < 0 || len(tail)-start < 2 {479 return false480 }481 // SS3 is judged like CSI: declaring it finished after one byte made the482 // parser give up on a split \eO1;5A. A malformed sequence is not waited for,483 // as nothing can complete it.484 return csiIntroducer(tail[start+1]) && csiEnd(tail[start:]) == 0485}486487func (r *LightRenderer) getBytes(cancellable bool) ([]byte, getCharResult, error) {488 return r.getBytesInternal(cancellable, r.buffer, false)489}490491func (r *LightRenderer) getBytesInternal(cancellable bool, buffer []byte, nonblock bool) ([]byte, getCharResult, error) {492 c, result := r.getch(cancellable, nonblock)493 if result == getCharCancelled {494 return buffer, getCharCancelled, nil495 }496 if !nonblock && !result.ok() {497 r.Close()498 return nil, getCharError, errors.New("failed to read " + DefaultTtyDevice)499 }500501 retries := 0502 if c == Esc.Int() || nonblock {503 retries = r.escDelay / escPollInterval504 }505 // A non-blocking read that found nothing has no byte to record. Recording506 // one would put a NUL in the middle of a reply still being assembled.507 if result.ok() {508 buffer = append(buffer, byte(c))509 }510511 pc := c512 for {513 c, result = r.getch(false, true)514 if !result.ok() {515 if retries > 0 {516 retries--517 time.Sleep(escPollInterval * time.Millisecond)518 continue519 }520 break521 } else if c == Esc.Int() && pc != c {522 retries = r.escDelay / escPollInterval523 } else {524 retries = 0525 }526 buffer = append(buffer, byte(c))527 // Keep waiting while a sequence is still arriving. Dropping the budget528 // after every byte left fzf parsing whatever the read happened to end on.529 // Past the introducer this is not the ESC key, so the wait costs no530 // Escape latency and ESCDELAY=0 must not reduce it to nothing.531 if retries == 0 && incompleteEscape(buffer) {532 retries = max(r.escDelay, defaultEscDelay) / escPollInterval533 }534 pc = c535536 // This should never happen under normal conditions,537 // so terminate fzf immediately.538 if len(buffer) > maxInputBuffer {539 r.Close()540 return nil, getCharError, fmt.Errorf("input buffer overflow (%d): %v", len(buffer), buffer)541 }542 }543544 return buffer, getCharSuccess, nil545}546547func (r *LightRenderer) GetChar(cancellable bool) Event {548 var err error549 var result getCharResult550 if len(r.buffer) == 0 {551 r.buffer, result, err = r.getBytes(cancellable)552 if err != nil {553 return Event{Fatal, 0, nil}554 }555 if result == getCharCancelled {556 return Event{Invalid, 0, nil}557 }558 }559 if len(r.buffer) == 0 {560 return Event{Fatal, 0, nil}561 }562563 sz := 1564 defer func() {565 r.buffer = r.buffer[sz:]566 }()567568 switch r.buffer[0] {569 case CtrlC.Byte():570 return Event{CtrlC, 0, nil}571 case CtrlG.Byte():572 return Event{CtrlG, 0, nil}573 case CtrlQ.Byte():574 return Event{CtrlQ, 0, nil}575 case 127:576 return Event{Backspace, 0, nil}577 case 8:578 return Event{CtrlBackspace, 0, nil}579 case 0:580 return Event{CtrlSpace, 0, nil}581 case 28:582 return Event{CtrlBackSlash, 0, nil}583 case 29:584 return Event{CtrlRightBracket, 0, nil}585 case 30:586 return Event{CtrlCaret, 0, nil}587 case 31:588 return Event{CtrlSlash, 0, nil}589 case Esc.Byte():590 ev := r.escSequence(&sz)591 // Second chance, but only for an unfinished sequence. Re-reading592 // otherwise blocks until the next keystroke, holding back whatever593 // follows in the buffer.594 if ev.Type == Invalid && stillArriving(r.buffer) {595 waited := len(r.buffer)596 var buffer []byte597 buffer, result, err = r.getBytes(true)598 if err != nil {599 return Event{Fatal, 0, nil}600 }601 r.buffer = buffer602 if result == getCharCancelled {603 return Event{Invalid, 0, nil}604 }605606 ev = r.escSequence(&sz)607 // This read has no time limit, so what it returned may be the next608 // keystroke rather than the rest of the sequence. Never drop it.609 if ev.Type == Invalid && sz > waited {610 sz = waited611 }612 }613 return ev614 }615616 // CTRL-A ~ CTRL-Z617 if r.buffer[0] <= CtrlZ.Byte() {618 return Event{EventType(r.buffer[0]), 0, nil}619 }620 char, rsz := utf8.DecodeRune(r.buffer)621 if char == utf8.RuneError {622 return Event{Esc, 0, nil}623 }624 sz = rsz625 return Event{Rune, char, nil}626}627628func (r *LightRenderer) CancelGetChar() {629 r.mutex.Lock()630 if r.cancel != nil {631 r.cancel()632 r.cancel = nil633 }634 r.mutex.Unlock()635}636637func (r *LightRenderer) setCancel(f func()) {638 r.mutex.Lock()639 r.cancel = f640 r.mutex.Unlock()641}642643// escSequence parses an escape sequence, then checks a CSI or SS3 result644// against its frame. parseEscSequence can stop after a few bytes, and consuming645// only those would leave the rest to be typed into the query. Complete646// sequences it does not recognize are dropped there, unless they could be an647// ALT key followed by typed text.648func (r *LightRenderer) escSequence(sz *int) Event {649 ev := r.parseEscSequence(sz)650 if len(r.buffer) < 3 || !csiIntroducer(r.buffer[1]) {651 return ev652 }653 // A frame missing its final byte may still be arriving654 end := csiEnd(r.buffer)655 if end <= 0 {656 return ev657 }658 // The parser can also set the size before checking the bytes and then give659 // up, counting typed input past the frame, as in \e[3;1u followed by ~660 if ev.Type == Invalid && *sz > end {661 *sz = end662 }663 // Four bytes or fewer could be ALT-[ or ALT-O and typed text, and rxvt sends664 // keys of that size fzf does not know, such as \e[3^ for CTRL-DELETE665 if end <= 4 {666 return ev667 }668 // A key matched on a prefix, such as Home for \e[70;5u, or a sequence given669 // up on partway670 if end > *sz {671 *sz = end672 return Event{Invalid, 0, nil}673 }674 return ev675}676677func (r *LightRenderer) parseEscSequence(sz *int) Event {678 if len(r.buffer) < 2 {679 return Event{Esc, 0, nil}680 }681682 loc := offsetRegexpBegin.FindIndex(r.buffer)683 if loc != nil && loc[0] == 0 {684 *sz = loc[1]685 return Event{Invalid, 0, nil}686 }687688 loc = pasteModeRegexpBegin.FindIndex(r.buffer)689 if loc != nil && loc[0] == 0 {690 *sz = loc[1]691 return Event{Invalid, 0, nil}692 }693694 *sz = 2695 if r.buffer[1] == 8 {696 return Event{CtrlAltBackspace, 0, nil}697 }698 if r.buffer[1] >= 1 && r.buffer[1] <= 'z'-'a'+1 {699 return CtrlAltKey(rune(r.buffer[1] + 'a' - 1))700 }701 alt := false702 if len(r.buffer) > 2 && r.buffer[1] == Esc.Byte() {703 r.buffer = r.buffer[1:]704 alt = true705 }706 switch r.buffer[1] {707 case Esc.Byte():708 return Event{Esc, 0, nil}709 case 127:710 return Event{AltBackspace, 0, nil}711 case '[', 'O':712 if len(r.buffer) < 3 {713 return Event{Invalid, 0, nil}714 }715 *sz = 3716 switch r.buffer[2] {717 case 'D':718 if alt {719 return Event{AltLeft, 0, nil}720 }721 return Event{Left, 0, nil}722 case 'C':723 if alt {724 // Ugh..725 return Event{AltRight, 0, nil}726 }727 return Event{Right, 0, nil}728 case 'B':729 if alt {730 return Event{AltDown, 0, nil}731 }732 return Event{Down, 0, nil}733 case 'A':734 if alt {735 return Event{AltUp, 0, nil}736 }737 return Event{Up, 0, nil}738 case 'Z':739 return Event{ShiftTab, 0, nil}740 case 'H':741 return Event{Home, 0, nil}742 case 'F':743 return Event{End, 0, nil}744 case '<':745 return r.mouseSequence(sz)746 case 'P':747 return Event{F1, 0, nil}748 case 'Q':749 return Event{F2, 0, nil}750 case 'R':751 return Event{F3, 0, nil}752 case 'S':753 return Event{F4, 0, nil}754 case '1', '2', '3', '4', '5', '6', '7', '8':755 if len(r.buffer) < 4 {756 return Event{Invalid, 0, nil}757 }758 // A byte that cannot continue the sequence, such as Enter after759 // ALT-[ and a digit, is a key of its own760 if csiEnd(r.buffer) < 0 {761 break762 }763 *sz = 4764 switch r.buffer[2] {765 case '2':766 if r.buffer[3] == '~' {767 return Event{Insert, 0, nil}768 }769 if len(r.buffer) > 4 && r.buffer[4] == '~' {770 *sz = 5771 switch r.buffer[3] {772 case '0':773 return Event{F9, 0, nil}774 case '1':775 return Event{F10, 0, nil}776 case '3':777 return Event{F11, 0, nil}778 case '4':779 return Event{F12, 0, nil}780 }781 }782 // Bracketed paste mode: \e[200~ ... \e[201~783 if len(r.buffer) > 5 && r.buffer[3] == '0' && (r.buffer[4] == '0' || r.buffer[4] == '1') && r.buffer[5] == '~' {784 *sz = 6785 if r.buffer[4] == '0' {786 return Event{BracketedPasteBegin, 0, nil}787 }788 return Event{BracketedPasteEnd, 0, nil}789 }790 return Event{Invalid, 0, nil} // INS791 case '3':792 if r.buffer[3] == '~' {793 return Event{Delete, 0, nil}794 }795 if len(r.buffer) > 6 && r.buffer[6] == '~' && r.buffer[4] == '1' {796 *sz = 7797 switch r.buffer[5] {798 case '0':799 return Event{AltShiftDelete, 0, nil}800 case '1':801 return Event{AltDelete, 0, nil}802 case '2':803 return Event{AltShiftDelete, 0, nil}804 case '3':805 return Event{CtrlAltDelete, 0, nil}806 case '4':807 return Event{CtrlAltShiftDelete, 0, nil}808 case '5':809 return Event{CtrlAltDelete, 0, nil}810 case '6':811 return Event{CtrlAltShiftDelete, 0, nil}812 }813 }814 if len(r.buffer) > 5 && r.buffer[5] == '~' {815 *sz = 6816 switch r.buffer[4] {817 case '2':818 return Event{ShiftDelete, 0, nil}819 case '3':820 return Event{AltDelete, 0, nil}821 case '4':822 return Event{AltShiftDelete, 0, nil}823 case '5':824 return Event{CtrlDelete, 0, nil}825 case '6':826 return Event{CtrlShiftDelete, 0, nil}827 case '7':828 return Event{CtrlAltDelete, 0, nil}829 case '8':830 return Event{CtrlAltShiftDelete, 0, nil}831 case '9':832 return Event{AltDelete, 0, nil}833 }834 }835 return Event{Invalid, 0, nil}836 case '4':837 if rxvtKeyEnd(r.buffer[3]) {838 return Event{End, 0, nil}839 }840 case '5':841 if r.buffer[3] == '~' {842 return Event{PageUp, 0, nil}843 }844 if len(r.buffer) > 6 && r.buffer[6] == '~' && r.buffer[4] == '1' {845 *sz = 7846 switch r.buffer[5] {847 case '0':848 return Event{AltShiftPageUp, 0, nil}849 case '1':850 return Event{AltPageUp, 0, nil}851 case '2':852 return Event{AltShiftPageUp, 0, nil}853 case '3':854 return Event{CtrlAltPageUp, 0, nil}855 case '4':856 return Event{CtrlAltShiftPageUp, 0, nil}857 case '5':858 return Event{CtrlAltPageUp, 0, nil}859 case '6':860 return Event{CtrlAltShiftPageUp, 0, nil}861 }862 }863 if len(r.buffer) > 5 && r.buffer[5] == '~' {864 *sz = 6865 switch r.buffer[4] {866 case '2':867 return Event{ShiftPageUp, 0, nil}868 case '3':869 return Event{AltPageUp, 0, nil}870 case '4':871 return Event{AltShiftPageUp, 0, nil}872 case '5':873 return Event{CtrlPageUp, 0, nil}874 case '6':875 return Event{CtrlShiftPageUp, 0, nil}876 case '7':877 return Event{CtrlAltPageUp, 0, nil}878 case '8':879 return Event{CtrlAltShiftPageUp, 0, nil}880 case '9':881 return Event{AltPageUp, 0, nil}882 }883 }884 return Event{Invalid, 0, nil}885 case '6':886 if r.buffer[3] == '~' {887 return Event{PageDown, 0, nil}888 }889 if len(r.buffer) > 6 && r.buffer[6] == '~' && r.buffer[4] == '1' {890 *sz = 7891 switch r.buffer[5] {892 case '0':893 return Event{AltShiftPageDown, 0, nil}894 case '1':895 return Event{AltPageDown, 0, nil}896 case '2':897 return Event{AltShiftPageDown, 0, nil}898 case '3':899 return Event{CtrlAltPageDown, 0, nil}900 case '4':901 return Event{CtrlAltShiftPageDown, 0, nil}902 case '5':903 return Event{CtrlAltPageDown, 0, nil}904 case '6':905 return Event{CtrlAltShiftPageDown, 0, nil}906 }907 }908 if len(r.buffer) > 5 && r.buffer[5] == '~' {909 *sz = 6910 switch r.buffer[4] {911 case '2':912 return Event{ShiftPageDown, 0, nil}913 case '3':914 return Event{AltPageDown, 0, nil}915 case '4':916 return Event{AltShiftPageDown, 0, nil}917 case '5':918 return Event{CtrlPageDown, 0, nil}919 case '6':920 return Event{CtrlShiftPageDown, 0, nil}921 case '7':922 return Event{CtrlAltPageDown, 0, nil}923 case '8':924 return Event{CtrlAltShiftPageDown, 0, nil}925 case '9':926 return Event{AltPageDown, 0, nil}927 }928 }929 return Event{Invalid, 0, nil}930 case '7':931 if rxvtKeyEnd(r.buffer[3]) {932 return Event{Home, 0, nil}933 }934 case '8':935 if rxvtKeyEnd(r.buffer[3]) {936 return Event{End, 0, nil}937 }938 case '1':939 switch r.buffer[3] {940 case '~':941 return Event{Home, 0, nil}942 case '1', '2', '3', '4', '5', '7', '8', '9':943 if len(r.buffer) > 4 && r.buffer[4] == '~' {944 *sz = 5945 switch r.buffer[3] {946 case '1':947 return Event{F1, 0, nil}948 case '2':949 return Event{F2, 0, nil}950 case '3':951 return Event{F3, 0, nil}952 case '4':953 return Event{F4, 0, nil}954 case '5':955 return Event{F5, 0, nil}956 case '7':957 return Event{F6, 0, nil}958 case '8':959 return Event{F7, 0, nil}960 case '9':961 return Event{F8, 0, nil}962 }963 }964 return Event{Invalid, 0, nil}965 case ';':966 if len(r.buffer) < 6 {967 return Event{Invalid, 0, nil}968 }969 *sz = 6970 switch r.buffer[4] {971 case '1', '2', '3', '4', '5', '6', '7', '8', '9':972 // Kitty iTerm2 WezTerm973 // ARROW "\e[1;1D"974 // SHIFT-ARROW "\e[1;2D"975 // ALT-SHIFT-ARROW "\e[1;4D" "\e[1;10D" "\e[1;4D"976 // CTRL-SHIFT-ARROW "\e[1;6D" N/A977 // CMD-SHIFT-ARROW "\e[1;10D" N/A N/A ("\e[1;2D")978 ctrl := bytes.IndexByte([]byte{'5', '6', '7', '8'}, r.buffer[4]) >= 0979 alt := bytes.IndexByte([]byte{'3', '4', '7', '8'}, r.buffer[4]) >= 0980 shift := bytes.IndexByte([]byte{'2', '4', '6', '8'}, r.buffer[4]) >= 0981 char := r.buffer[5]982 if r.buffer[4] == '9' {983 ctrl = false984 alt = true985 shift = false986 if len(r.buffer) < 6 {987 return Event{Invalid, 0, nil}988 }989 *sz = 6990 char = r.buffer[5]991 } else if r.buffer[4] == '1' && bytes.IndexByte([]byte{'0', '1', '2', '3', '4', '5', '6'}, r.buffer[5]) >= 0 {992 ctrl = bytes.IndexByte([]byte{'3', '4', '5', '6'}, r.buffer[5]) >= 0993 alt = true994 shift = bytes.IndexByte([]byte{'0', '2', '4', '6'}, r.buffer[5]) >= 0995 if len(r.buffer) < 7 {996 return Event{Invalid, 0, nil}997 }998 *sz = 7999 char = r.buffer[6]1000 }1001 ctrlShift := ctrl && shift1002 ctrlAlt := ctrl && alt1003 altShift := alt && shift1004 ctrlAltShift := ctrl && alt && shift1005 switch char {1006 case 'A':1007 if ctrlAltShift {1008 return Event{CtrlAltShiftUp, 0, nil}1009 }1010 if ctrlAlt {1011 return Event{CtrlAltUp, 0, nil}1012 }1013 if ctrlShift {1014 return Event{CtrlShiftUp, 0, nil}1015 }1016 if altShift {1017 return Event{AltShiftUp, 0, nil}1018 }1019 if ctrl {1020 return Event{CtrlUp, 0, nil}1021 }1022 if alt {1023 return Event{AltUp, 0, nil}1024 }1025 if shift {1026 return Event{ShiftUp, 0, nil}1027 }1028 return Event{Up, 0, nil}1029 case 'B':1030 if ctrlAltShift {1031 return Event{CtrlAltShiftDown, 0, nil}1032 }1033 if ctrlAlt {1034 return Event{CtrlAltDown, 0, nil}1035 }1036 if ctrlShift {1037 return Event{CtrlShiftDown, 0, nil}1038 }1039 if altShift {1040 return Event{AltShiftDown, 0, nil}1041 }1042 if ctrl {1043 return Event{CtrlDown, 0, nil}1044 }1045 if alt {1046 return Event{AltDown, 0, nil}1047 }1048 if shift {1049 return Event{ShiftDown, 0, nil}1050 }1051 return Event{Down, 0, nil}1052 case 'C':1053 if ctrlAltShift {1054 return Event{CtrlAltShiftRight, 0, nil}1055 }1056 if ctrlAlt {1057 return Event{CtrlAltRight, 0, nil}1058 }1059 if ctrlShift {1060 return Event{CtrlShiftRight, 0, nil}1061 }1062 if altShift {1063 return Event{AltShiftRight, 0, nil}1064 }1065 if ctrl {1066 return Event{CtrlRight, 0, nil}1067 }1068 if shift {1069 return Event{ShiftRight, 0, nil}1070 }1071 if alt {1072 return Event{AltRight, 0, nil}1073 }1074 return Event{Right, 0, nil}1075 case 'D':1076 if ctrlAltShift {1077 return Event{CtrlAltShiftLeft, 0, nil}1078 }1079 if ctrlAlt {1080 return Event{CtrlAltLeft, 0, nil}1081 }1082 if ctrlShift {1083 return Event{CtrlShiftLeft, 0, nil}1084 }1085 if altShift {1086 return Event{AltShiftLeft, 0, nil}1087 }1088 if ctrl {1089 return Event{CtrlLeft, 0, nil}1090 }1091 if alt {1092 return Event{AltLeft, 0, nil}1093 }1094 if shift {1095 return Event{ShiftLeft, 0, nil}1096 }1097 return Event{Left, 0, nil}1098 case 'H':1099 if ctrlAltShift {1100 return Event{CtrlAltShiftHome, 0, nil}1101 }1102 if ctrlAlt {1103 return Event{CtrlAltHome, 0, nil}1104 }1105 if ctrlShift {1106 return Event{CtrlShiftHome, 0, nil}1107 }1108 if altShift {1109 return Event{AltShiftHome, 0, nil}1110 }1111 if ctrl {1112 return Event{CtrlHome, 0, nil}1113 }1114 if alt {1115 return Event{AltHome, 0, nil}1116 }1117 if shift {1118 return Event{ShiftHome, 0, nil}1119 }1120 return Event{Home, 0, nil}1121 case 'F':1122 if ctrlAltShift {1123 return Event{CtrlAltShiftEnd, 0, nil}1124 }1125 if ctrlAlt {1126 return Event{CtrlAltEnd, 0, nil}1127 }1128 if ctrlShift {1129 return Event{CtrlShiftEnd, 0, nil}1130 }1131 if altShift {1132 return Event{AltShiftEnd, 0, nil}1133 }1134 if ctrl {1135 return Event{CtrlEnd, 0, nil}1136 }1137 if alt {1138 return Event{AltEnd, 0, nil}1139 }1140 if shift {1141 return Event{ShiftEnd, 0, nil}1142 }1143 return Event{End, 0, nil}1144 }1145 } // r.buffer[4]1146 } // r.buffer[3]1147 } // r.buffer[2]1148 } // r.buffer[2]1149 } // r.buffer[1]1150 // Nothing matched. A framed sequence is dropped whole: reading its1151 // introducer as an ALT-key below would type the rest into the query.1152 // Unterminated ones are left alone, as that is how ALT-[, ALT-O, ALT-],1153 // ALT-P and ALT-_ arrive.1154 if csiIntroducer(r.buffer[1]) {1155 // ALT-[ or ALT-O and one or two typed characters can look like a short1156 // sequence, so ask for at least two bytes before the final byte1157 if end := csiEnd(r.buffer); end > 4 {1158 *sz = end1159 return Event{Invalid, 0, nil}1160 }1161 } else if stringIntroducer(r.buffer[1]) {1162 if end := stringEnd(r.buffer); end > 0 && stringReply(r.buffer) {1163 *sz = end1164 return Event{Invalid, 0, nil}1165 }1166 }11671168 rest := bytes.NewBuffer(r.buffer[1:])1169 c, size, err := rest.ReadRune()1170 if err == nil {1171 *sz = 1 + size1172 return AltKey(c)1173 }1174 return Event{Invalid, 0, nil}1175}11761177// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Mouse-Tracking1178func (r *LightRenderer) mouseSequence(sz *int) Event {1179 // "\e[<0;0;0M"1180 if len(r.buffer) < 9 || !r.mouse {1181 return Event{Invalid, 0, nil}1182 }11831184 // Not past the frame, where M or m can be a key typed later1185 frame := csiEnd(r.buffer)1186 if frame <= 0 || r.buffer[frame-1] != 'm' && r.buffer[frame-1] != 'M' {1187 return Event{Invalid, 0, nil}1188 }1189 rest := r.buffer[*sz:]1190 end := frame - 1 - *sz11911192 elems := strings.SplitN(string(rest[:end]), ";", 3)1193 if len(elems) != 3 {1194 return Event{Invalid, 0, nil}1195 }11961197 t := atoi(elems[0], -1)1198 x := atoi(elems[1], -1) - 11199 y := atoi(elems[2], -1) - 1 - r.yoffset1200 if t < 0 || x < 0 {1201 return Event{Invalid, 0, nil}1202 }1203 *sz += end + 112041205 down := rest[end] == 'M'12061207 scroll := 01208 wheel := t >= 641209 if wheel {1210 t -= 641211 // SGR wheel button codes: 64=up, 65=down, 66=left, 67=right1212 switch t & 0b11 {1213 case 0:1214 scroll = 11215 case 1:1216 scroll = -11217 }1218 }12191220 // middle := t & 0b11221 left := t&0b11 == 01222 ctrl := t&0b10000 > 01223 alt := t&0b01000 > 01224 shift := t&0b00100 > 01225 drag := t&0b100000 > 0 // 3212261227 if wheel {1228 return Event{Mouse, 0, &MouseEvent{y, x, scroll, false, false, false, ctrl, alt, shift}}1229 }12301231 double := false1232 if down && !drag {1233 now := time.Now()1234 if !left { // Right double click is not allowed1235 r.clicks = [][2]int{}1236 } else if now.Sub(r.prevDownTime) < doubleClickDuration {1237 r.clicks = append(r.clicks, [2]int{x, y})1238 } else {1239 r.clicks = [][2]int{{x, y}}1240 }1241 r.prevDownTime = now1242 } else {1243 n := len(r.clicks)1244 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] &&1245 time.Since(r.prevDownTime) < doubleClickDuration {1246 double = true1247 if double {1248 r.clicks = [][2]int{}1249 }1250 }1251 }1252 return Event{Mouse, 0, &MouseEvent{y, x, 0, left, down, double, ctrl, alt, shift}}1253}12541255func (r *LightRenderer) smcup() {1256 r.flush()1257 r.flushRaw("\x1b[?1049h")1258}12591260func (r *LightRenderer) rmcup() {1261 r.flush()1262 r.flushRaw("\x1b[?1049l")1263}12641265func (r *LightRenderer) Pause(clear bool) {1266 r.disableModes()1267 r.restoreTerminal()1268 if clear {1269 if r.fullscreen {1270 r.rmcup()1271 } else {1272 r.smcup()1273 r.csi("H")1274 }1275 r.flush()1276 }1277}12781279func (r *LightRenderer) enableModes() {1280 if r.mouse {1281 r.csi("?1000h")1282 r.csi("?1002h")1283 r.csi("?1006h")1284 }1285 r.csi("?2004h") // Enable bracketed paste mode1286}12871288func (r *LightRenderer) disableMouse() {1289 if r.mouse {1290 r.csi("?1000l")1291 r.csi("?1002l")1292 r.csi("?1006l")1293 }1294}12951296func (r *LightRenderer) disableModes() {1297 r.disableMouse()1298 // Put bracketed paste back the way we found it. A shell that runs fzf from1299 // a line editor widget re-enables the mode only when the editor starts, so1300 // forcing it off here would leave it off for the rest of the session.1301 // Terminals that did not answer the query fall back to disabling, which is1302 // what fzf has always done.1303 if r.pasteWasSet != nil && *r.pasteWasSet {1304 r.csi("?2004h")1305 } else {1306 r.csi("?2004l")1307 }1308}13091310func (r *LightRenderer) Resume(clear bool, sigcont bool) {1311 r.setupTerminal()1312 // The programs that ran in the meantime may have left the terminal in an1313 // arbitrary SGR state1314 r.invalidateSGR()1315 if clear {1316 if r.fullscreen {1317 r.smcup()1318 } else {1319 r.rmcup()1320 }1321 r.enableModes()1322 r.flush()1323 } else if sigcont && !r.fullscreen && r.mouse {1324 // NOTE: SIGCONT (Coming back from CTRL-Z):1325 // It's highly likely that the offset we obtained at the beginning is1326 // no longer correct, so we simply disable mouse input.1327 r.disableMouse()1328 r.mouse = false1329 }1330}13311332func (r *LightRenderer) Clear() {1333 if r.fullscreen {1334 r.csi("H")1335 }1336 r.origin()1337 r.csi("J")1338 r.flush()1339}13401341func (r *LightRenderer) NeedScrollbarRedraw() bool {1342 return false1343}13441345func (r *LightRenderer) ShouldEmitResizeEvent() bool {1346 return false1347}13481349func (r *LightRenderer) RefreshWindows(windows []Window) {1350 r.flush()1351}13521353func (r *LightRenderer) Refresh() {1354 r.updateTerminalSize()1355}13561357func (r *LightRenderer) Close() {1358 if r.clearOnExit {1359 if r.fullscreen {1360 r.rmcup()1361 } else {1362 r.origin()1363 // Erase our own area first, then step back onto the line the1364 // prompt was on, so nothing on that line is touched1365 r.csi("J")1366 if r.upOneLine {1367 r.csi("A")1368 r.csi(fmt.Sprintf("%dG", r.xoffset+1))1369 }1370 }1371 } else if !r.fullscreen {1372 r.stderr("\x1b8") // DECRC: restore cursor position1373 }1374 if !r.showCursor {1375 r.csi("?25h")1376 }1377 r.disableModes()1378 r.flush()1379 r.restoreTerminal()1380 r.closePlatform()1381}13821383func (r *LightRenderer) Top() int {1384 return r.yoffset1385}13861387func (r *LightRenderer) MaxX() int {1388 return r.width1389}13901391func (r *LightRenderer) MaxY() int {1392 if r.height == 0 {1393 r.updateTerminalSize()1394 }1395 return r.height1396}13971398func (r *LightRenderer) NewWindow(top int, left int, width int, height int, windowType WindowType, borderStyle BorderStyle, erase bool) Window {1399 width = max(0, width)1400 height = max(0, height)1401 w := &LightWindow{1402 renderer: r,1403 colored: r.theme.Colored,1404 windowType: windowType,1405 border: borderStyle,1406 top: top,1407 left: left,1408 width: width,1409 height: height,1410 tabstop: r.tabstop,1411 fg: colDefault,1412 bg: colDefault}1413 switch windowType {1414 case WindowBase:1415 w.fg = r.theme.Fg.Color1416 w.bg = r.theme.Bg.Color1417 case WindowList:1418 w.fg = r.theme.ListFg.Color1419 w.bg = r.theme.ListBg.Color1420 case WindowInput:1421 w.fg = r.theme.Input.Color1422 w.bg = r.theme.InputBg.Color1423 case WindowHeader:1424 w.fg = r.theme.Header.Color1425 w.bg = r.theme.HeaderBg.Color1426 case WindowFooter:1427 w.fg = r.theme.Footer.Color1428 w.bg = r.theme.FooterBg.Color1429 case WindowPreview:1430 w.fg = r.theme.PreviewFg.Color1431 w.bg = r.theme.PreviewBg.Color1432 }1433 if erase && !w.bg.IsDefault() && w.border.shape != BorderNone && w.height > 0 {1434 // fzf --color bg:blue --border --padding 1,21435 w.Erase()1436 }1437 w.drawBorder(false)1438 return w1439}14401441func (w *LightWindow) DrawBorder() {1442 w.drawBorder(false)1443}14441445func (w *LightWindow) DrawHBorder() {1446 w.drawBorder(true)1447}14481449// drawHLine fills row `row` with `line` between optional left/right caps.1450// A zero rune means "no cap"; caps are placed at the very edges of `w`.1451func (w *LightWindow) drawHLine(row int, line, leftCap, rightCap rune, color ColorPair) {1452 w.Move(row, 0)1453 hw := runeWidth(line)1454 width := w.width1455 if leftCap != 0 {1456 w.CPrint(color, string(leftCap))1457 width -= runeWidth(leftCap)1458 }1459 if rightCap != 0 {1460 width -= runeWidth(rightCap)1461 }1462 if width < 0 {1463 width = 01464 }1465 inner := width / hw1466 rem := width - inner*hw1467 w.CPrint(color, repeat(line, inner)+repeat(' ', rem))1468 if rightCap != 0 {1469 w.CPrint(color, string(rightCap))1470 }1471}14721473func (w *LightWindow) DrawHSeparator(row int, windowType WindowType, useBottom bool) {1474 if w.height == 0 {1475 return1476 }1477 shape := w.border.shape1478 if shape == BorderNone {1479 return1480 }1481 color := BorderColor(windowType)1482 line := w.border.top1483 if useBottom {1484 line = w.border.bottom1485 }1486 var leftCap, rightCap rune1487 if shape.HasLeft() {1488 leftCap = w.border.leftMid1489 }1490 if shape.HasRight() {1491 rightCap = w.border.rightMid1492 }1493 w.drawHLine(row, line, leftCap, rightCap, color)1494}14951496func (w *LightWindow) PaintSectionFrame(topContent, bottomContent int, windowType WindowType, edge SectionEdge) {1497 if w.height == 0 || w.border.shape == BorderNone {1498 return1499 }1500 color := BorderColor(windowType)1501 shape := w.border.shape1502 hasLeft := shape.HasLeft()1503 hasRight := shape.HasRight()1504 rightW := runeWidth(w.border.right)1505 // Content rows: overpaint left/right verticals + their 1-char margin.1506 for row := topContent; row <= bottomContent; row++ {1507 if hasLeft {1508 w.Move(row, 0)1509 w.CPrint(color, string(w.border.left)+" ")1510 }1511 if hasRight {1512 w.Move(row, w.width-rightW-1)1513 w.CPrint(color, " "+string(w.border.right))1514 }1515 }1516 if edge == SectionEdgeTop && shape.HasTop() {1517 var leftCap, rightCap rune1518 if hasLeft {1519 leftCap = w.border.topLeft1520 }1521 if hasRight {1522 rightCap = w.border.topRight1523 }1524 w.drawHLine(0, w.border.top, leftCap, rightCap, color)1525 }1526 if edge == SectionEdgeBottom && shape.HasBottom() {1527 var leftCap, rightCap rune1528 if hasLeft {1529 leftCap = w.border.bottomLeft1530 }1531 if hasRight {1532 rightCap = w.border.bottomRight1533 }1534 w.drawHLine(w.height-1, w.border.bottom, leftCap, rightCap, color)1535 }1536}15371538func (w *LightWindow) drawBorder(onlyHorizontal bool) {1539 if w.height == 0 {1540 return1541 }1542 shape := w.border.shape1543 if shape == BorderNone {1544 return1545 }1546 color := BorderColor(w.windowType)1547 hasLeft := shape.HasLeft()1548 hasRight := shape.HasRight()15491550 if shape.HasTop() {1551 var leftCap, rightCap rune1552 if hasLeft {1553 leftCap = w.border.topLeft1554 }1555 if hasRight {1556 rightCap = w.border.topRight1557 }1558 w.drawHLine(0, w.border.top, leftCap, rightCap, color)1559 }1560 if !onlyHorizontal && (hasLeft || hasRight) {1561 vw := runeWidth(w.border.left)1562 for y := 0; y < w.height; y++ {1563 // Corner rows are already painted by drawHLine above / below.1564 if (y == 0 && shape.HasTop()) || (y == w.height-1 && shape.HasBottom()) {1565 continue1566 }1567 if hasLeft {1568 w.Move(y, 0)1569 w.CPrint(color, string(w.border.left)+" ")1570 }1571 if hasRight {1572 w.Move(y, w.width-vw-1)1573 w.CPrint(color, " "+string(w.border.right))1574 }1575 }1576 }1577 if shape.HasBottom() {1578 var leftCap, rightCap rune1579 if hasLeft {1580 leftCap = w.border.bottomLeft1581 }1582 if hasRight {1583 rightCap = w.border.bottomRight1584 }1585 w.drawHLine(w.height-1, w.border.bottom, leftCap, rightCap, color)1586 }1587}15881589func (w *LightWindow) stderrInternal(str string, allowNLCR bool, resetCode string) {1590 w.renderer.stderrInternal(str, allowNLCR, resetCode)1591}15921593func (w *LightWindow) Top() int {1594 return w.top1595}15961597func (w *LightWindow) Left() int {1598 return w.left1599}16001601func (w *LightWindow) Width() int {1602 return w.width1603}16041605func (w *LightWindow) Height() int {1606 return w.height1607}16081609func (w *LightWindow) Refresh() {1610}16111612func (w *LightWindow) X() int {1613 return w.posx1614}16151616func (w *LightWindow) Y() int {1617 return w.posy1618}16191620func (w *LightWindow) EncloseX(x int) bool {1621 return x >= w.left && x < (w.left+w.width)1622}16231624func (w *LightWindow) EncloseY(y int) bool {1625 return y >= w.top && y < (w.top+w.height)1626}16271628func (w *LightWindow) Enclose(y int, x int) bool {1629 return w.EncloseX(x) && w.EncloseY(y)1630}16311632func (w *LightWindow) Move(y int, x int) {1633 w.posx = x1634 w.posy = y16351636 w.renderer.move(w.Top()+y, w.Left()+x)1637}16381639func (w *LightWindow) MoveAndClear(y int, x int) {1640 w.Move(y, x)1641 // We should not delete preview window on the right1642 // csi("K")1643 w.Print(repeat(' ', w.width-x))1644 w.Move(y, x)1645}16461647func attrCodes(attr Attr) []string {1648 codes := []string{}1649 if (attr & AttrClear) > 0 {1650 return codes1651 }1652 if (attr&Bold) > 0 || (attr&BoldForce) > 0 {1653 codes = append(codes, "1")1654 }1655 if (attr & Dim) > 0 {1656 codes = append(codes, "2")1657 }1658 if (attr & Italic) > 0 {1659 codes = append(codes, "3")1660 }1661 if (attr & Underline) > 0 {1662 switch attr.UnderlineStyle() {1663 case UlStyleDouble:1664 codes = append(codes, "4:2")1665 case UlStyleCurly:1666 codes = append(codes, "4:3")1667 case UlStyleDotted:1668 codes = append(codes, "4:4")1669 case UlStyleDashed:1670 codes = append(codes, "4:5")1671 default:1672 codes = append(codes, "4")1673 }1674 }1675 if (attr & Blink) > 0 {1676 codes = append(codes, "5")1677 }1678 if (attr & Reverse) > 0 {1679 codes = append(codes, "7")1680 }1681 if (attr & StrikeThrough) > 0 {1682 codes = append(codes, "9")1683 }1684 return codes1685}16861687func colorCodes(fg Color, bg Color) []string {1688 codes := []string{}1689 appendCode := func(c Color, offset int) {1690 if c == colDefault {1691 return1692 }1693 if c.is24() {1694 r := (c >> 16) & 0xff1695 g := (c >> 8) & 0xff1696 b := (c) & 0xff1697 codes = append(codes, fmt.Sprintf("%d;2;%d;%d;%d", 38+offset, r, g, b))1698 } else if c >= colBlack && c <= colWhite {1699 codes = append(codes, fmt.Sprintf("%d", int(c)+30+offset))1700 } else if c > colWhite && c < 16 {1701 codes = append(codes, fmt.Sprintf("%d", int(c)+90+offset-8))1702 } else if c >= 16 && c < 256 {1703 codes = append(codes, fmt.Sprintf("%d;5;%d", 38+offset, c))1704 }1705 }1706 appendCode(fg, 0)1707 appendCode(bg, 10)1708 return codes1709}17101711func ulColorCode(c Color) string {1712 if c == colDefault {1713 return ""1714 }1715 if c.is24() {1716 r := (c >> 16) & 0xff1717 g := (c >> 8) & 0xff1718 b := (c) & 0xff1719 return fmt.Sprintf("58;2;%d;%d;%d", r, g, b)1720 }1721 if c >= 0 && c < 256 {1722 return fmt.Sprintf("58;5;%d", c)1723 }1724 return ""1725}17261727// csiColor builds the SGR sequence for the given colors and attributes1728// without emitting it. The sequence starts with a reset parameter, so it1729// fully determines the SGR state on its own.1730func (w *LightWindow) csiColor(fg Color, bg Color, ul Color, attr Attr) (bool, string) {1731 codes := append(attrCodes(attr), colorCodes(fg, bg)...)1732 if ulCode := ulColorCode(ul); ulCode != "" {1733 codes = append(codes, ulCode)1734 }1735 if len(codes) == 0 {1736 return false, "\x1b[0m"1737 }1738 return true, "\x1b[;" + strings.Join(codes, ";") + "m"1739}17401741func (w *LightWindow) Print(text string) {1742 w.cprint2(colDefault, w.bg, AttrRegular, text)1743}17441745func cleanse(str string) string {1746 return strings.ReplaceAll(str, "\x1b", "")1747}17481749func (w *LightWindow) CPrint(pair ColorPair, text string) {1750 _, code := w.csiColor(pair.Fg(), pair.Bg(), pair.Ul(), pair.Attr())1751 w.renderer.setSGR(code)1752 w.stderrInternal(cleanse(text), false, code)1753}17541755func (w *LightWindow) cprint2(fg Color, bg Color, attr Attr, text string) {1756 _, code := w.csiColor(fg, bg, colDefault, attr)1757 w.renderer.setSGR(code)1758 w.stderrInternal(cleanse(text), false, code)1759}17601761func (w *LightWindow) fill(str string, resetCode string) FillReturn {1762 allLines := strings.Split(str, "\n")1763 for i, line := range allLines {1764 lines := WrapLine(line, w.posx, w.width, w.tabstop, w.wrapSignWidth)1765 for j, wl := range lines {1766 if w.posx < w.width {1767 w.stderrInternal(wl.Text, false, resetCode)1768 w.posx += wl.DisplayWidth1769 }17701771 // Wrap line1772 if j < len(lines)-1 || i < len(allLines)-1 {1773 if w.posy+1 >= w.height {1774 return FillSuspend1775 }1776 w.MoveAndClear(w.posy, w.posx)1777 w.Move(w.posy+1, 0)1778 w.renderer.setSGR(resetCode)1779 if len(lines) > 1 {1780 sign := w.wrapSign1781 width := w.wrapSignWidth1782 if width > w.width {1783 runes, truncatedWidth := util.Truncate(w.wrapSign, w.width)1784 sign = string(runes)1785 width = truncatedWidth1786 }1787 w.stderrInternal(DIM+sign, false, resetCode)1788 w.renderer.invalidateSGR()1789 w.renderer.setSGR(resetCode)1790 w.Move(w.posy, width)1791 }1792 }1793 }1794 }1795 if w.posx >= w.Width() {1796 if w.posy+1 >= w.height {1797 return FillSuspend1798 }1799 w.Move(w.posy+1, 0)1800 w.renderer.setSGR(resetCode)1801 return FillNextLine1802 }1803 return FillContinue1804}18051806func (w *LightWindow) setBg() string {1807 // The plain reset code for the default background is still required to1808 // clear the dim attribute after ␍ in the preview window1809 // e.g. printf "foo\rbar" | fzf --ansi --preview 'printf "foo\rbar"'1810 _, code := w.csiColor(colDefault, w.bg, colDefault, AttrRegular)1811 w.renderer.setSGR(code)1812 return code1813}18141815func (w *LightWindow) LinkBegin(uri string, params string) {1816 w.renderer.queued.WriteString("\x1b]8;" + params + ";" + uri + "\x1b\\")1817}18181819func (w *LightWindow) LinkEnd() {1820 w.renderer.queued.WriteString("\x1b]8;;\x1b\\")1821}18221823func (w *LightWindow) Fill(text string) FillReturn {1824 w.Move(w.posy, w.posx)1825 code := w.setBg()1826 return w.fill(text, code)1827}18281829func (w *LightWindow) CFill(fg Color, bg Color, ul Color, attr Attr, text string) FillReturn {1830 w.Move(w.posy, w.posx)1831 if fg == colDefault {1832 fg = w.fg1833 }1834 if bg == colDefault {1835 bg = w.bg1836 }1837 if hasColors, resetCode := w.csiColor(fg, bg, ul, attr); hasColors {1838 w.renderer.setSGR(resetCode)1839 return w.fill(text, resetCode)1840 }1841 return w.fill(text, w.setBg())1842}18431844func (w *LightWindow) FinishFill() {1845 if w.posy < w.height {1846 w.MoveAndClear(w.posy, w.posx)1847 }1848 for y := w.posy + 1; y < w.height; y++ {1849 w.MoveAndClear(y, 0)1850 }1851}18521853func (w *LightWindow) Erase() {1854 w.DrawBorder()1855 w.Move(0, 0)1856 w.FinishFill()1857 w.Move(0, 0)1858}18591860func (w *LightWindow) EraseMaybe() bool {1861 return false1862}18631864func (w *LightWindow) SetWrapSign(sign string, width int) {1865 w.wrapSign = sign1866 w.wrapSignWidth = width1867}18681869func (r *LightRenderer) HideCursor() {1870 r.showCursor = false1871 r.csi("?25l")1872}18731874func (r *LightRenderer) ShowCursor() {1875 r.showCursor = true1876 r.csi("?25h")1877}