-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathterminal.go
633 lines (534 loc) · 16 KB
/
terminal.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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
package midterm
import (
"io"
"sync"
"github.com/danielgatis/go-ansicode"
)
// Terminal represents a raw terminal capable of handling VT100 and VT102 ANSI
// escape sequences, some of which are handled by forwarding them to a local or
// remote session (e.g. OSC52 copy/paste).
type Terminal struct {
// Screen is the current screen, embedded so that Terminal is a pass-through.
*Screen
// The title of the terminal
Title string
// Alt is either the alternate screen (if !IsAlt) or the main screen (if
// IsAlt).
Alt *Screen
// IsAlt indicates whether the alt screen is active.
IsAlt bool
// AutoResizeY indicates whether the terminal should automatically resize
// when the content exceeds its maximum height.
AutoResizeY bool
// AutoResizeX indicates that the terminal has no defined width - instead,
// columns are dynamically allocated as text is printed, and not all rows
// will be the same width.
AutoResizeX bool
// ForwardRequests is the writer to which we send requests to forward
// to the terminal.
ForwardRequests io.Writer
// ForwardResponses is the writer to which we send responses to CSI/OSC queries.
ForwardResponses io.Writer
// Enable "raw" mode. Line endings do not imply a carriage return.
Raw bool
// AppendOnly instructs the terminal to not respect sequences that might
// cause output to be lost - for example, setting a scrolling region.
AppendOnly bool
// wrap indicates that we've reached the end of the screen and need to wrap
// to the next line if another character is printed.
wrap bool
*ansicode.Decoder
// onResize is a hook called every time the terminal resizes.
onResize OnResizeFunc
// onScrollack is a hook called every time a line is about to be pushed out
// of the visible screen region.
onScrollback OnScrollbackFunc
// for synchronizing e.g. writes and async resizing
mut sync.Mutex
}
// Cursor represents both the position and text type of the cursor.
type Cursor struct {
// Y and X are the coordinates.
Y, X int
// F is the format that will be displayed.
F Format
// S is the cursor style.
S ansicode.CursorStyle
}
// ScrollRegion represents a region of the terminal that is
// scrollable.
type ScrollRegion struct {
Start, End int
}
// NewAutoResizingTerminal creates a new Terminal object with small initial
// dimensions, configured to automatically resize width and height as needed.
//
// This may be useful for applications that want to display dynamically sized
// content.
func NewAutoResizingTerminal() *Terminal {
term := NewTerminal(0, 0)
term.AutoResizeX = true
term.AutoResizeY = true
return term
}
// NewTerminal creates a new Terminal object with the specified dimensions. y
// and x must both be greater than zero.
//
// Each cell is set to contain a ' ' rune, and all formats are left as the
// default.
func NewTerminal(rows, cols int) *Terminal {
v := &Terminal{
Screen: newScreen(rows, cols),
}
v.Decoder = ansicode.NewDecoder(v)
v.reset()
return v
}
// Write writes the input sequence to the terminal.
func (v *Terminal) Write(p []byte) (int, error) {
if trace != nil {
trace.Write(p)
}
return v.Decoder.Write(p)
}
func (v *Terminal) Reset() {
v.mut.Lock()
defer v.mut.Unlock()
v.reset()
}
func (v *Terminal) UsedHeight() int {
v.mut.Lock()
defer v.mut.Unlock()
return v.MaxY + 1
}
func (v *Terminal) UsedWidth() int {
v.mut.Lock()
defer v.mut.Unlock()
return v.MaxX + 1
}
// Resize sets the terminal height and width to rows and cols and disables
// auto-resizing on both axes.
func (v *Terminal) Resize(rows, cols int) {
v.mut.Lock()
v.resize(rows, cols)
// disable auto-resize upon manually resizing. what's the point if the new
// size won't be respected?
v.AutoResizeX = false
v.AutoResizeY = false
f := v.onResize
v.mut.Unlock()
if f != nil {
f(rows, cols)
}
}
// Resize sets the terminal width to cols and disables auto-resizing width.
func (v *Terminal) ResizeX(cols int) {
v.mut.Lock()
v.resize(v.Height, cols)
// disable auto-resize upon manually resizing. what's the point if the new
// size won't be respected?
v.AutoResizeX = false
f := v.onResize
v.mut.Unlock()
if f != nil {
f(v.Height, cols)
}
}
// Resize sets the terminal height to rows rows and disables auto-resizing
// height.
func (v *Terminal) ResizeY(rows int) {
v.mut.Lock()
v.resize(rows, v.Width)
// disable auto-resize upon manually resizing. what's the point if the new
// size won't be respected?
v.AutoResizeY = false
f := v.onResize
v.mut.Unlock()
if f != nil {
f(rows, v.Width)
}
}
type OnScrollbackFunc func(line Line)
// OnScrollback sets a hook that is called every time a line is about to be
// pushed out of the visible screen region.
func (v *Terminal) OnScrollback(f OnScrollbackFunc) {
v.mut.Lock()
v.onScrollback = f
v.mut.Unlock()
}
type OnResizeFunc func(rows, cols int)
// OnResize sets a hook that is called every time the terminal resizes.
func (v *Terminal) OnResize(f OnResizeFunc) {
f(v.Height, v.Width)
v.mut.Lock()
v.onResize = f
v.mut.Unlock()
}
func (v *Terminal) resize(h, w int) {
v.Screen.resize(h, w)
if v.Alt != nil {
v.Alt.resize(h, w)
}
}
// put puts r onto the current cursor's position, then advances the cursor.
func (v *Terminal) put(r rune) {
if v.wrap {
v.Cursor.X = 0
v.moveDown()
v.wrap = false
}
x, y, f := v.Cursor.X, v.Cursor.Y, v.Cursor.F
v.paint(y, x, f, r)
if y > v.MaxY {
v.MaxY = y
}
if x > v.MaxX {
v.MaxX = x
}
v.advance()
}
// advance advances the cursor, wrapping to the next line if need be.
func (v *Terminal) advance() {
if !v.AutoResizeX && v.Cursor.X == v.Width-1 {
v.wrap = true
} else {
v.moveRel(0, 1)
v.changed(v.Cursor.Y, true)
}
}
func (v *Terminal) resizeY(h int) {
v.Screen.resizeY(h)
if v.Alt != nil {
v.Alt.resizeY(h)
}
}
func (v *Terminal) swapAlt() {
v.IsAlt = !v.IsAlt
v.Screen, v.Alt = v.Alt, v.Screen
}
func scrollUp[T any](arr [][]T, positions, start, end int, empty T) {
if start < 0 || end > len(arr) || start >= end || positions <= 0 {
return // handle invalid inputs
}
// for i := start; i < end-positions; i++ {
for i := start; i < (end+1)-positions; i++ { // +1 fixes weird stuff when shell scrollback exceeds window height
arr[i] = make([]T, len(arr[i+positions]))
copy(arr[i], arr[i+positions])
}
// Fill the newly scrolled lines with blank runes
for i := end - positions + 1; i <= end; i++ { // +1 and <= fixes last line not being cleared
arr[i] = make([]T, len(arr[i]))
for j := range arr[i] {
arr[i][j] = empty
}
}
}
func scrollUpShallow[T any](arr []T, positions, start, end int, init func() T) {
if start < 0 || end > len(arr) || start >= end || positions <= 0 {
return // handle invalid inputs
}
// for i := start; i < end-positions; i++ {
for i := start; i < (end+1)-positions; i++ { // +1 fixes weird stuff when shell scrollback exceeds window height
arr[i] = arr[i+positions]
}
// Fill the newly scrolled lines with blank runes
for i := end - positions + 1; i <= end; i++ { // +1 and <= fixes last line not being cleared
arr[i] = init()
}
}
func scrollDown[T any](arr [][]T, positions, start, end int, empty T) {
if start < 0 || end > len(arr) || start >= end || positions <= 0 {
return // handle invalid inputs
}
// Shift all rows down
for i := end; i >= start+positions; i-- {
arr[i] = make([]T, len(arr[i-positions]))
copy(arr[i], arr[i-positions])
}
// Fill the newly scrolled lines with blank runes
for i := start; i < start+positions; i++ {
arr[i] = make([]T, len(arr[i]))
for j := range arr[i] {
arr[i][j] = empty
}
}
}
func scrollDownShallow[T any](arr []T, positions, start, end int, init func() T) {
if start < 0 || end > len(arr) || start >= end || positions <= 0 {
return // handle invalid inputs
}
// Shift all rows down
for i := end; i >= start+positions; i-- {
arr[i] = arr[i-positions]
}
// Fill the newly scrolled lines with blank runes
for i := start; i < start+positions; i++ {
arr[i] = init()
}
}
func insertLines[T any](arr [][]T, start, ps, scrollStart, scrollEnd int, empty T) {
if start < 0 || start+ps > len(arr) || ps <= 0 {
return // handle invalid inputs
}
// Shift lines down by Ps positions starting from the start position
for i := scrollEnd; i >= start+ps; i-- {
arr[i] = arr[i-ps]
}
// Fill the newly inserted lines with the empty value
for i := start; i < start+ps; i++ {
arr[i] = make([]T, len(arr[i]))
for j := range arr[i] {
arr[i][j] = empty
}
}
}
func insertLinesShallow[T any](arr []T, start, ps, scrollStart, scrollEnd int, init func() T) {
if start < 0 || start+ps > len(arr) || ps <= 0 {
return // handle invalid inputs
}
// Shift lines down by Ps positions starting from the start position
for i := scrollEnd; i >= start+ps; i-- {
arr[i] = arr[i-ps]
}
// Fill the newly inserted lines with the empty value
for i := start; i < start+ps; i++ {
arr[i] = init()
}
}
func deleteLines[T any](arr [][]T, start, ps, scrollStart, scrollEnd int, empty T) {
if start < 0 || start+ps > len(arr) || ps <= 0 {
return // handle invalid inputs
}
// Delete Ps lines starting from the start position
copy(
arr[start:scrollEnd],
arr[start+ps:],
)
// Fill the end lines with the empty value
fillStart := scrollEnd - ps
for i := fillStart + 1; i < scrollEnd+1; i++ {
arr[i] = make([]T, len(arr[start])) // Assume all lines have the same length as the start line
for j := range arr[i] {
arr[i][j] = empty
}
}
}
func deleteLinesShallow[T any](arr []T, start, ps, scrollStart, scrollEnd int, init func() T) {
if start < 0 || start+ps > len(arr) || ps <= 0 {
return // handle invalid inputs
}
// Delete Ps lines starting from the start position
copy(
arr[start:scrollEnd],
arr[start+ps:],
)
// Fill the end lines with the empty value
fillStart := scrollEnd - ps
for i := fillStart + 1; i < scrollEnd+1; i++ {
arr[i] = init()
}
}
func eraseCharacters[T any](arr [][]T, row, col, ps int, empty T) {
if row < 0 || row >= len(arr) || col < 0 || col+ps > len(arr[row]) {
return // handle invalid inputs
}
if ps <= 0 {
ps = 1 // if Ps is 0 or negative, erase one character
}
// Replace Ps characters with the empty value starting from the given position
for i := col; i < col+ps; i++ {
arr[row][i] = empty
}
}
func deleteCharacters[T any](arr [][]T, row, col, ps int, empty T) {
if row < 0 || row >= len(arr) || col < 0 || col >= len(arr[row]) || ps < 0 {
return // handle invalid inputs
}
// Calculate the actual number of characters to delete, so it doesn't exceed the available space
actualPs := ps
if actualPs == 0 {
actualPs = 1 // if Ps is 0, delete one character
}
if col+actualPs > len(arr[row]) {
actualPs = len(arr[row]) - col
}
// Shift characters to the left by Ps positions starting from the given column
copy(arr[row][col:], arr[row][col+actualPs:])
// Fill the end characters with the empty value
for i := len(arr[row]) - ps; i < len(arr[row]); i++ {
arr[row][i] = empty
}
}
func insertEmpties[T any](arr [][]T, row, col, ps int, empty T) {
if row < 0 || row >= len(arr) || col < 0 || col > len(arr[row]) || ps <= 0 {
return // Return the original array if the inputs are out of bounds or invalid
}
// Create a slice with ps empty elements
empties := make([]T, ps)
for i := range empties {
empties[i] = empty
}
// Insert the empties at the specified row and column
inserted := append(arr[row][:col], append(empties, arr[row][col:]...)...)
// clip the row to the length of the original array
//
// NB: we don't actually need to handle wrapping. sh for example handles that
// automatically, by manually writing the next row and moving the cursor back
// up
arr[row] = inserted[:len(arr[row])]
}
func (v *Terminal) insertCharacters(n int) {
insertEmpties(v.Content, v.Cursor.Y, v.Cursor.X, n, ' ')
v.Format.Insert(v.Cursor.Y, v.Cursor.X, v.Cursor.F, n)
v.changed(v.Cursor.Y, false)
}
func (v *Terminal) deleteCharacters(n int) {
v.wrap = false // delete characters resets the wrap state.
deleteCharacters(v.Content, v.Cursor.Y, v.Cursor.X, n, ' ')
v.Format.Delete(v.Cursor.Y, v.Cursor.X, n)
v.changed(v.Cursor.Y, false)
}
func (v *Terminal) eraseCharacters(n int) {
v.wrap = false // erase characters resets the wrap state.
eraseCharacters(v.Content, v.Cursor.Y, v.Cursor.X, n, ' ')
for i := 0; i < n; i++ {
v.Format.Paint(v.Cursor.Y, v.Cursor.X+i, v.Cursor.F)
}
v.changed(v.Cursor.Y, false)
}
func (v *Terminal) insertLines(n int) {
v.ensureHeight(v.Cursor.Y + n)
start, end := v.scrollRegion()
if v.Cursor.Y < start || v.Cursor.Y > end {
return
}
v.wrap = false
insertLines(v.Content, v.Cursor.Y, n, start, end, ' ')
insertLinesShallow(v.Format.Rows, v.Cursor.Y, n, start, end, func() *Region {
return &Region{Size: v.Width, F: v.Cursor.F}
})
insertLinesShallow(v.Changes, v.Cursor.Y, n, start, end, func() uint64 {
return 1
})
}
func (v *Terminal) deleteLines(n int) {
start, end := v.scrollRegion()
if v.Cursor.Y < start || v.Cursor.Y > end {
return
}
v.wrap = false // delete lines resets the wrap state.
deleteLines(v.Content, v.Cursor.Y, n, start, end, ' ')
deleteLinesShallow(v.Format.Rows, v.Cursor.Y, n, start, end, func() *Region {
return &Region{Size: v.Width, F: v.Cursor.F}
})
deleteLinesShallow(v.Changes, v.Cursor.Y, n, start, end, func() uint64 {
return 1
})
}
func (v *Terminal) scrollDownN(n int) {
v.wrap = false // scroll down resets the wrap state.
start, end := v.scrollRegion()
scrollDown(v.Content, n, start, end, ' ')
scrollDownShallow(v.Format.Rows, n, start, end, func() *Region {
return &Region{Size: v.Width, F: v.Cursor.F}
})
scrollDownShallow(v.Changes, n, start, end, func() uint64 {
return 1
})
}
func (v *Terminal) scrollUpN(n int) {
if v.onScrollback != nil {
for i := 0; i < n; i++ {
// v.onScrollback(Line{v.Content[i], v.Format[i]})
}
}
// v.wrap = false // scroll up does NOT reset the wrap state.
start, end := v.scrollRegion()
scrollUp(v.Content, n, start, end, ' ')
scrollUpShallow(v.Format.Rows, n, start, end, func() *Region {
return &Region{Size: v.Width, F: v.Cursor.F}
})
scrollUpShallow(v.Changes, n, start, end, func() uint64 {
return 1
})
}
func (v *Terminal) scrollRegion() (int, int) {
if v.ScrollRegion == nil {
return 0, v.Height - 1
} else {
return v.ScrollRegion.Start, v.ScrollRegion.End
}
}
func (v *Terminal) scrollOne() {
v.scrollUpN(1)
v.Cursor.Y = v.Height - 1
}
func (v *Terminal) home(y, x int) {
v.wrap = false // cursor movement always resets the wrap state.
v.moveAbs(y, x)
}
// eraseDirection is the logical direction in which an erase command happens,
// from the cursor. For both erase commands, forward is 0, backward is 1,
// and everything is 2.
type eraseDirection int
const (
// From the cursor to the end, inclusive.
eraseForward eraseDirection = iota
// From the beginning to the cursor, inclusive.
eraseBack
// Everything.
eraseAll
)
func (v *Terminal) eraseRegion(y1, x1, y2, x2 int) {
// Erasing lines and columns clears the wrap state.
v.wrap = false
if y1 > y2 && y2 > 0 {
y1, y2 = y2, y1
}
if x1 > x2 && x2 > 0 {
x1, x2 = x2, x1
}
f := v.Cursor.F
for y := y1; y <= y2; y++ {
if len(v.Content) <= y {
continue
}
rowX2 := x2
if rowX2 < 0 {
// to handle dynamic width, assume "clear to end"
rowX2 = len(v.Content[y]) - 1
}
for x := x1; x <= rowX2; x++ {
v.clear(y, x, f)
}
}
}
func (v *Terminal) moveDown() {
if v.ScrollRegion != nil && v.Cursor.Y == v.ScrollRegion.End {
// if we're at the bottom of the scroll region, scroll it instead of
// moving the cursor, so the cursor stays at the bottom of the scroll
// region
v.scrollUpN(1)
} else if v.Cursor.Y == v.Height-1 && !v.AutoResizeY {
// if we're at the bottom of the entire screen, and we're not
// configured to auto-resize, scroll the screen
v.scrollUpN(1)
} else {
v.moveRel(1, 0)
}
}
func (v *Terminal) moveUp() {
if v.Cursor.Y == 0 || v.ScrollRegion != nil && v.Cursor.Y == v.ScrollRegion.Start {
// if we're at the bottom of the scroll region, scroll it instead of
// moving the cursor
v.scrollDownN(1)
} else {
v.moveRel(-1, 0)
}
}
func (v *Terminal) save() {
v.SavedCursor = v.Cursor
}
func (v *Terminal) unsave() {
v.Cursor = v.SavedCursor
}