1package tui
2
3import (
4 "io"
5 "os"
6 "path/filepath"
7 "sync"
8 "time"
9
10 "golang.org/x/term"
11)
12
13// Terminal abstracts the real terminal for tests.
14type Terminal interface {
15 io.Writer
16 // Size returns (cols, rows).
17 Size() (int, int)
18 // OnResize registers a callback invoked on SIGWINCH (best effort).
19 OnResize(func())
20 // EnterRaw puts the tty into raw mode. Returns a restore func.
21 EnterRaw() (restore func() error, err error)
22 // ReadByte reads one byte of input. Blocks.
23 ReadByte() (byte, error)
24 // PeekByteTimeout reads one byte of input but returns (0, false, nil)
25 // if no byte arrives within the timeout. Used to disambiguate bare
26 // Esc from the start of an escape sequence.
27 PeekByteTimeout(time.Duration) (byte, bool, error)
28 // SetNonblock sets stdin to non-blocking mode (used by paste handling).
29 // May be a no-op on some platforms.
30 SetNonblock(bool) error
31}
32
33// ProcTerm is a Terminal bound to the current process's tty.
34type ProcTerm struct {
35 out *os.File
36 in *os.File
37 resizeCBs []func()
38 resizeOnce sync.Once // Windows polls each terminal independently.
39}
40
41// NewProcTerm returns a Terminal bound to stdin/stdout.
42func NewProcTerm() *ProcTerm {
43 return &ProcTerm{out: os.Stdout, in: os.Stdin}
44}
45
46func (p *ProcTerm) Write(b []byte) (int, error) { return p.out.Write(b) }
47
48func (p *ProcTerm) Size() (int, int) {
49 w, h, err := term.GetSize(int(p.out.Fd()))
50 if err != nil || w <= 0 || h <= 0 {
51 return 80, 24
52 }
53 return w, h
54}
55
56func (p *ProcTerm) OnResize(fn func()) {
57 p.resizeCBs = append(p.resizeCBs, fn)
58 p.installResizeHandler()
59}
60
61func (p *ProcTerm) EnterRaw() (func() error, error) {
62 fd := int(p.in.Fd())
63 if !term.IsTerminal(fd) {
64 return func() error { return nil }, nil
65 }
66 st, err := term.MakeRaw(fd)
67 if err != nil {
68 return nil, err
69 }
70 return func() error { return term.Restore(fd, st) }, nil
71}
72
73func (p *ProcTerm) ReadByte() (byte, error) {
74 var b [1]byte
75 _, err := p.in.Read(b[:])
76 return b[0], err
77}
78
79// PeekByteTimeout uses a platform-specific non-blocking read to decide
80// whether another byte is available within d. If not, returns (0, false, nil).
81func (p *ProcTerm) PeekByteTimeout(d time.Duration) (byte, bool, error) {
82 return peekStdin(p.in, d)
83}
84
85// ---- terminal control sequences ----
86
87// HideCursor, ShowCursor, ClearScreen, BracketedPasteOn/Off, etc.
88const (
89 SeqHideCursor = "\x1b[?25l"
90 SeqShowCursor = "\x1b[?25h"
91 SeqClearScreen = "\x1b[2J\x1b[H"
92 // SeqClearScreenNoHome is SeqClearScreen without the trailing
93 // cursor-home (\x1b[H). Use it whenever a MoveTo(...) follows
94 // immediately. VS Code's integrated terminal interprets a bare
95 // CUP-no-args during a clear as "snap the viewport scrollbar to
96 // row 0", which makes the user's scroll position jump on every
97 // repaint. The explicit MoveTo we emit afterwards positions the
98 // cursor identically without triggering that snap.
99 SeqClearScreenNoHome = "\x1b[2J"
100 SeqClearScrollback = "\x1b[3J"
101 // SeqCursorHome moves to the top-left of the visible viewport.
102 // SeqClearToEnd erases from the cursor to the end of the screen
103 // without scrolling content into scrollback (unlike \x1b[2J on
104 // xterm.js). Together they clear the visible frame in place, which
105 // the VS Code terminal needs for duplicate-free full repaints.
106 SeqCursorHome = "\x1b[H"
107 SeqClearToEnd = "\x1b[0J"
108 SeqClearLine = "\x1b[2K"
109 SeqResetScrollRegion = "\x1b[r"
110 SeqDeleteKittyImages = "\x1b_Ga=d\x1b\\"
111 SeqBracketedPasteOn = "\x1b[?2004h"
112 SeqBracketedPasteOff = "\x1b[?2004l"
113 // Request enhanced keyboard reporting where supported. Kitty-style
114 // keyboard protocol covers Ghostty, Kitty, VS Code's integrated
115 // terminal, and recent xterm.js builds. Xterm modifyOtherKeys is a
116 // useful fallback for terminals/tmux configurations that expose
117 // modified Enter as CSI 27;<mod>;<code>~.
118 SeqEnhancedKeyboardOn = "\x1b[>1u\x1b[>4;2m"
119 SeqEnhancedKeyboardOff = "\x1b[<u\x1b[>4m"
120 // Basic mouse tracking + SGR extended coordinates. Used only
121 // when explicitly enabled by the interactive mode (currently VS
122 // Code terminal) so terminals with good native scrolling, like
123 // Ghostty, are left alone.
124 SeqMouseOn = "\x1b[?1000h\x1b[?1006h"
125 SeqMouseOff = "\x1b[?1000l\x1b[?1006l"
126 SeqAltScreenOn = "\x1b[?1049h"
127 SeqAltScreenOff = "\x1b[?1049l"
128 SeqSynchronizedOn = "\x1b[?2026h"
129 SeqSynchronizedOff = "\x1b[?2026l"
130 // SeqSaveCursor / SeqRestoreCursor use DECSC/DECRC. All terminals
131 // we target adjust the saved row when natural scrolling occurs, so
132 // these survive scroll-on-write inside the bottom band.
133 SeqSaveCursor = "\x1b7"
134 SeqRestoreCursor = "\x1b8"
135 // SeqEraseToEnd erases from the cursor to the end of the screen.
136 SeqEraseToEnd = "\x1b[J"
137)
138
139// ReportCWD returns the OSC 7 sequence that tells the terminal the
140// current working directory, formatted as a file URL. Terminals such
141// as kitty, WezTerm, iTerm2, and GNOME Terminal use this to open new
142// tabs / splits in the same directory. Returns "" for an empty path so
143// callers can write it unconditionally. The path is percent-encoded
144// per RFC 3986 (only unreserved characters and the path separator are
145// left bare) and prefixed with the local hostname.
146func ReportCWD(dir string) string {
147 if dir == "" {
148 return ""
149 }
150 abs, err := filepath.Abs(dir)
151 if err != nil {
152 abs = dir
153 }
154 host, _ := os.Hostname()
155 return "\x1b]7;file://" + host + osc7EscapePath(abs) + "\x07"
156}
157
158// osc7EscapePath percent-encodes a filesystem path for an OSC 7 file
159// URL. Forward slashes (the URL path separator) and the unreserved set
160// (A-Z a-z 0-9 - _ . ~) pass through; everything else is %XX-encoded.
161// On Windows the backslash separators are normalised to forward
162// slashes and a leading slash is added so "C:\foo" becomes "/C:/foo".
163func osc7EscapePath(p string) string {
164 p = filepath.ToSlash(p)
165 if len(p) > 1 && p[1] == ':' {
166 p = "/" + p
167 }
168 const hex = "0123456789ABCDEF"
169 var b []byte
170 for i := 0; i < len(p); i++ {
171 c := p[i]
172 unreserved := (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
173 (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~' || c == '/'
174 if unreserved {
175 b = append(b, c)
176 continue
177 }
178 b = append(b, '%', hex[c>>4], hex[c&0x0f])
179 }
180 return string(b)
181}
182
183// SetScrollRegion returns the DECSTBM sequence to set the terminal's
184// scroll region (1-indexed, inclusive). Lines that scroll out of this
185// region still flow into the terminal's scrollback, but content above
186// or below the region is not affected by scroll-induced movement.
187func SetScrollRegion(top, bottom int) string {
188 return "\x1b[" + itoa(top) + ";" + itoa(bottom) + "r"
189}
190
191// MoveTo moves the cursor to 1-indexed (row, col).
192func MoveTo(row, col int) string {
193 return "\x1b[" + itoa(row) + ";" + itoa(col) + "H"
194}