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