-
Notifications
You must be signed in to change notification settings - Fork 1
/
input.go
556 lines (494 loc) · 12.2 KB
/
input.go
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package anansi
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"os/signal"
"runtime"
"syscall"
"time"
"unicode/utf8"
"github.com/jcorbin/anansi/ansi"
)
const defaultMinReadSize = 128
// Input supports reading terminal input from a file handle with a buffer for
// things like escape sequences. It supports both blocking and non-blocking
// reads. It is not safe to use Input in parallel from multiple goroutines,
// such users need to layer a lock around an Input.
type Input struct {
File *os.File
MinReadSize int
oldFlags uintptr
ateof bool
nonblock bool
async bool
sigio chan os.Signal
buf bytes.Buffer
rec io.Writer
recTmp bytes.Buffer
}
var errNoFd = errors.New("non-blocking io not supported by underlying reader")
// SetRecording enables (or disables if nil-argument) input recording. When
// enabled, all read bytes are written to the given destination with added
// timing marks.
//
// Timing marks are encoded as an ANSI Application Program Command (APC)
// string; schematically:
//
// APC "recTime:" RFC3339Nano ST
//
// For example:
//
// "\x1b_recTime:12345\x1b\\any bytes read at that time"
//
// In specific: ReadAny() records the time it was called (even if no bytes were
// available to be read); ReadMore() records the time that its blocking read
// call returned non-zero bytes (modulo go scheduler lag of course).
//
// Any read error(s) are recorded similiarly:
//
// APC "recReadErr:" error-string ST
func (in *Input) SetRecording(dest io.Writer) {
in.rec = dest
}
// IsRecording returns true only if a recording destination is in effect (as
// given to SetRecording).
func (in *Input) IsRecording(dest *os.File) bool {
return in.rec != nil
}
const (
recMarkStart = "\x1b_recTime:" // APC "recTime:"
recMarkEnd = "\x1b\\" // ST
recMarkSize = 2 + 8 + len(time.RFC3339Nano) + 2
recReadErrStart = "\x1b_recReadErr:" // APC "recReadErr:"
recReadErrEnd = "\x1b\\" // ST
recReadErrSize = 2 + 11 + 256 + 2
)
type fdProvider interface {
Fd() uintptr
}
// AtEOF returns true if the last input read returned io.EOF.
func (in *Input) AtEOF() bool {
return in.ateof
}
// Notify sets up async notification to the given channel, replacing (stopping
// notifications to) any prior channel passed to Notify(). If the passed
// channel is nil, async mode is disabled.
func (in *Input) Notify(sigio chan os.Signal) error {
prior := in.sigio
in.sigio = sigio
if sigio != nil {
signal.Notify(in.sigio, syscall.SIGIO)
}
if prior != nil {
signal.Stop(prior)
}
return in.setAsync(sigio != nil)
}
// InputSignal is a convenience wrapper for using a Signal and Input.Notify
// contextually.
type InputSignal struct {
Signal
}
// Enter opens the signal, and sets up input notification.
func (is *InputSignal) Enter(term *Term) error {
err := is.Open()
if err == nil {
err = term.Input.Notify(is.C)
}
return err
}
// Decode decodes the next available ANSI escape sequence or UTF8 rune from the
// internal buffer filled by ReadMore or ReadAny. If the ok return value is
// false, then none can be decoded without first reading more input.
//
// The caller should call e.IsEscape() to tell the difference between
// escape-sequence-signifying runes, and normal ones. Normal runes may then be
// cast and handled ala `if !e.IsEscape() { r := rune(e) }`.
//
// NOTE any returned escape argument slice becomes invalid after the next call
// to Decode; the caller MUST copy any bytes out if it needs to retain them.
func (in *Input) Decode() (e ansi.Escape, a []byte, ok bool) {
if e, a := in.decodeEscape(); e != 0 {
return e, a, true
}
if r, ok := in.decodeRune(); ok {
return ansi.Escape(r), nil, true
}
return 0, nil, false
}
func (in *Input) decodeEscape() (e ansi.Escape, a []byte) {
if in.buf.Len() == 0 {
return 0, nil
}
e, a, n := ansi.DecodeEscape(in.buf.Bytes())
if n > 0 {
in.buf.Next(n)
}
return e, a
}
func (in *Input) decodeRune() (rune, bool) {
if in.buf.Len() == 0 {
return 0, false
}
r, n := utf8.DecodeRune(in.buf.Bytes())
if !in.ateof {
switch r {
case 0x90, 0x9B, 0x9D, 0x9E, 0x9F: // DCS, CSI, OSC, PM, APC
return 0, false
case 0x1B: // ESC
if p := in.buf.Bytes(); len(p) == cap(p) && !in.ateof {
return 0, false
}
}
}
in.buf.Next(n)
return r, true
}
// ReadMore from the underlying file into the internal byte buffer; it
// may block until at least one new byte has been read. Returns the
// number of bytes read and any error.
func (in *Input) ReadMore() (int, error) {
for {
var frm InputFrame
p := in.readBuf()
n, err := in.File.Read(p)
if in.rec != nil {
frm.T = time.Now()
}
switch unwrapOSError(err) {
case io.EOF:
if in.ateof {
return n, io.EOF
}
in.ateof = true
if n > 0 {
err = nil
}
case syscall.EWOULDBLOCK:
in.ateof = false
if n > 0 {
return n, nil
}
if err := in.setNonblock(false); err != nil {
return 0, err
}
case nil:
in.ateof = false
}
if n > 0 {
frm.B = p[:n]
_, _ = in.buf.Write(frm.B)
}
if in.rec != nil {
frm.E = err
if werr := in.recordFrame(frm); err == nil {
err = werr
}
}
if n > 0 || err != nil {
return n, err
}
}
}
// ReadAny reads any (and all!) available bytes from the underlying file into
// the internal byte buffer; uses non-blocking reads. Returns the number of
// bytes read and any error.
func (in *Input) ReadAny() (n int, err error) {
if err = in.setNonblock(true); err != nil {
return 0, err
}
in.ateof = false
var frm InputFrame
if in.rec != nil {
frm.T = time.Now()
}
for err == nil {
var m int
p := in.readBuf()
m, err = in.File.Read(p)
if m == 0 {
break
}
_, _ = in.buf.Write(p[:m])
n += m
}
switch unwrapOSError(err) {
case io.EOF:
in.ateof = true
case syscall.EWOULDBLOCK:
in.ateof = false
err = nil
case nil:
in.ateof = false
}
if n > 0 {
p := in.buf.Bytes()
frm.B = p[len(p)-n:]
}
if in.rec != nil {
frm.E = err
if werr := in.recordFrame(frm); err == nil {
err = werr
}
}
return n, err
}
// Enter gets the current fcntl flags for restoration during Exit(), and sets
// non-blocking/async modes if needed.
func (in *Input) Enter(term *Term) error {
prior, err := in.setFlags()
if err == nil {
in.oldFlags = prior
}
return err
}
// Exit restores fcntl flags to their Enter() time value.
func (in *Input) Exit(term *Term) error {
if in.File == nil {
return nil
}
if _, _, err := in.fcntl(syscall.F_SETFL, in.oldFlags); err != nil {
return fmt.Errorf("failed to set input file flags: %v", err)
}
return nil
}
// Close stops any signal notification setup by Notify().
func (in *Input) Close() error {
if in.sigio != nil {
signal.Stop(in.sigio)
in.sigio = nil
}
return nil
}
func (in *Input) recordFrame(frm InputFrame) error {
frm.writeIntoBuffer(&in.recTmp)
_, err := in.recTmp.WriteTo(in.rec)
in.recTmp.Reset()
return err
}
func (frm InputFrame) writeIntoBuffer(buf *bytes.Buffer) {
if frm.E == nil {
buf.Grow(recMarkSize + len(frm.B))
_, _ = buf.WriteString(recMarkStart)
b := buf.Bytes()
_, _ = buf.Write(frm.T.AppendFormat(b[len(b):], time.RFC3339Nano))
_, _ = buf.WriteString(recMarkEnd)
} else {
buf.Grow(recMarkSize + recReadErrSize + len(frm.B))
_, _ = buf.WriteString(recMarkStart)
b := buf.Bytes()
_, _ = buf.Write(frm.T.AppendFormat(b[len(b):], time.RFC3339Nano))
_, _ = buf.WriteString(recMarkEnd)
_, _ = buf.WriteString(recReadErrStart)
b = buf.Bytes()
_, _ = buf.WriteString(frm.E.Error())
_, _ = buf.WriteString(recReadErrEnd)
}
_, _ = buf.Write(frm.B)
}
// readBuf returns a slice into the internal byte buffer with enough space to
// read at least n bytes.
func (in *Input) readBuf() []byte {
if in.MinReadSize == 0 {
in.MinReadSize = defaultMinReadSize
}
in.buf.Grow(in.MinReadSize)
p := in.buf.Bytes()
p = p[len(p):cap(p)]
return p
}
func (in *Input) setAsync(async bool) error {
if async == in.async {
return nil
}
in.async = async
if _, err := in.setFlags(); err != nil {
return err
}
if in.async && in.File != nil {
_, _, err := in.fcntl(syscall.F_SETOWN, uintptr(syscall.Getpid()))
if err != nil && runtime.GOOS != "darwin" {
return fmt.Errorf("failed to set input file owner: %v", err)
}
}
return nil
}
func (in *Input) setNonblock(nonblock bool) error {
if nonblock == in.nonblock {
return nil
}
in.nonblock = nonblock
_, err := in.setFlags()
return err
}
func (in *Input) setFlags() (prior uintptr, _ error) {
if in.File == nil {
return 0, nil
}
flags, _, err := in.fcntl(syscall.F_GETFL, 0)
if err != nil {
return 0, fmt.Errorf("failed to get input file flags: %v", err)
}
prior = flags
flags = in.buildFlags(flags)
_, _, err = in.fcntl(syscall.F_SETFL, flags)
if err != nil {
return prior, fmt.Errorf("failed to set input file flags: %v", err)
}
return prior, nil
}
func (in *Input) buildFlags(flags uintptr) uintptr {
if in.nonblock {
flags |= syscall.O_NONBLOCK
}
if in.async {
flags |= syscall.O_ASYNC
}
return flags
}
func (in *Input) fcntl(a2, a3 uintptr) (r1, r2 uintptr, err error) {
r1, r2, e := syscall.Syscall(syscall.SYS_FCNTL, in.File.Fd(), a2, a3)
if e != 0 {
return 0, 0, e
}
return r1, r2, nil
}
// InputReplay is a session of recorded input.
type InputReplay []InputFrame
// InputFrame is a frame of recorded input.
type InputFrame struct {
T time.Time // input timestamp
E error // input read error
B []byte // read input
M []byte // pass through APC message
}
// InputError represets a recorderded read error.
type InputError []byte
func (ie InputError) String() string { return string(ie) }
func (ie InputError) Error() string { return string(ie) }
// Duration returns the total elapsed time of the replay.
func (rs InputReplay) Duration() time.Duration {
if len(rs) == 0 {
return 0
}
return rs[len(rs)-1].T.Sub(rs[0].T)
}
func (frm InputFrame) String() string {
var buf bytes.Buffer
buf.Grow(1024)
_, _ = buf.WriteString(frm.T.String())
if frm.E != nil {
if ie, ok := frm.E.(InputError); ok {
_, _ = fmt.Fprintf(&buf, " err=%s", []byte(ie))
} else {
_, _ = buf.WriteString(" err=")
_, _ = buf.WriteString(frm.E.Error())
}
}
if len(frm.M) != 0 {
_, _ = fmt.Fprintf(&buf, " mess=%q", frm.M)
}
if len(frm.B) == 0 {
_, _ = buf.WriteString(" mark")
} else {
_, _ = fmt.Fprintf(&buf, " %q", frm.M)
}
return buf.String()
}
// ReadInputReplay reads an InputReplay from the provided file.
func ReadInputReplay(f *os.File) (InputReplay, error) {
fi, err := f.Stat()
if err != nil {
return nil, err
}
estBytes := int(fi.Size())
estFrames := estBytes / recMarkSize
type protoFrame struct {
InputFrame
e [2]int
b [2]int
m [2]int
}
var (
in = Input{File: f, MinReadSize: 1024}
frames = make([]protoFrame, 0, estFrames)
bs = make([]byte, 0, estBytes)
off int
prot protoFrame
)
push := func() {
if prot.m != [2]int{} || !prot.T.IsZero() || off < len(bs) {
prot.b = [2]int{off, len(bs)}
frames = append(frames, prot)
prot = protoFrame{}
off = len(bs)
}
}
for {
e, a, ok := in.Decode()
if !ok {
if _, err := in.ReadMore(); err == io.EOF {
push()
break
} else if err != nil {
return nil, err
}
}
if e == 0x9F { // APC
switch {
case bytes.HasPrefix(a, []byte("recTime:")):
push()
if parseErr := prot.T.UnmarshalText(a[8:]); parseErr != nil {
return nil, fmt.Errorf("invalid recTime value %q", a[8:])
}
case bytes.HasPrefix(a, []byte("recReadErr:")):
bs = append(bs, a[11:]...)
prot.m = [2]int{off, len(bs)}
off = len(bs)
push()
default:
push()
bs = append(bs, a...)
prot.m = [2]int{off, len(bs)}
off = len(bs)
}
} else if e.IsEscape() {
bs = e.AppendWith(bs, a...)
} else {
var tmp [4]byte
n := utf8.EncodeRune(tmp[:], rune(e))
bs = append(bs, tmp[:n]...)
}
}
result := make(InputReplay, len(frames))
for i, frm := range frames {
if frm.e != [2]int{} {
prot.E = InputError(bs[frm.e[0]:frm.e[1]])
}
if frm.b != [2]int{} {
frm.B = bs[frm.b[0]:frm.b[1]]
}
if frm.m != [2]int{} {
frm.M = bs[frm.m[0]:frm.m[1]]
}
result[i] = frm.InputFrame
}
return result, nil
}
func unwrapOSError(err error) error {
for {
switch val := err.(type) {
case *os.PathError:
err = val.Err
case *os.LinkError:
err = val.Err
case *os.SyscallError:
err = val.Err
default:
return err
}
}
}