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