Debian Codegraph @

state.go

raw
1 package terminal
2
3 import (
4 "log"
5 "sync"
6 )
7
8 const (
9 tabspaces = 8
10 )
11
12 const (
13 attrReverse = 1 << iota
14 attrUnderline
15 attrBold
16 attrGfx
17 attrItalic
18 attrBlink
19 attrWrap
20 )
21
22 const (
23 cursorDefault = 1 << iota
24 cursorWrapNext
25 cursorOrigin
26 )
27
28 // ModeFlag represents various terminal mode states.
29 type ModeFlag uint32
30
31 // Terminal modes
32 const (
33 ModeWrap ModeFlag = 1 << iota
34 ModeInsert
35 ModeAppKeypad
36 ModeAltScreen
37 ModeCRLF
38 ModeMouseButton
39 ModeMouseMotion
40 ModeReverse
41 ModeKeyboardLock
42 ModeHide
43 ModeEcho
44 ModeAppCursor
45 ModeMouseSgr
46 Mode8bit
47 ModeBlink
48 ModeFBlink
49 ModeFocus
50 ModeMouseX10
51 ModeMouseMany
52 ModeMouseMask = ModeMouseButton | ModeMouseMotion | ModeMouseX10 | ModeMouseMany
53 )
54
55 // ChangeFlag represents possible state changes of the terminal.
56 type ChangeFlag uint32
57
58 // Terminal changes to occur in VT.ReadState
59 const (
60 ChangedScreen ChangeFlag = 1 << iota
61 ChangedTitle
62 )
63
64 type glyph struct {
65 c rune
66 mode int16
67 fg, bg Color
68 }
69
70 type line []glyph
71
72 type cursor struct {
73 attr glyph
74 x, y int
75 state uint8
76 }
77
78 type parseState func(c rune)
79
80 // State represents the terminal emulation state. Use Lock/Unlock
81 // methods to synchronize data access with VT.
82 type State struct {
83 DebugLogger *log.Logger
84
85 mu sync.Mutex
86 changed ChangeFlag
87 cols, rows int
88 lines []line
89 altLines []line
90 dirty []bool // line dirtiness
91 anydirty bool
92 cur, curSaved cursor
93 top, bottom int // scroll limits
94 mode ModeFlag
95 state parseState
96 str strEscape
97 csi csiEscape
98 numlock bool
99 tabs []bool
100 title string
101 }
102
103 func (t *State) logf(format string, args ...interface{}) {
104 if t.DebugLogger != nil {
105 t.DebugLogger.Printf(format, args...)
106 }
107 }
108
109 func (t *State) logln(s string) {
110 if t.DebugLogger != nil {
111 t.DebugLogger.Println(s)
112 }
113 }
114
115 func (t *State) lock() {
116 t.mu.Lock()
117 }
118
119 func (t *State) unlock() {
120 t.mu.Unlock()
121 }
122
123 // Lock locks the state object's mutex.
124 func (t *State) Lock() {
125 t.mu.Lock()
126 }
127
128 // Unlock resets change flags and unlocks the state object's mutex.
129 func (t *State) Unlock() {
130 t.resetChanges()
131 t.mu.Unlock()
132 }
133
134 // Cell returns the character code, foreground color, and background
135 // color at position (x, y) relative to the top left of the terminal.
136 func (t *State) Cell(x, y int) (ch rune, fg Color, bg Color) {
137 return t.lines[y][x].c, Color(t.lines[y][x].fg), Color(t.lines[y][x].bg)
138 }
139
140 // Cursor returns the current position of the cursor.
141 func (t *State) Cursor() (int, int) {
142 return t.cur.x, t.cur.y
143 }
144
145 // CursorVisible returns the visible state of the cursor.
146 func (t *State) CursorVisible() bool {
147 return t.mode&ModeHide == 0
148 }
149
150 // Mode tests if mode is currently set.
151 func (t *State) Mode(mode ModeFlag) bool {
152 return t.mode&mode != 0
153 }
154
155 // Title returns the current title set via the tty.
156 func (t *State) Title() string {
157 return t.title
158 }
159
160 /*
161 // ChangeMask returns a bitfield of changes that have occured by VT.
162 func (t *State) ChangeMask() ChangeFlag {
163 return t.changed
164 }
165 */
166
167 // Changed returns true if change has occured.
168 func (t *State) Changed(change ChangeFlag) bool {
169 return t.changed&change != 0
170 }
171
172 // resetChanges resets the change mask and dirtiness.
173 func (t *State) resetChanges() {
174 for i := range t.dirty {
175 t.dirty[i] = false
176 }
177 t.anydirty = false
178 t.changed = 0
179 }
180
181 func (t *State) saveCursor() {
182 t.curSaved = t.cur
183 }
184
185 func (t *State) restoreCursor() {
186 t.cur = t.curSaved
187 t.moveTo(t.cur.x, t.cur.y)
188 }
189
190 func (t *State) put(c rune) {
191 t.state(c)
192 }
193
194 func (t *State) putTab(forward bool) {
195 x := t.cur.x
196 if forward {
197 if x == t.cols {
198 return
199 }
200 for x++; x < t.cols && !t.tabs[x]; x++ {
201 }
202 } else {
203 if x == 0 {
204 return
205 }
206 for x--; x > 0 && !t.tabs[x]; x-- {
207 }
208 }
209 t.moveTo(x, t.cur.y)
210 }
211
212 func (t *State) newline(firstCol bool) {
213 y := t.cur.y
214 if y == t.bottom {
215 cur := t.cur
216 t.cur = t.defaultCursor()
217 t.ScrollUp(t.top, 1)
218 t.cur = cur
219 } else {
220 y++
221 }
222 if firstCol {
223 t.moveTo(0, y)
224 } else {
225 t.moveTo(t.cur.x, y)
226 }
227 }
228
229 // table from st, which in turn is from rxvt :)
230 var gfxCharTable = [62]rune{
231 '↑', '↓', '→', '←', '█', '▚', '☃', // A - G
232 0, 0, 0, 0, 0, 0, 0, 0, // H - O
233 0, 0, 0, 0, 0, 0, 0, 0, // P - W
234 0, 0, 0, 0, 0, 0, 0, ' ', // X - _
235 '◆', '▒', '␉', '␌', '␍', '␊', '°', '±', // ` - g
236 '␤', '␋', '┘', '┐', '┌', '└', '┼', '⎺', // h - o
237 '⎻', '─', '⎼', '⎽', '├', '┤', '┴', '┬', // p - w
238 '│', '≤', '≥', 'π', '≠', '£', '·', // x - ~
239 }
240
241 func (t *State) setChar(c rune, attr *glyph, x, y int) {
242 if attr.mode&attrGfx != 0 {
243 if c >= 0x41 && c <= 0x7e && gfxCharTable[c-0x41] != 0 {
244 c = gfxCharTable[c-0x41]
245 }
246 }
247 t.changed |= ChangedScreen
248 t.dirty[y] = true
249 t.lines[y][x] = *attr
250 t.lines[y][x].c = c
251 //if t.options.BrightBold && attr.mode&attrBold != 0 && attr.fg < 8 {
252 if attr.mode&attrBold != 0 && attr.fg < 8 {
253 t.lines[y][x].fg = attr.fg + 8
254 }
255 if attr.mode&attrReverse != 0 {
256 t.lines[y][x].fg = attr.bg
257 t.lines[y][x].bg = attr.fg
258 }
259 }
260
261 func (t *State) defaultCursor() cursor {
262 c := cursor{}
263 c.attr.fg = DefaultFG
264 c.attr.bg = DefaultBG
265 return c
266 }
267
268 func (t *State) reset() {
269 t.cur = t.defaultCursor()
270 t.saveCursor()
271 for i := range t.tabs {
272 t.tabs[i] = false
273 }
274 for i := tabspaces; i < len(t.tabs); i += tabspaces {
275 t.tabs[i] = true
276 }
277 t.top = 0
278 t.bottom = t.rows - 1
279 t.mode = ModeWrap
280 t.clear(0, 0, t.rows-1, t.cols-1)
281 t.moveTo(0, 0)
282 }
283
284 // TODO: definitely can improve allocs
285 func (t *State) resize(cols, rows int) bool {
286 if cols == t.cols && rows == t.rows {
287 return false
288 }
289 if cols < 1 || rows < 1 {
290 return false
291 }
292 slide := t.cur.y - rows + 1
293 if slide > 0 {
294 copy(t.lines, t.lines[slide:slide+rows])
295 copy(t.altLines, t.altLines[slide:slide+rows])
296 }
297
298 lines, altLines, tabs := t.lines, t.altLines, t.tabs
299 t.lines = make([]line, rows)
300 t.altLines = make([]line, rows)
301 t.dirty = make([]bool, rows)
302 t.tabs = make([]bool, cols)
303
304 minrows := min(rows, t.rows)
305 mincols := min(cols, t.cols)
306 t.changed |= ChangedScreen
307 for i := 0; i < rows; i++ {
308 t.dirty[i] = true
309 t.lines[i] = make(line, cols)
310 t.altLines[i] = make(line, cols)
311 }
312 for i := 0; i < minrows; i++ {
313 copy(t.lines[i], lines[i])
314 copy(t.altLines[i], altLines[i])
315 }
316 copy(t.tabs, tabs)
317 if cols > t.cols {
318 i := t.cols - 1
319 for i > 0 && !tabs[i] {
320 i--
321 }
322 for i += tabspaces; i < len(tabs); i += tabspaces {
323 tabs[i] = true
324 }
325 }
326
327 t.cols = cols
328 t.rows = rows
329 t.setScroll(0, rows-1)
330 t.moveTo(t.cur.x, t.cur.y)
331 for i := 0; i < 2; i++ {
332 if mincols < cols && minrows > 0 {
333 t.clear(mincols, 0, cols-1, minrows-1)
334 }
335 if cols > 0 && minrows < rows {
336 t.clear(0, minrows, cols-1, rows-1)
337 }
338 t.swapScreen()
339 }
340 return slide > 0
341 }
342
343 func (t *State) clear(x0, y0, x1, y1 int) {
344 if x0 > x1 {
345 x0, x1 = x1, x0
346 }
347 if y0 > y1 {
348 y0, y1 = y1, y0
349 }
350 x0 = clamp(x0, 0, t.cols-1)
351 x1 = clamp(x1, 0, t.cols-1)
352 y0 = clamp(y0, 0, t.rows-1)
353 y1 = clamp(y1, 0, t.rows-1)
354 t.changed |= ChangedScreen
355 for y := y0; y <= y1; y++ {
356 t.dirty[y] = true
357 for x := x0; x <= x1; x++ {
358 t.lines[y][x] = t.cur.attr
359 t.lines[y][x].c = ' '
360 }
361 }
362 }
363
364 func (t *State) clearAll() {
365 t.clear(0, 0, t.cols-1, t.rows-1)
366 }
367
368 func (t *State) moveAbsTo(x, y int) {
369 if t.cur.state&cursorOrigin != 0 {
370 y += t.top
371 }
372 t.moveTo(x, y)
373 }
374
375 func (t *State) moveTo(x, y int) {
376 var miny, maxy int
377 if t.cur.state&cursorOrigin != 0 {
378 miny = t.top
379 maxy = t.bottom
380 } else {
381 miny = 0
382 maxy = t.rows - 1
383 }
384 x = clamp(x, 0, t.cols-1)
385 y = clamp(y, miny, maxy)
386 t.changed |= ChangedScreen
387 t.cur.state &^= cursorWrapNext
388 t.cur.x = x
389 t.cur.y = y
390 }
391
392 func (t *State) swapScreen() {
393 t.lines, t.altLines = t.altLines, t.lines
394 t.mode ^= ModeAltScreen
395 t.dirtyAll()
396 }
397
398 func (t *State) dirtyAll() {
399 t.changed |= ChangedScreen
400 for y := 0; y < t.rows; y++ {
401 t.dirty[y] = true
402 }
403 }
404
405 func (t *State) setScroll(top, bottom int) {
406 top = clamp(top, 0, t.rows-1)
407 bottom = clamp(bottom, 0, t.rows-1)
408 if top > bottom {
409 top, bottom = bottom, top
410 }
411 t.top = top
412 t.bottom = bottom
413 }
414
415 func min(a, b int) int {
416 if a < b {
417 return a
418 }
419 return b
420 }
421
422 func max(a, b int) int {
423 if a > b {
424 return a
425 }
426 return b
427 }
428
429 func clamp(val, min, max int) int {
430 if val < min {
431 return min
432 } else if val > max {
433 return max
434 }
435 return val
436 }
437
438 func between(val, min, max int) bool {
439 if val < min || val > max {
440 return false
441 }
442 return true
443 }
444
445 func (t *State) ScrollDown(orig, n int) {
446 n = clamp(n, 0, t.bottom-orig+1)
447 t.clear(0, t.bottom-n+1, t.cols-1, t.bottom)
448 t.changed |= ChangedScreen
449 for i := t.bottom; i >= orig+n; i-- {
450 t.lines[i], t.lines[i-n] = t.lines[i-n], t.lines[i]
451 t.dirty[i] = true
452 t.dirty[i-n] = true
453 }
454
455 // TODO: selection scroll
456 }
457
458 func (t *State) ScrollUp(orig, n int) {
459 n = clamp(n, 0, t.bottom-orig+1)
460 t.clear(0, orig, t.cols-1, orig+n-1)
461 t.changed |= ChangedScreen
462 for i := orig; i <= t.bottom-n; i++ {
463 t.lines[i], t.lines[i+n] = t.lines[i+n], t.lines[i]
464 t.dirty[i] = true
465 t.dirty[i+n] = true
466 }
467
468 // TODO: selection scroll
469 }
470
471 func (t *State) modMode(set bool, bit ModeFlag) {
472 if set {
473 t.mode |= bit
474 } else {
475 t.mode &^= bit
476 }
477 }
478
479 func (t *State) setMode(priv bool, set bool, args []int) {
480 if priv {
481 for _, a := range args {
482 switch a {
483 case 1: // DECCKM - cursor key
484 t.modMode(set, ModeAppCursor)
485 case 5: // DECSCNM - reverse video
486 mode := t.mode
487 t.modMode(set, ModeReverse)
488 if mode != t.mode {
489 // TODO: redraw
490 }
491 case 6: // DECOM - origin
492 if set {
493 t.cur.state |= cursorOrigin
494 } else {
495 t.cur.state &^= cursorOrigin
496 }
497 t.moveAbsTo(0, 0)
498 case 7: // DECAWM - auto wrap
499 t.modMode(set, ModeWrap)
500 // IGNORED:
501 case 0, // error
502 2, // DECANM - ANSI/VT52
503 3, // DECCOLM - column
504 4, // DECSCLM - scroll
505 8, // DECARM - auto repeat
506 18, // DECPFF - printer feed
507 19, // DECPEX - printer extent
508 42, // DECNRCM - national characters
509 12: // att610 - start blinking cursor
510 break
511 case 25: // DECTCEM - text cursor enable mode
512 t.modMode(!set, ModeHide)
513 case 9: // X10 mouse compatibility mode
514 t.modMode(false, ModeMouseMask)
515 t.modMode(set, ModeMouseX10)
516 case 1000: // report button press
517 t.modMode(false, ModeMouseMask)
518 t.modMode(set, ModeMouseButton)
519 case 1002: // report motion on button press
520 t.modMode(false, ModeMouseMask)
521 t.modMode(set, ModeMouseMotion)
522 case 1003: // enable all mouse motions
523 t.modMode(false, ModeMouseMask)
524 t.modMode(set, ModeMouseMany)
525 case 1004: // send focus events to tty
526 t.modMode(set, ModeFocus)
527 case 1006: // extended reporting mode
528 t.modMode(set, ModeMouseSgr)
529 case 1034:
530 t.modMode(set, Mode8bit)
531 case 1049, // = 1047 and 1048
532 47, 1047:
533 alt := t.mode&ModeAltScreen != 0
534 if alt {
535 t.clear(0, 0, t.cols-1, t.rows-1)
536 }
537 if !set || !alt {
538 t.swapScreen()
539 }
540 if a != 1049 {
541 break
542 }
543 fallthrough
544 case 1048:
545 if set {
546 t.saveCursor()
547 } else {
548 t.restoreCursor()
549 }
550 case 1001:
551 // mouse highlight mode; can hang the terminal by design when
552 // implemented
553 case 1005:
554 // utf8 mouse mode; will confuse applications not supporting
555 // utf8 and luit
556 case 1015:
557 // urxvt mangled mouse mode; incompatiblt and can be mistaken
558 // for other control codes
559 default:
560 t.logf("unknown private set/reset mode %d\n", a)
561 }
562 }
563 } else {
564 for _, a := range args {
565 switch a {
566 case 0: // Error (ignored)
567 case 2: // KAM - keyboard action
568 t.modMode(set, ModeKeyboardLock)
569 case 4: // IRM - insertion-replacement
570 t.modMode(set, ModeInsert)
571 t.logln("insert mode not implemented")
572 case 12: // SRM - send/receive
573 t.modMode(set, ModeEcho)
574 case 20: // LNM - linefeed/newline
575 t.modMode(set, ModeCRLF)
576 case 34:
577 t.logln("right-to-left mode not implemented")
578 case 96:
579 t.logln("right-to-left copy mode not implemented")
580 default:
581 t.logf("unknown set/reset mode %d\n", a)
582 }
583 }
584 }
585 }
586
587 func (t *State) setAttr(attr []int) {
588 if len(attr) == 0 {
589 attr = []int{0}
590 }
591 for i := 0; i < len(attr); i++ {
592 a := attr[i]
593 switch a {
594 case 0:
595 t.cur.attr.mode &^= attrReverse | attrUnderline | attrBold | attrItalic | attrBlink
596 t.cur.attr.fg = DefaultFG
597 t.cur.attr.bg = DefaultBG
598 case 1:
599 t.cur.attr.mode |= attrBold
600 case 3:
601 t.cur.attr.mode |= attrItalic
602 case 4:
603 t.cur.attr.mode |= attrUnderline
604 case 5, 6: // slow, rapid blink
605 t.cur.attr.mode |= attrBlink
606 case 7:
607 t.cur.attr.mode |= attrReverse
608 case 21, 22:
609 t.cur.attr.mode &^= attrBold
610 case 23:
611 t.cur.attr.mode &^= attrItalic
612 case 24:
613 t.cur.attr.mode &^= attrUnderline
614 case 25, 26:
615 t.cur.attr.mode &^= attrBlink
616 case 27:
617 t.cur.attr.mode &^= attrReverse
618 case 38:
619 if i+2 < len(attr) && attr[i+1] == 5 {
620 i += 2
621 if between(attr[i], 0, 255) {
622 t.cur.attr.fg = Color(attr[i])
623 } else {
624 t.logf("bad fgcolor %d\n", attr[i])
625 }
626 } else {
627 t.logf("gfx attr %d unknown\n", a)
628 }
629 case 39:
630 t.cur.attr.fg = DefaultFG
631 case 48:
632 if i+2 < len(attr) && attr[i+1] == 5 {
633 i += 2
634 if between(attr[i], 0, 255) {
635 t.cur.attr.bg = Color(attr[i])
636 } else {
637 t.logf("bad bgcolor %d\n", attr[i])
638 }
639 } else {
640 t.logf("gfx attr %d unknown\n", a)
641 }
642 case 49:
643 t.cur.attr.bg = DefaultBG
644 default:
645 if between(a, 30, 37) {
646 t.cur.attr.fg = Color(a - 30)
647 } else if between(a, 40, 47) {
648 t.cur.attr.bg = Color(a - 40)
649 } else if between(a, 90, 97) {
650 t.cur.attr.fg = Color(a - 90 + 8)
651 } else if between(a, 100, 107) {
652 t.cur.attr.bg = Color(a - 100 + 8)
653 } else {
654 t.logf("gfx attr %d unknown\n", a)
655 }
656 }
657 }
658 }
659
660 func (t *State) insertBlanks(n int) {
661 src := t.cur.x
662 dst := src + n
663 size := t.cols - dst
664 t.changed |= ChangedScreen
665 t.dirty[t.cur.y] = true
666
667 if dst >= t.cols {
668 t.clear(t.cur.x, t.cur.y, t.cols-1, t.cur.y)
669 } else {
670 copy(t.lines[t.cur.y][dst:dst+size], t.lines[t.cur.y][src:src+size])
671 t.clear(src, t.cur.y, dst-1, t.cur.y)
672 }
673 }
674
675 func (t *State) insertBlankLines(n int) {
676 if t.cur.y < t.top || t.cur.y > t.bottom {
677 return
678 }
679 t.ScrollDown(t.cur.y, n)
680 }
681
682 func (t *State) deleteLines(n int) {
683 if t.cur.y < t.top || t.cur.y > t.bottom {
684 return
685 }
686 t.ScrollUp(t.cur.y, n)
687 }
688
689 func (t *State) deleteChars(n int) {
690 src := t.cur.x + n
691 dst := t.cur.x
692 size := t.cols - src
693 t.changed |= ChangedScreen
694 t.dirty[t.cur.y] = true
695
696 if src >= t.cols {
697 t.clear(t.cur.x, t.cur.y, t.cols-1, t.cur.y)
698 } else {
699 copy(t.lines[t.cur.y][dst:dst+size], t.lines[t.cur.y][src:src+size])
700 t.clear(t.cols-n, t.cur.y, t.cols-1, t.cur.y)
701 }
702 }
703
704 func (t *State) setTitle(title string) {
705 t.changed |= ChangedTitle
706 t.title = title
707 }