-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathterminal.go
More file actions
394 lines (359 loc) Β· 10.8 KB
/
Copy pathterminal.go
File metadata and controls
394 lines (359 loc) Β· 10.8 KB
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
390
391
392
393
394
package uv
import (
"fmt"
"os"
"os/signal"
"time"
"github.com/charmbracelet/x/ansi"
"golang.org/x/sync/errgroup"
)
// DefaultBufferSize is the default size of the input buffer used for reading
// terminal events.
const DefaultBufferSize = 4096
// DefaultEventTimeout is the default duration to wait for input events before
// timing out.
const DefaultEventTimeout = 100 * time.Millisecond
// Options represents options for creating a new [Terminal].
type Options struct {
// BufferSize is the size of the input buffer used for reading terminal
// events. If zero, [DefaultBufferSize] is used.
BufferSize int
// EventTimeout is the duration to wait for input events before timing out.
// If zero, a default of 100 milliseconds is used.
EventTimeout time.Duration
// LegacyKeyEncoding represents any legacy key encoding ambiguities. By
// default, the terminal will use its preferred key encoding settings.
LegacyKeyEncoding LegacyKeyEncoding
// LookupKeys whether to use a lookup table for common key sequences. If
// true, the terminal will use a lookup table to quickly identify common
// key sequences, reducing the need for more complex decoding logic. This
// can improve performance for common key sequences at the cost of
// increased memory usage.
//
// This is enabled by default.
LookupKeys bool
// UseTerminfoKeys whether to use terminfo databases key definitions to
// build up the keys lookup table. If true, the terminal will use terminfo
// databases key definitions to build up the keys lookup table, which can
// provide more accurate key mappings for legacy non-xterm like terminals.
//
// This won't take effect if [TerminalOptions.LookupKeys] is false, since
// the lookup table won't be used.
//
// This is disabled by default.
UseTerminfoKeys bool
// Logger is an optional logger for tracing terminal I/O operations.
// If nil, no logging is performed.
Logger Logger
}
// DefaultOptions returns the default [Terminal] options.
func DefaultOptions() *Options {
return &Options{
BufferSize: DefaultBufferSize,
EventTimeout: DefaultEventTimeout,
LookupKeys: true,
}
}
// Terminal represents an interactive terminal application.
type Terminal struct {
con Console
opts *Options
scr *TerminalScreen
pr pollReader
buf []byte
evc chan Event
errg errgroup.Group
winch chan os.Signal
donec chan struct{}
}
// DefaultTerminal creates a new [Terminal] instance using the default standard
// console and the given options. Options can be nil to use the default
// options.
//
// This is a convenience function for creating a terminal that uses the
// standard input and output file descriptors.
func DefaultTerminal() *Terminal {
return NewTerminal(nil, nil)
}
// ControllingTerminal creates a new [Terminal] instance using the controlling
// terminal's input and output file descriptors.
// Options can be nil to use the default options.
//
// This is a convenience function for creating a terminal that uses the
// controlling TTY of the current process.
func ControllingTerminal() (*Terminal, error) {
con, err := ControllingConsole()
if err != nil {
return nil, err
}
return NewTerminal(con, nil), nil
}
// NewTerminal creates a new [Terminal] instance with the given console and
// options.
// Options can be nil to use the default options.
func NewTerminal(con Console, opts *Options) *Terminal {
t := &Terminal{}
if con == nil {
con = DefaultConsole()
}
if opts == nil {
opts = DefaultOptions()
}
if opts.BufferSize <= 0 {
opts.BufferSize = DefaultBufferSize
}
if opts.EventTimeout <= 0 {
opts.EventTimeout = DefaultEventTimeout
}
t.con = con
t.opts = opts
t.scr = NewTerminalScreen(t.con.Writer(), t.con.Environ())
t.buf = make([]byte, opts.BufferSize)
// These channels never close during the terminal's lifetime.
t.evc = make(chan Event)
t.winch = make(chan os.Signal, 1) // buffered to avoid missing signals
if opts.Logger != nil {
t.scr.rend.SetLogger(opts.Logger)
}
return t
}
// GetSize returns the current size of the terminal in characters and pixels.
func (t *Terminal) GetSize() (width, height int, err error) {
w, h, err := t.con.GetSize()
if err != nil {
return 0, 0, fmt.Errorf("getting terminal size: %w", err)
}
return int(w), int(h), nil
}
// GetWinsize returns the current size of the terminal as a [Winsize] struct.
// This includes both character dimensions (columns and rows) and pixel
// dimensions (xpixel and ypixel).
//
// Note that this only returns the pixel dimensions on Unix-like systems that
// support the TIOCGWINSZ ioctl. On other platforms, the pixel dimensions may
// be zero or not available.
func (t *Terminal) GetWinsize() (*Winsize, error) {
ws, err := t.con.GetWinsize()
if err != nil {
return nil, fmt.Errorf("getting terminal winsize: %w", err)
}
return ws, nil
}
// Screen returns the terminal's screen.
func (t *Terminal) Screen() *TerminalScreen {
return t.scr
}
// Events returns the terminal's event channel.
func (t *Terminal) Events() <-chan Event {
return t.evc
}
// Start starts the terminal application event loop. This is a non-blocking
// call. Use [Terminal.Wait] to wait for the terminal to exit.
func (t *Terminal) Start() error {
_, err := t.con.MakeRaw()
if err != nil {
return fmt.Errorf("failed to set terminal to raw mode: %w", err)
}
evs := newEventScanner()
evs.lookup = t.opts.LookupKeys
if evs.lookup {
evs.table = buildKeysTable(t.opts.LegacyKeyEncoding, t.con.Getenv("TERM"), t.opts.UseTerminfoKeys)
}
if t.opts.Logger != nil {
evs.setLogger(t.opts.Logger)
}
bufc := make(chan []byte)
t.donec = make(chan struct{})
t.pr, err = newPollReader(t.con.Reader())
if err != nil {
return fmt.Errorf("failed to create poll reader: %w", err)
}
// input loop
t.errg.Go(func() error {
for {
n, err := t.pr.Read(t.buf)
if err != nil {
return fmt.Errorf("reading terminal input: %w", err)
}
select {
case bufc <- t.buf[:n]:
case <-t.donec:
return nil
}
}
})
// event loop
sendEvents := func(buf []byte, expired bool) int {
n, events := evs.scanEvents(buf, expired)
for _, ev := range events {
t.handleEvent(ev)
t.SendEvent(ev)
}
return n
}
t.errg.Go(func() error {
var buf []byte
timer := time.NewTimer(t.opts.EventTimeout)
timeout := time.Now().Add(t.opts.EventTimeout)
for {
select {
case <-t.donec:
return nil
case <-timer.C:
expired := len(buf) > 0 && time.Now().After(timeout)
n := sendEvents(buf, expired)
if n > 0 {
buf = buf[min(n, len(buf)):]
}
if len(buf) > 0 {
timer.Reset(t.opts.EventTimeout)
}
case data := <-bufc:
buf = append(buf, data...)
n := sendEvents(buf, false)
timeout = time.Now().Add(t.opts.EventTimeout)
timer.Stop()
if n > 0 {
buf = buf[min(n, len(buf)):]
}
if len(buf) > 0 {
timer.Reset(t.opts.EventTimeout)
}
}
}
})
sendWinsize := func() error {
ws, err := t.con.GetWinsize()
if err != nil {
return fmt.Errorf("getting terminal size: %w", err)
}
if ws.Col > 0 && ws.Row > 0 {
t.SendEvent(WindowSizeEvent{
Width: int(ws.Col),
Height: int(ws.Row),
})
}
if ws.Xpixel > 0 && ws.Ypixel > 0 {
t.SendEvent(PixelSizeEvent{
Width: int(ws.Xpixel),
Height: int(ws.Ypixel),
})
}
return nil
}
// winch handler
NotifyWinch(t.winch)
t.errg.Go(func() error {
for {
select {
case <-t.donec:
return nil
case <-t.winch:
if err := sendWinsize(); err != nil {
return err
}
}
}
})
// init window size
t.errg.Go(func() error {
if err := sendWinsize(); err != nil {
return err
}
return nil
})
// Restore any previous screen state.
t.scr.Restore()
// Query whether the terminal supports Unicode core mode (DEC mode 2027) so
// we can negotiate grapheme-cluster width. The response is handled in the
// event loop.
t.scr.requestGraphemeWidth()
if err := t.scr.Flush(); err != nil {
return fmt.Errorf("failed to flush terminal screen: %w", err)
}
return nil
}
// handleEvent reacts to internal events before they are forwarded to the
// application. It negotiates Unicode core mode (DEC mode 2027): when the
// terminal reports the mode is in a settable or active state, it enables
// grapheme-cluster width so wide-glyph measurement matches the terminal. The
// event is still forwarded to the application.
//
// The mode is only enabled for settable/active states (mode set, reset but
// settable, or permanently set). It is explicitly not enabled when the mode is
// not recognized or permanently reset, since those terminals cannot honor it.
// Enabling goes through the screen's locked write path so it cannot race with
// the application's Render/Flush.
func (t *Terminal) handleEvent(ev Event) {
if mr, ok := ev.(ModeReportEvent); ok {
if mr.Mode == ansi.ModeUnicodeCore &&
(mr.Value.IsSet() || mr.Value == ansi.ModeReset) {
t.scr.enableGraphemeWidth()
}
}
}
// Wait waits for the terminal event loop to exit and returns any error that
// occurred.
func (t *Terminal) Wait() error {
if err := t.errg.Wait(); err != nil {
return fmt.Errorf("terminal event loop error: %w", err)
}
return nil
}
// Stop stops the terminal event loop. It is safe to call Stop without a
// prior [Terminal.Start], and safe to call Stop multiple times in a row.
// After Stop returns, [Terminal.Start] may be called again to resume.
func (t *Terminal) Stop() error {
if t.donec != nil {
select {
case <-t.donec:
// Already closed.
default:
close(t.donec)
}
}
if t.winch != nil {
signal.Stop(t.winch)
}
if t.pr != nil {
t.pr.Cancel()
_ = t.pr.Close()
t.pr = nil
}
t.scr.Reset()
if err := t.scr.Flush(); err != nil {
_ = t.con.Restore()
return fmt.Errorf("failed to flush terminal screen: %w", err)
}
if err := t.con.Restore(); err != nil {
return fmt.Errorf("failed to restore terminal state: %w", err)
}
return nil
}
// SendEvent sends an event to the terminal's event channel.
//
// This can be used to inject custom events into the terminal's event loop,
// such as timer events, signals, or application-specific events.
func (t *Terminal) SendEvent(e Event) {
select {
case t.evc <- e:
case <-t.donec:
}
}
// Write writes data directly to the terminal's console output.
//
// This is a low-level operation that bypasses the terminal screen buffering
// and writes directly to the console output handler, usually [os.Stdout] or
// the controlling TTY.
func (t *Terminal) Write(p []byte) (n int, err error) {
return t.con.Write(p)
}
// Read reads data from the terminal's console input.
//
// This is a low-level operation that bypasses the terminal event processing
// and reads directly from the console input handler, usually [os.Stdin] or the
// controlling TTY. Use this method with caution, as it may interfere with the
// terminal's event loop and screen management.
func (t *Terminal) Read(p []byte) (n int, err error) {
return t.con.Read(p)
}