gitstack

grindlemire/go-tui code browser

10.4 KB Go 389 lines 2026-06-19 ยท dfa2075 raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package tui

import (
	"bytes"
	"io"
	"os"
)

// ANSITerminal implements Terminal using ANSI escape sequences.
// It works with any terminal emulator that supports ANSI codes.
type ANSITerminal struct {
	out           io.Writer     // Output destination (usually os.Stdout)
	in            io.Reader     // Input source (usually os.Stdin)
	caps          Capabilities  // Terminal capabilities
	lastStyle     Style         // Last emitted style (for optimization)
	esc           *escBuilder   // Escape sequence builder
	inFd          uintptr       // File descriptor for input (needed for raw mode)
	outFd         uintptr       // File descriptor for output (needed for size query)
	rawState      *rawModeState // Platform-specific raw mode state
	kittyKeyboard bool          // true if Kitty keyboard protocol was successfully negotiated
}

// NewANSITerminal creates a new ANSI terminal with auto-detected capabilities.
// The output writer is typically os.Stdout and the input reader is os.Stdin.
func NewANSITerminal(out io.Writer, in io.Reader) (*ANSITerminal, error) {
	caps := DetectCapabilities()

	t := &ANSITerminal{
		out:  out,
		in:   in,
		caps: caps,
		esc:  newEscBuilder(4096),
	}

	// Try to get file descriptors for size queries and raw mode
	if f, ok := out.(*os.File); ok {
		t.outFd = f.Fd()
	}
	if f, ok := in.(*os.File); ok {
		t.inFd = f.Fd()
	}

	return t, nil
}

// NewANSITerminalWithCaps creates a new ANSI terminal with explicit capabilities.
// Use this when you want to override auto-detection.
func NewANSITerminalWithCaps(out io.Writer, in io.Reader, caps Capabilities) *ANSITerminal {
	t := &ANSITerminal{
		out:  out,
		in:   in,
		caps: caps,
		esc:  newEscBuilder(4096),
	}

	if f, ok := out.(*os.File); ok {
		t.outFd = f.Fd()
	}
	if f, ok := in.(*os.File); ok {
		t.inFd = f.Fd()
	}

	return t
}

// Size returns the terminal dimensions.
// Returns a default of 80x24 if the size cannot be determined.
func (t *ANSITerminal) Size() (width, height int) {
	w, h, err := getTerminalSize(int(t.outFd))
	if err != nil {
		return 80, 24 // Sensible default
	}
	return w, h
}

// Flush writes the given cell changes to the terminal.
// It optimizes cursor movement and style changes for efficiency.
func (t *ANSITerminal) Flush(changes []CellChange) {
	if len(changes) == 0 {
		return
	}

	t.esc.Reset()
	lastX, lastY := -1, -1
	openLink := "" // currently-open OSC 8 hyperlink ("" = none)

	for _, ch := range changes {
		// Erase-to-end-of-line: clear the row's tail with ESC[K. Reset style
		// first so the erased cells take the default background and stay blank
		// (terminals trim such cells when copying a selection). Checked before
		// the continuation guard below, since this change carries a zero Cell
		// (Width 0) that would otherwise be mistaken for a continuation cell.
		if ch.EraseToEOL {
			if t.caps.Hyperlinks {
				openLink = linkTransition(t.esc, openLink, "")
			}
			t.esc.MoveTo(ch.X, ch.Y)
			if !t.lastStyle.Equal(NewStyle()) {
				t.esc.ResetStyle()
				t.lastStyle = NewStyle()
			}
			t.esc.EraseToEndOfLine()
			lastX, lastY = -1, -1
			continue
		}

		// Skip continuation cells entirely - they represent the second column
		// of a wide character, which was already rendered by the primary cell.
		// Processing them would incorrectly move the cursor backwards.
		if ch.Cell.IsContinuation() {
			continue
		}

		// Optimize cursor movement
		needsMove := false
		if ch.Y != lastY {
			needsMove = true
		} else if ch.X != lastX+1 {
			// Not sequential on the same row
			needsMove = true
		}

		if needsMove {
			// A non-contiguous jump ends any open hyperlink run.
			if t.caps.Hyperlinks {
				openLink = linkTransition(t.esc, openLink, "")
			}
			t.esc.MoveTo(ch.X, ch.Y)
		}

		// Open/close OSC 8 hyperlinks around contiguous same-link runs.
		if t.caps.Hyperlinks {
			openLink = linkTransition(t.esc, openLink, ch.Cell.Link)
		}

		// Only emit style changes when style differs
		if !ch.Cell.Style.Equal(t.lastStyle) {
			t.esc.SetStyle(ch.Cell.Style, t.caps)
			t.lastStyle = ch.Cell.Style
		}

		// Write the cluster glyph (empty cell renders as a space).
		r := ch.Cell.Rune
		if r == 0 {
			r = ' '
		}
		t.esc.WriteRune(r)
		if ch.Cell.Combining != "" {
			t.esc.WriteString(ch.Cell.Combining)
		}

		lastX = ch.X
		if ch.Cell.Width > 1 {
			// Wide character advances cursor by its width
			lastX = ch.X + int(ch.Cell.Width) - 1
		}
		lastY = ch.Y
	}

	if t.caps.Hyperlinks {
		linkTransition(t.esc, openLink, "")
	}

	t.out.Write(t.esc.Bytes())
}

// Clear clears the entire terminal screen.
func (t *ANSITerminal) Clear() {
	t.esc.Reset()
	t.esc.ResetStyle()
	t.esc.MoveTo(0, 0)      // Home first
	t.esc.ClearScreen()     // ESC[2J - clear visible screen
	t.esc.ClearScrollback() // ESC[3J - also clear scrollback (helps with resize)
	t.esc.MoveTo(0, 0)      // Ensure cursor at home after clear
	t.out.Write(t.esc.Bytes())
	t.lastStyle = NewStyle()
}

// ClearToEnd clears from cursor position to end of screen.
func (t *ANSITerminal) ClearToEnd() {
	t.esc.Reset()
	t.esc.ClearToEndOfScreen()
	t.out.Write(t.esc.Bytes())
}

// SetCursor moves the cursor to the specified position (0-indexed).
func (t *ANSITerminal) SetCursor(x, y int) {
	t.esc.Reset()
	t.esc.MoveTo(x, y)
	t.out.Write(t.esc.Bytes())
}

// HideCursor makes the cursor invisible.
func (t *ANSITerminal) HideCursor() {
	t.esc.Reset()
	t.esc.HideCursor()
	t.out.Write(t.esc.Bytes())
}

// ShowCursor makes the cursor visible.
func (t *ANSITerminal) ShowCursor() {
	t.esc.Reset()
	t.esc.ShowCursor()
	t.out.Write(t.esc.Bytes())
}

// EnterRawMode puts the terminal into raw mode.
// This is implemented in platform-specific files.
func (t *ANSITerminal) EnterRawMode() error {
	state, err := enableRawMode(int(t.inFd))
	if err != nil {
		return err
	}
	t.rawState = state
	return nil
}

// ExitRawMode restores the terminal to its previous mode.
// This is implemented in platform-specific files.
func (t *ANSITerminal) ExitRawMode() error {
	if t.rawState == nil {
		return nil
	}
	err := disableRawMode(t.rawState)
	t.rawState = nil
	return err
}

// EnterAltScreen switches to the alternate screen buffer.
func (t *ANSITerminal) EnterAltScreen() {
	t.esc.Reset()
	t.esc.EnterAltScreen()
	t.out.Write(t.esc.Bytes())
}

// ExitAltScreen switches back to the main screen buffer.
func (t *ANSITerminal) ExitAltScreen() {
	t.esc.Reset()
	t.esc.ExitAltScreen()
	t.out.Write(t.esc.Bytes())
}

// EnableMouse enables mouse event reporting.
func (t *ANSITerminal) EnableMouse() {
	t.esc.Reset()
	t.esc.EnableMouse()
	t.out.Write(t.esc.Bytes())
}

// DisableMouse disables mouse event reporting.
func (t *ANSITerminal) DisableMouse() {
	t.esc.Reset()
	t.esc.DisableMouse()
	t.out.Write(t.esc.Bytes())
}

// EnableAltScroll enables alternate-scroll mode (mouse wheel -> cursor keys).
func (t *ANSITerminal) EnableAltScroll() {
	t.esc.Reset()
	t.esc.EnableAltScroll()
	t.out.Write(t.esc.Bytes())
}

// DisableAltScroll disables alternate-scroll mode.
func (t *ANSITerminal) DisableAltScroll() {
	t.esc.Reset()
	t.esc.DisableAltScroll()
	t.out.Write(t.esc.Bytes())
}

// EnableKittyKeyboard pushes Kitty keyboard protocol mode onto the terminal's
// stack without querying. Use this on resume when the terminal is already known
// to support the protocol.
func (t *ANSITerminal) EnableKittyKeyboard() {
	t.esc.Reset()
	t.esc.KittyKeyboardPush(1)
	t.out.Write(t.esc.Bytes())
	t.kittyKeyboard = true
	t.caps.KittyKeyboard = true
}

// DisableKittyKeyboard pops the Kitty keyboard protocol mode from the stack.
func (t *ANSITerminal) DisableKittyKeyboard() {
	if !t.kittyKeyboard {
		return
	}
	t.popKittyKeyboard()
	t.kittyKeyboard = false
	t.caps.KittyKeyboard = false
}

// popKittyKeyboard sends the pop escape sequence to undo a Kitty push.
func (t *ANSITerminal) popKittyKeyboard() {
	t.esc.Reset()
	t.esc.KittyKeyboardPop()
	t.out.Write(t.esc.Bytes())
}

// parseKittyQueryResponse checks if the response bytes contain a valid
// Kitty keyboard protocol query response (CSI ? flags u) where flags
// includes bit 1 (disambiguate).
func parseKittyQueryResponse(data []byte) bool {
	// Look for: \x1b [ ? <digits> u
	// Loop bound ensures i+3 is always in bounds.
	for i := 0; i < len(data)-3; i++ {
		if data[i] == 0x1b && data[i+1] == '[' && data[i+2] == '?' {
			// Parse digits after '?'
			j := i + 3
			flags := 0
			hasDigit := false
			for j < len(data) && data[j] >= '0' && data[j] <= '9' {
				flags = flags*10 + int(data[j]-'0')
				hasDigit = true
				j++
			}
			// Check for 'u' terminator and that flag 1 (disambiguate) is set
			if hasDigit && j < len(data) && data[j] == 'u' && flags&1 != 0 {
				return true
			}
		}
	}
	return false
}

// BeginSyncUpdate starts a synchronized update block.
// Output is buffered until EndSyncUpdate, then displayed atomically.
func (t *ANSITerminal) BeginSyncUpdate() {
	t.esc.Reset()
	t.esc.BeginSyncUpdate()
	t.out.Write(t.esc.Bytes())
}

// EndSyncUpdate ends a synchronized update block.
func (t *ANSITerminal) EndSyncUpdate() {
	t.esc.Reset()
	t.esc.EndSyncUpdate()
	t.out.Write(t.esc.Bytes())
}

// Caps returns the terminal's capabilities.
func (t *ANSITerminal) Caps() Capabilities {
	return t.caps
}

// SetCaps updates the terminal's capabilities.
// This is useful after detecting capabilities at runtime.
func (t *ANSITerminal) SetCaps(caps Capabilities) {
	t.caps = caps
}

// ResetStyle resets the style tracking, forcing the next Flush to emit style codes.
func (t *ANSITerminal) ResetStyle() {
	t.lastStyle = Style{Fg: RGBColor(255, 255, 255)} // Use something that won't match
}

// Writer returns the underlying writer for direct output.
// Use with caution as it bypasses the terminal's buffering.
func (t *ANSITerminal) Writer() io.Writer {
	return t.out
}

// WriteDirect writes raw bytes directly to the terminal output.
// Use for escape sequences or content that doesn't need processing.
func (t *ANSITerminal) WriteDirect(b []byte) (int, error) {
	return t.out.Write(b)
}

// BufferedWriter provides a buffered writer for efficient batch writes.
type BufferedWriter struct {
	buf bytes.Buffer
	out io.Writer
}

// NewBufferedWriter creates a buffered writer wrapping the given writer.
func NewBufferedWriter(out io.Writer) *BufferedWriter {
	return &BufferedWriter{out: out}
}

// Write writes bytes to the buffer.
func (w *BufferedWriter) Write(p []byte) (int, error) {
	return w.buf.Write(p)
}

// Flush writes the buffer contents to the underlying writer and clears the buffer.
func (w *BufferedWriter) Flush() error {
	_, err := w.out.Write(w.buf.Bytes())
	w.buf.Reset()
	return err
}