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