Debian Codegraph @

vt/emulate.go

raw symbols SCIP
1 // Copyright 2026 The TCell Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package vt
16
17 import (
18 "bytes"
19 "encoding/base64"
20 "errors"
21 "fmt"
22 "io"
23 "slices"
24 "strconv"
25 "strings"
26 "sync"
27 "unicode"
28 "unicode/utf8"
29
30 "github.com/clipperhouse/uax29/v2/graphemes"
31 "github.com/gdamore/tcell/v3/color"
32 )
33
34 // Emulator is a terminal emulator API. It implements the state machinery
35 // (escape parsing and so forth) associated with being a terminal emulator.
36 // The backend handles rendering the content, and some low level details.
37 //
38 // NOTE: This is not a committed interface yet, its entirely a work in progress.
39 type Emulator interface {
40 // SetId sets our identity.
41 SetId(name string, version string)
42
43 // SendRaw sends raw data to the consumer. This bypasses the normal encoding,
44 // so it should be used with caution.
45 SendRaw([]byte)
46
47 // KeyEvent injects a keyboard event into the emulator, which will ultimately
48 // result in data being sent via SendRaw.
49 KeyEvent(ev KeyEvent)
50
51 // ResizeEvent is called by a backend when the terminal has resized
52 // This will send in-band resize notifications if the client has requested them.
53 ResizeEvent(Coord)
54
55 // MouseEvent is called by a backend to report mouse activity.
56 MouseEvent(ev MouseEvent)
57
58 // FocusEvent is called by a backend to report that focus is gained (true) or lost (false).
59 FocusEvent(bool)
60
61 // Drain waits until any queued but not processed input has finished processing.
62 // It also wakes the reader.
63 Drain() error
64
65 // Start starts processing.
66 Start() error
67
68 // Stop stops processing.
69 Stop() error
70
71 // Reader reads data from the emulator. These are bytes that would be transmitted
72 // to a remote party.
73 io.Reader
74
75 // Writer writes data to the emulator. These are commands that the emulator should process.
76 io.Writer
77 }
78
79 // Style represents the styling of a cell.
80 // This is an interface to prevent direct modification.
81 type Style interface {
82 Fg() color.Color // Fg returns the foreground color.
83 Bg() color.Color // Bg returns the background color.
84 Uc() color.Color // Uc returns the underline color.k
85 Attr() Attr // Attr returns the associated attributes.
86 Url() (string, string) // Url returns the URL and associated id if one was set.
87 WithFg(color.Color) Style // WithFg creates a new style with the foreground
88 WithBg(color.Color) Style // WithBg creates a new style with the background.
89 WithUc(color.Color) Style // WithUc creates a new style with the underline color
90 WithAttr(Attr) Style // WithAttr creates a new style with the attributes.
91 WithUrl(string, string) Style // WithLink creates a new style with the URL and id.
92 Equal(Style) bool // Equal returns true if the styles are the same.
93 }
94
95 // styleStruct implements Style. Note that it is possible to make this even more
96 // compact, but we don't think further optimization here on size will justify the
97 // complexity and runtime performance hit to do so. We're also already only storing
98 // a class reference to this per cell.
99 type styleStruct struct {
100 fg color.Color
101 bg color.Color
102 uc color.Color // underline color
103 attr Attr
104 url string // URL
105 id string // Id for link
106 }
107
108 var BaseStyle = &styleStruct{}
109
110 var asciiRuneStrings = func() [utf8.RuneSelf]string {
111 var table [utf8.RuneSelf]string
112 for i := 0; i < utf8.RuneSelf; i++ {
113 table[i] = string(rune(i))
114 }
115 return table
116 }()
117
118 const (
119 runeStringCacheSize = 32
120 clusterStringCacheSize = 32
121 clusterStringCacheMaxLen = 128
122 )
123
124 type runeStringCache struct {
125 entries [runeStringCacheSize]runeStringCacheEntry
126 n int
127 }
128
129 type runeStringCacheEntry struct {
130 r rune
131 s string
132 }
133
134 func (c *runeStringCache) stringFor(r rune) string {
135 for i := 0; i < c.n; i++ {
136 if c.entries[i].r == r {
137 return c.entries[i].s
138 }
139 }
140
141 s := string(r)
142 n := c.n
143 if n < len(c.entries) {
144 n++
145 }
146 copy(c.entries[1:n], c.entries[:n-1])
147 c.entries[0] = runeStringCacheEntry{r: r, s: s}
148 c.n = n
149 return s
150 }
151
152 type clusterStringCache struct {
153 entries [clusterStringCacheSize]clusterStringCacheEntry
154 n int
155 }
156
157 type clusterStringCacheEntry struct {
158 n int
159 b [clusterStringCacheMaxLen]byte
160 s string
161 }
162
163 func (c *clusterStringCache) stringFor(cluster []byte) string {
164 if len(cluster) == 0 {
165 return ""
166 }
167 if len(cluster) > clusterStringCacheMaxLen {
168 return string(cluster)
169 }
170 for i := 0; i < c.n; i++ {
171 e := &c.entries[i]
172 if e.n == len(cluster) && bytes.Equal(e.b[:e.n], cluster) {
173 return e.s
174 }
175 }
176
177 s := string(cluster)
178 n := c.n
179 if n < len(c.entries) {
180 n++
181 }
182 copy(c.entries[1:n], c.entries[:n-1])
183 e := &c.entries[0]
184 e.n = len(cluster)
185 copy(e.b[:], cluster)
186 e.s = s
187 c.n = n
188 return s
189 }
190
191 func (ss *styleStruct) Fg() color.Color { return ss.fg }
192 func (ss *styleStruct) Bg() color.Color { return ss.bg }
193 func (ss *styleStruct) Uc() color.Color { return ss.uc }
194 func (ss *styleStruct) Attr() Attr { return ss.attr }
195 func (ss *styleStruct) Url() (string, string) { return ss.url, ss.id }
196 func (ss *styleStruct) WithFg(fg color.Color) Style { ns := *ss; ns.fg = fg; return &ns }
197 func (ss *styleStruct) WithBg(bg color.Color) Style { ns := *ss; ns.bg = bg; return &ns }
198 func (ss *styleStruct) WithUc(uc color.Color) Style { ns := *ss; ns.uc = uc; return &ns }
199 func (ss *styleStruct) WithAttr(a Attr) Style { ns := *ss; ns.attr = a; return &ns }
200 func (ss *styleStruct) WithUrl(url, id string) Style { ns := *ss; ns.url = url; ns.id = id; return &ns }
201 func (ss *styleStruct) Equal(other Style) bool {
202 if s2, ok := other.(*styleStruct); ok {
203 return *ss == *s2
204 }
205 // We have chosen not to support alternative implementations for this compare.
206 // We could delegate to the other style, but that could lead to a loop if they
207 // do the same.
208 return (false)
209 }
210
211 // Cell is a representation of a display cell. Most consumers will not need this.
212 // Note, this is not the simplest possible representation, and a 256x256 cell
213 // display is going to need about 3MB to store it all, but it's simple, and adequate
214 // to retain pretty much all of what we need for Unicode. We could save some memory
215 // by using explicit struct pointers and by eliminating grapheme cluster support,
216 // but modern users expect these features.
217 type Cell struct {
218 C string // Content, it will be a grapheme cluster
219 S Style // Style, a pointer is used efficiency
220 W int // Display width (0, 1, or 2)
221 }
222
223 // EmulatorOpt configures an Emulator.
224 type EmulatorOpt interface {
225 setEmulatorOpt(*emulator)
226 }
227
228 // EmulatorOpt8BitControls enables parsing of C1 controls, such as CSI and OSC,
229 // when they are presented as raw 8-bit bytes or UTF-8 encoded C1 controls.
230 // The default is to only accept the 7-bit ESC-prefixed forms.
231 type EmulatorOpt8BitControls struct{}
232
233 func (EmulatorOpt8BitControls) setEmulatorOpt(em *emulator) {
234 em.c1Allowed = true
235 em.c1Enabled = true
236 }
237
238 // NewEmulator creates an emulator instance on top of the given backend.
239 // The input is relative to the emulator, so it receives data from the host,
240 // whereas the emulator sends data to the application through the output.
241 func NewEmulator(be Backend, opts ...EmulatorOpt) Emulator {
242 stopQ := make(chan bool)
243 defStyle := BaseStyle.WithFg(color.Silver).WithBg(color.Black)
244 em := &emulator{
245 be: be,
246 inBuf: &bytes.Buffer{},
247 writeQ: make(chan any),
248 readQ: make(chan any, 1024),
249 stopQ: stopQ,
250 style: defStyle,
251 defaultStyle: defStyle,
252 ansiModes: map[AnsiMode]ModeStatus{
253 AmNewLineMode: ModeOff,
254 },
255 localModes: map[PrivateMode]ModeStatus{
256 PmAppCursor: ModeOff,
257 PmAutoMargin: ModeOn,
258 PmAutoRepeat: ModeOn,
259 PmVT52: ModeOnLocked, // we never support VT52 mode (note ON means ANSI mode)
260 PmLeftRightMargin: ModeOff,
261 PmShowCursor: ModeOn,
262 PmBlinkCursor: ModeOn,
263 PmWin32Input: ModeOff,
264 },
265 mouseReports: MouseDisabled,
266 }
267 for _, opt := range opts {
268 opt.setEmulatorOpt(em)
269 }
270 if _, ok := be.(Resizer); ok {
271 em.localModes[PmResizeReports] = ModeOff
272 }
273
274 // add mouse modes - we also add focus reporting mode
275 if _, ok := be.(Mouser); ok {
276 em.localModes[PmMouseX10] = ModeOff
277 em.localModes[PmMouseButton] = ModeOff
278 em.localModes[PmMouseDrag] = ModeOff
279 em.localModes[PmMouseMotion] = ModeOff
280 em.localModes[PmMouseSgr] = ModeOff
281 em.localModes[PmFocusReports] = ModeOff
282 }
283
284 if ak, ok := be.(AdvancedKeyboard); ok && ak.IsAdvancedKeyboard() {
285 em.localModes[PmWin32Input] = ModeOff
286 }
287
288 em.size = em.be.GetSize()
289 em.topMargin = 0
290 em.botMargin = em.size.Y - 1
291 em.ltMargin = 0
292 em.rtMargin = em.size.X - 1
293 em.cells = make([]Cell, int(em.size.X)*int(em.size.Y))
294 em.graphemeIter = *graphemes.FromBytes(nil)
295 close(stopQ)
296 em.inb = em.inbInit
297 em.cursor = BlinkingBlock
298 em.be.SetCursor(em.cursor)
299 return em
300 }
301
302 // emulator is an implementation of a terminal emulator built on top of
303 // a Backend. It implements the common escape sequence handling and high
304 // level functionality that a real terminal emulator, or a mock, would need.
305 type emulator struct {
306 stopQ chan bool
307 writeQ chan any // queues data from application to emulator
308 readQ chan any // queues data from emulator to application
309 be Backend
310 inBuf *bytes.Buffer // buffer queued for input
311 inb func(byte) // input byte function (faster than state switch)
312 style Style
313 defaultStyle Style
314 utfLen int
315 pos Coord
316 buffering uint // reference count - number of (re-entrant) buffering calls
317 autoWrap bool // next character will wrap (auto margin, deferred until char emitted)
318 c1Allowed bool // allow C1 controls in raw 8-bit and UTF-8 encodings
319 c1Enabled bool // C1 controls are currently enabled
320 c1Prefix bool // string parser has seen the first byte of a UTF-8 encoded C1 control
321 appKeyPad bool // use application key pad keys?
322 name string // name of this emulator (used for extended attributes)
323 vers string // version string of this emulator (used for extended attributes)
324 saved savedCursor // data saved by save cursor (DECSC)
325 sendLock sync.Mutex // ensures that send data cannot be intermixed
326 modeLock sync.RWMutex // protects localModes/ansiModes and related derived state
327 tabStops []Col // tab stops, ordered. if nil every 8th position is used
328 lastIndex int // index of last cell written + 1 (for grapheme clustering) (zero means none)
329 graphemeBuf []byte // scratch buffer for grapheme clustering checks
330 graphemeIter graphemes.Iterator[[]byte]
331 runeStrings runeStringCache
332 clusterStrings clusterStringCache
333 cells []Cell // content of cells, we have to maintain our own copy (backend might or might not)
334 mouseReports MouseReporting // whether we have enabled mouse reports
335 size Coord // physical window size
336 topMargin Row // top margin, scrollable region includes this row
337 botMargin Row // bottom margin, scrollable region includes this row
338 ltMargin Col // left margin, scrollable region to the right
339 rtMargin Col // right margin, scrollable region to the left
340 cursor CursorStyle // current cursor style (visibility, blink, shape)
341
342 localModes map[PrivateMode]ModeStatus // some modes we handle locally
343 ansiModes map[AnsiMode]ModeStatus // some modes we handle locally
344 }
345
346 // savedCursor is the content we save when saving the cursor,
347 // which is more than just the cursor location itself.
348 type savedCursor struct {
349 pos Coord
350 style Style
351 autoWrap bool
352 // We should probably store OSC 8 data here, eventually.
353 // TODO: Character sets
354 // TODO: Origin mode (DEC Mode 6)
355 }
356
357 func (em *emulator) saveCursor() {
358 em.saved.pos = em.getPosition()
359 em.saved.style = em.style
360 em.saved.autoWrap = em.autoWrap
361 }
362
363 func (em *emulator) restoreCursor() {
364 em.setPosition(em.saved.pos)
365 em.autoWrap = em.saved.autoWrap
366 em.style = em.saved.style
367 }
368
369 func (em *emulator) bufferingStart() {
370 em.buffering++
371 if em.buffering == 1 {
372 em.be.Buffering(true)
373 }
374 }
375
376 func (em *emulator) bufferingEnd() {
377 em.buffering--
378 if em.buffering == 0 {
379 em.be.Buffering(false)
380 }
381 }
382
383 // inbInit processes bytes received in the "default" state. Most often these are just
384 // text characters to display on screen, but if ESC is seen then additional processing will result.
385 func (em *emulator) inbInit(b byte) {
386 em.inBuf.Reset()
387
388 // hot path - just doing ASCII directly.
389 if b >= ' ' && b < 0x7f {
390 // plain ascii
391 em.putRune(rune(b))
392 return
393 }
394
395 // For C1 controls, the raw 8-bit form is the same as ESC followed by
396 // (b - 0x40). This is disabled by default because modern protocols
397 // generally treat these forms as insecure.
398 if b >= 0x80 && b <= 0x9f {
399 if em.c1Enabled {
400 em.inbEsc(b - 0x40)
401 }
402 return
403 }
404
405 // TODO: To support non-UTF-8 locales, include a check here for > 0x7F. Those locales
406 // might preclude 8-bit control sequences - 8859 character sets are fine, but e.g. KOI8,
407 // and ShiftJIS use values in those ranges.
408
409 switch b {
410 case 0x1b: // ESC (escape)
411 em.inb = em.inbEsc
412 case 0x07: // BEL (bell)
413 em.beep()
414 case 0x08: // BS (backspace)
415 em.moveLeft()
416 case 0x09: // horizontal tab
417 em.nextTab()
418 case 0x0a, 0x0b, 0x0c: // LF (line feed), VF, FF
419 em.processLineFeed()
420 case 0x0d: // CR (carriage return)
421 em.processCarriageReturn()
422 case 0x0e: // TODO: SO
423 em.lastIndex = 0
424 case 0x0f: // TODO: SI
425 em.lastIndex = 0
426 case 0x18: //TODO Cancel (reset parser)
427 em.lastIndex = 0
428 default:
429 // TODO: consider separating Unicode from other 8-bit character sets
430 if b&0xE0 == 0xC0 {
431 em.utfLen = 2
432 em.inb = em.inbUTF
433 em.inBuf.WriteByte(b)
434 } else if b&0xF0 == 0xE0 {
435 em.utfLen = 3
436 em.inb = em.inbUTF
437 em.inBuf.WriteByte(b)
438 } else if b&0xF8 == 0xF0 {
439 em.utfLen = 4
440 em.inb = em.inbUTF
441 em.inBuf.WriteByte(b)
442 } else {
443 em.lastIndex = 0
444 em.beep()
445 }
446 }
447 }
448
449 // inbEsc processes the next byte after an escape character is seen.
450 func (em *emulator) inbEsc(b byte) {
451
452 // By default, reset to init state. Other states will be set explicitly as needed.
453 em.inb = em.inbInit
454 em.lastIndex = 0
455
456 switch b {
457 case '[':
458 em.inb = em.inbCSI
459 case ']':
460 em.inb = em.inbOSC
461 case ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/':
462 // 0x20 - 0x2F -- usually followed by just one terminating character, but could include others
463 em.inb = em.inbNF
464 em.inBuf.WriteByte(b)
465 case '^': // privacy message (PM)
466 em.inb = em.inbStr
467 case '_': // application program command (APC)
468 em.inb = em.inbStr
469 case '=':
470 em.appKeyPad = true
471 case '>':
472 em.appKeyPad = false
473 case 'D': // down one line (IND)
474 em.processIndex()
475 case 'E': // next line (NEL)
476 em.nextLine()
477 case 'H': // set tab stop (HTS) - VT52 is go home, but we do not support VT52
478 em.setTabStop(em.getPosition().X)
479 case 'M': // up one line (RI)
480 em.processReverseIndex()
481 case 'N': // single shift two (SS2) (TODO)
482 case 'O': // single shift three (SS3) (TODO)
483 case 'P':
484 em.inb = em.inbStr // device control string (DCS) (TODO)
485 case 'X': // start of string (SOS)
486 em.inb = em.inbStr
487 case 'Z': // DECID, obsolete form to get primary DA
488 em.sendDA()
489 case 'c': // RIS, soft reset
490 em.softReset()
491 case '6': // back index (DECBI, VT420, not widely supported)
492 em.moveLeft()
493 case '7': // save cursor (DECSC, VT100)
494 em.saveCursor()
495 case '8': // restore cursor (DECRC, VT100)
496 em.restoreCursor()
497 case '9': // forward index (DECFI, VT420, not widely supported)
498 em.moveRight()
499 default:
500 // ESC-V and ESC-W are for guarded area (TODO)
501 em.inb = em.inbInit
502 }
503 }
504
505 // inbNF processes bytes that are part of an "nF" sequence (see ECMA-48).
506 func (em *emulator) inbNF(b byte) {
507 if b >= 0x20 && b <= 0x2F {
508 em.inBuf.WriteByte(b)
509 return
510 }
511 if b < 0x20 || b > 0x7E { // not a valid sequence
512 em.beep()
513 em.inb = em.inbInit
514 return
515 }
516 em.inBuf.WriteByte(b)
517 em.inb = em.inbInit
518 switch em.inBuf.String() {
519 case "#8": // DECALN - fill screen with 'E'
520 size := em.size
521 em.autoWrap = false
522 em.topMargin = 0
523 em.botMargin = em.size.Y - 1
524 em.ltMargin = 0
525 em.rtMargin = em.size.X - 1
526 em.setPosition(Coord{0, 0})
527 em.style = em.style.WithAttr(Plain)
528 // TODO: Reset DECOM (when we implement origin mode)
529 for row := range size.Y {
530 ix := em.index(Coord{X: 0, Y: row})
531 for col := range size.X {
532 em.cells[ix].S = em.style
533 em.cells[ix].C = "E"
534 em.cells[ix].W = 1
535 em.be.Put(Coord{X: col, Y: row}, em.cells[ix])
536 ix++
537 }
538 }
539 // most implementations leave the cursor at home for this
540 em.setPosition(Coord{0, 0})
541
542 // case "%@": // TODO: select 8859-1
543 // case "%G": // TODO: select UTF-8
544 // case "(A": // TODO: select G0 as UK
545 // case "(B": // TODO: select G0 as US
546 // case "(C", "(5": // TODO: select G0 as Finnish
547 // case "(H", "(7": // TODO: select G0 as Swedish
548 // case "(K": // TODO: select G0 as German
549 // case "(Q", "(9": // TODO: select G0 as French Canadian
550 // case "(R", "(f": // TODO: select G0 as French
551 // case "(Y": // TODO: select G0 as Italian
552 case " F": // S7C1T - send/use 7-bit C1 controls
553 em.c1Enabled = false
554 case " G": // S8C1T - send/use 8-bit C1 controls
555 if em.c1Allowed {
556 em.c1Enabled = true
557 }
558 }
559 }
560
561 // inbCSI handles bytes that are part of a CSI based sequence.
562 func (em *emulator) inbCSI(b byte) {
563 if (b >= 0x30) && (b <= 0x3F) {
564 em.inBuf.WriteByte(b) // parameter bytes
565 } else if (b >= 0x20) && (b <= 0x2F) {
566 em.inBuf.WriteByte(b) // intermediate bytes
567 } else if b >= 0x40 && (b <= 0x7F) {
568 em.inb = em.inbInit
569 em.processCsi(b)
570 } else {
571 // error state
572 em.beep()
573 em.inb = em.inbInit
574 }
575 }
576
577 // inbOSC handles bytes that are part of on OSC sequences (operating system command).
578 func (em *emulator) inbOSC(b byte) {
579 if em.inbStringC1(b, em.processOSC) {
580 return
581 }
582
583 switch b {
584 case 0x9c:
585 if em.c1Enabled {
586 em.inb = em.inbInit
587 em.processOSC()
588 }
589 case 0x07:
590 em.inb = em.inbInit
591 em.processOSC()
592 case '\\':
593 if buf := em.inBuf.Bytes(); len(buf) > 0 && buf[len(buf)-1] == 0x1b {
594 em.inb = em.inbInit
595 em.inBuf.Truncate(em.inBuf.Len() - 1)
596 em.processOSC()
597 } else {
598 em.inBuf.WriteByte(b)
599 }
600 default:
601 em.inBuf.WriteByte(b)
602 }
603 }
604
605 // inbStr handles PM, SOS, and any other string we want to consume and discard.
606 func (em *emulator) inbStr(b byte) {
607 if em.inbStringC1(b, nil) {
608 return
609 }
610
611 switch b {
612 case 0x9c:
613 if em.c1Enabled {
614 em.inb = em.inbInit
615 }
616 case 0x07:
617 em.inb = em.inbInit
618 case '\\':
619 if buf := em.inBuf.Bytes(); len(buf) > 0 && buf[len(buf)-1] == 0x1b {
620 em.inb = em.inbInit
621 em.inBuf.Truncate(em.inBuf.Len() - 1)
622 } else {
623 em.inBuf.WriteByte(b)
624 }
625 default:
626 em.inBuf.WriteByte(b)
627 }
628 }
629
630 func (em *emulator) inbStringC1(b byte, done func()) bool {
631 if em.c1Prefix {
632 em.c1Prefix = false
633 if b >= 0x80 && b <= 0x9f {
634 if em.c1Enabled && b == 0x9c {
635 em.inb = em.inbInit
636 if done != nil {
637 done()
638 }
639 }
640 return true
641 }
642 em.inBuf.WriteByte(0xc2)
643 }
644 if b == 0xc2 {
645 em.c1Prefix = true
646 return true
647 }
648 return false
649 }
650
651 // inbUTF handles continuation bytes for UTF-8 sequences.
652 func (em *emulator) inbUTF(b byte) {
653 if b&0xC0 == 0x80 {
654 // good continuation byte
655 em.inBuf.WriteByte(b)
656 if em.inBuf.Len() == em.utfLen {
657 em.inb = em.inbInit
658 r, _, err := em.inBuf.ReadRune()
659 if err != nil {
660 em.beep()
661 } else {
662 if r >= 0x80 && r <= 0x9f {
663 if em.c1Enabled {
664 em.inbEsc(byte(r) - 0x40)
665 }
666 } else {
667 em.putRune(r)
668 }
669 }
670 }
671 } else {
672 em.beep()
673 em.inb = em.inbInit
674 }
675 }
676
677 func (em *emulator) beep() {
678 if beeper, ok := em.be.(Beeper); ok {
679 beeper.Beep()
680 }
681 }
682
683 // numericParams splits the string consisting of numeric parameters into integers.
684 // It ensures a minimum number are present (needed for some safety cases).
685 // Empty strings default to zero.
686 func numericParams(str string, minimumLen int) ([]int, error) {
687 ps := strings.Split(str, ";")
688 pi := make([]int, max(len(ps), minimumLen))
689 for i, str := range ps {
690 if str != "" {
691 if iv, err := strconv.Atoi(str); err != nil {
692 return nil, err
693 } else {
694 pi[i] = iv
695 }
696 }
697 }
698 return pi, nil
699 }
700
701 // parseSgrColor grabs either 2 arguments, or 4 arguments for palette or rgb values
702 // used with SGR 38 and 48. The arguments must be numbers, and are returned as such.
703 func (em *emulator) parseSgrColor(args []string, words []string) (color.Color, []string, error) {
704 if len(args) == 0 {
705 if len(words) == 0 {
706 return color.None, nil, errors.New("invalid color specification")
707 }
708
709 switch words[0] {
710 case "2": // RGB (direct)
711 if len(words) < 4 {
712 return color.None, nil, errors.New("invalid color specification")
713 }
714 args = words[:4]
715 words = words[4:]
716 case "5": // palette index
717 if len(words) < 2 {
718 return color.None, nil, errors.New("invalid color specification")
719 }
720 args = words[:2]
721 words = words[2:]
722 default:
723 return color.None, nil, errors.New("invalid color specification")
724 }
725 }
726
727 switch args[0] {
728 case "2": // RGB color
729 if len(args) < 4 || em.be.Colors() <= 256 {
730 return color.None, nil, errors.New("invalid color specification")
731 }
732 r, re := strconv.Atoi(args[1])
733 g, ge := strconv.Atoi(args[2])
734 b, be := strconv.Atoi(args[3])
735 if re != nil || ge != nil || be != nil || r > 255 || g > 255 || b > 255 || r < 0 || g < 0 || b < 0 {
736 return color.None, nil, errors.New("invalid color specification")
737 }
738 return color.NewRGBColor(int32(r), int32(g), int32(b)), words, nil
739 case "5": // palette index
740 if len(args) < 2 {
741 return color.None, nil, errors.New("invalid color specification")
742 }
743 p, e := strconv.Atoi(args[1])
744 if e != nil || p < 0 || p >= em.be.Colors() {
745 return color.None, nil, errors.New("invalid color specification")
746 }
747 return color.IsValid | color.Color(p&0xff), words, nil
748 }
749
750 return color.None, nil, errors.New("invalid color specification")
751 }
752
753 func (em *emulator) pickColor(c color.Color, def color.Color) (color.Color, bool) {
754 numColors := em.be.Colors()
755 if numColors == 0 {
756 return color.None, false
757 }
758 if c.Valid() {
759 if c.IsRGB() {
760 if numColors > 256 {
761 return c, true
762 }
763 }
764 if (int(c) & 255) < numColors {
765 return c, true
766 }
767 }
768 if c == color.Reset {
769 return def, true
770 }
771 return color.None, false
772 }
773
774 // processSgr processes SGR commands (things that change how characters are displayed).
775 func (em *emulator) processSgr(str string) {
776 words := strings.Split(str, ";")
777
778 // technically parameters for 38 or 48 should be separated by colons, but due to historical
779 // accident it is more common to see semicolon separation. Underline styles are also separated
780 // by a colon, if present.
781 if len(words) == 0 {
782 words = []string{"0"}
783 }
784 for len(words) > 0 {
785 // we do this instead of a range so we can lop off
786 // multiple words for SGR38 and 48.
787 word := words[0]
788 words = words[1:]
789
790 if word == "" {
791 word = "0"
792 }
793 args := []string(nil)
794 if strings.Contains(word, ":") {
795 args = strings.Split(word, ":")
796 word = args[0]
797 args = args[1:]
798 }
799
800 v, err := strconv.Atoi(word)
801 if err != nil {
802 // just swallow it for now
803 continue
804 }
805 switch v {
806 case 0:
807 em.style = em.defaultStyle
808 case 1:
809 em.style = em.style.WithAttr((em.style.Attr() &^ Dim) | Bold)
810 case 2:
811 em.style = em.style.WithAttr((em.style.Attr() &^ Bold) | Dim)
812 case 3:
813 em.style = em.style.WithAttr(em.style.Attr() | Italic)
814 case 4:
815 em.style = em.style.WithAttr((em.style.Attr() &^ UnderlineMask) | Underline)
816
817 if len(args) > 0 {
818 switch args[0] {
819 case "2":
820 em.style = em.style.WithAttr(em.style.Attr() | DoubleUnderline)
821 case "3":
822 em.style = em.style.WithAttr(em.style.Attr() | CurlyUnderline)
823 case "4":
824 em.style = em.style.WithAttr(em.style.Attr() | DottedUnderline)
825 case "5":
826 em.style = em.style.WithAttr(em.style.Attr() | DashedUnderline)
827 }
828 }
829 case 5, 6:
830 em.style = em.style.WithAttr(em.style.Attr() | Blink)
831 case 7:
832 em.style = em.style.WithAttr(em.style.Attr() | Reverse)
833 case 8: // ignore, its for invisible
834 case 9:
835 em.style = em.style.WithAttr(em.style.Attr() | StrikeThrough)
836 case 21: // Doubly underlined, per ECMA
837 em.style = em.style.WithAttr((em.style.Attr() &^ UnderlineMask) | DoubleUnderline)
838 case 22:
839 em.style = em.style.WithAttr(em.style.Attr() &^ (Bold | Dim))
840 case 23:
841 em.style = em.style.WithAttr(em.style.Attr() &^ Italic)
842 case 24:
843 em.style = em.style.WithAttr(em.style.Attr() &^ UnderlineMask)
844 case 25:
845 em.style = em.style.WithAttr(em.style.Attr() &^ Blink)
846 case 27:
847 em.style = em.style.WithAttr(em.style.Attr() &^ Reverse)
848 case 29:
849 em.style = em.style.WithAttr(em.style.Attr() &^ StrikeThrough)
850
851 case 30, 31, 32, 33, 34, 35, 36, 37: // simple foreground colors
852 if c, ok := em.pickColor(color.Black+color.Color(v-30), em.defaultStyle.Fg()); ok {
853 em.style = em.style.WithFg(c)
854 }
855 case 38:
856 if c, rest, err := em.parseSgrColor(args, words); err == nil {
857 words = rest
858 em.style = em.style.WithFg(c)
859 }
860 case 39:
861 if c, ok := em.pickColor(color.Reset, em.defaultStyle.Fg()); ok {
862 em.style = em.style.WithFg(c)
863 }
864 case 40, 41, 42, 43, 44, 45, 46, 47: // simple background colors
865 if c, ok := em.pickColor(color.Black+color.Color(v-40), em.defaultStyle.Bg()); ok {
866 em.style = em.style.WithBg(c)
867 }
868 case 48:
869 if c, rest, err := em.parseSgrColor(args, words); err == nil {
870 words = rest
871 em.style = em.style.WithBg(c)
872 }
873 case 49:
874 if c, ok := em.pickColor(color.Reset, em.defaultStyle.Bg()); ok {
875 em.style = em.style.WithBg(c)
876 }
877 case 53:
878 em.style = em.style.WithAttr(em.style.Attr() | Overline)
879 case 55:
880 em.style = em.style.WithAttr(em.style.Attr() &^ Overline)
881 case 58:
882 if c, rest, err := em.parseSgrColor(args, words); err == nil {
883 words = rest
884 em.style = em.style.WithUc(c)
885 }
886 }
887 }
888 }
889
890 // processCursorUp implements CUU.
891 func (em *emulator) processCursorUp(str string) {
892 if pi, err := numericParams(str, 1); err == nil {
893 em.autoWrap = false
894 em.moveUpN(Row(max(1, pi[0])))
895 }
896 }
897
898 // processCursorDown implements CUD.
899 func (em *emulator) processCursorDown(str string) {
900 if pi, err := numericParams(str, 1); err == nil {
901 em.autoWrap = false
902 em.moveDownN(Row(max(1, pi[0])))
903 }
904 }
905
906 // processCursorForward implements CUF.
907 func (em *emulator) processCursorForward(str string) {
908 if pi, err := numericParams(str, 1); err == nil {
909 em.autoWrap = false
910 em.moveRightN(Col(max(1, pi[0])))
911 }
912 }
913
914 // processCursorBackward implements CUB.
915 func (em *emulator) processCursorBackward(str string) {
916 if pi, err := numericParams(str, 1); err == nil {
917 em.autoWrap = false
918 em.moveLeftN(Col(max(1, pi[0])))
919 }
920 }
921
922 // processCursorNextLine implements CNL.
923 func (em *emulator) processCursorNextLine(str string) {
924 if pi, err := numericParams(str, 1); err == nil {
925 em.autoWrap = false
926 em.moveDownN(Row(max(1, pi[0])))
927 pos := em.getPosition()
928 pos.X = 0
929 em.setPosition(pos)
930 }
931 }
932
933 // processCursorPreviousLine implements CPL.
934 func (em *emulator) processCursorPreviousLine(str string) {
935 if pi, err := numericParams(str, 1); err == nil {
936 em.autoWrap = false
937 em.moveUpN(Row(max(1, pi[0])))
938 pos := em.getPosition()
939 pos.X = 0
940 em.setPosition(pos)
941 }
942 }
943
944 // processCursorColumn implements CHA.
945 func (em *emulator) processCursorColumn(str string) {
946 if pi, err := numericParams(str, 1); err == nil {
947 em.autoWrap = false
948 pos := em.getPosition()
949 // TODO: possibly clip to margins (origin mode)
950 pos.X = min(Col(max(1, pi[0])), em.size.X) - 1
951 em.setPosition(pos)
952 }
953 }
954
955 // processCursorPosition implements CUP, and also HVP.
956 func (em *emulator) processCursorPosition(str string) {
957 if pi, err := numericParams(str, 2); err == nil {
958 em.autoWrap = false
959 pos := em.getPosition()
960 wsz := em.size
961 row := Row(max(1, pi[0]))
962 col := Col(max(1, pi[1]))
963 row = max(1, min(row, wsz.Y))
964 col = max(1, min(col, wsz.X))
965 pos.X = col - 1
966 pos.Y = row - 1
967 em.setPosition(pos)
968 }
969 }
970
971 // processCursorTab implements CHT.
972 func (em *emulator) processCursorTab(str string) {
973 if pi, err := numericParams(str, 1); err == nil {
974 // Note: tab does not clear this field.
975 for range max(1, pi[0]) {
976 em.nextTab()
977 }
978 }
979 }
980
981 // processCursorBackTab implements CBT.
982 func (em *emulator) processCursorBackTab(str string) {
983 if pi, err := numericParams(str, 1); err == nil {
984 em.autoWrap = false
985 for range max(1, pi[0]) {
986 em.prevTab()
987 }
988 }
989 }
990
991 // processEraseDisplay implements ED.
992 func (em *emulator) processEraseDisplay(str string) {
993 if pi, err := numericParams(str, 1); err == nil {
994 em.bufferingStart()
995 defer em.bufferingEnd()
996
997 switch pi[0] {
998 case 0: // erase below
999 em.eraseBelow()
1000 case 1: // erase above
1001 em.eraseAbove()
1002 case 2: // erase all
1003 em.eraseAll()
1004 // others not supported (3 is erase saved lines)
1005 }
1006 }
1007 }
1008
1009 // processEraseLine implements EL.
1010 func (em *emulator) processEraseLine(str string) {
1011 if pi, err := numericParams(str, 1); err == nil {
1012 em.bufferingStart()
1013 defer em.bufferingEnd()
1014
1015 switch pi[0] {
1016 case 0:
1017 em.eraseToLineEnd()
1018 case 1:
1019 em.eraseToLineStart()
1020 case 2:
1021 em.eraseLine()
1022 }
1023 }
1024 }
1025
1026 // processEraseCharacter implements ECH.
1027 // This ignores the margin.
1028 func (em *emulator) processEraseCharacter(str string) {
1029 if pi, err := numericParams(str, 1); err == nil {
1030 em.autoWrap = false
1031 pos := em.pos
1032 // TODO: delete wide character if we are splitting it at the start
1033 em.bufferingStart()
1034 defer em.bufferingEnd()
1035 for range max(1, pi[0]) {
1036
1037 em.eraseCell(pos)
1038 pos.X++
1039 if pos.X >= em.size.X {
1040 break
1041 }
1042 }
1043 }
1044 }
1045
1046 // processScrollUp implements SU (VT420.)
1047 func (em *emulator) processScrollUp(str string) {
1048 if pi, err := numericParams(str, 1); err == nil {
1049 em.bufferingStart()
1050 defer em.bufferingEnd()
1051 for range max(pi[0], 1) {
1052 // TODO: consider faster jump scroll.
1053 // This should be something tunable as well.
1054 em.scrollUp()
1055 }
1056 }
1057 }
1058
1059 // processScrollDown implements SD (VT420.)
1060 func (em *emulator) processScrollDown(str string) {
1061 if pi, err := numericParams(str, 1); err == nil {
1062 em.bufferingStart()
1063 defer em.bufferingEnd()
1064 for range max(pi[0], 1) {
1065 // TODO: consider faster jump scroll.
1066 // This should be something tunable as well.
1067 em.scrollDown()
1068 }
1069 }
1070 }
1071
1072 // processWindowOps handles CSI ... t window operations.
1073 func (em *emulator) processWindowOps(str string) {
1074 if pi, err := numericParams(str, 3); err == nil {
1075 switch pi[0] {
1076 case 8: // Resize window: CSI 8 ; rows ; cols t
1077 rows := pi[1]
1078 cols := pi[2]
1079 if rows < 1 || cols < 1 {
1080 return
1081 }
1082 size := Coord{X: Col(cols), Y: Row(rows)}
1083 if ws, ok := em.be.(interface{ SetSize(Coord) }); ok {
1084 ws.SetSize(size)
1085 em.applyResize(size)
1086 }
1087
1088 case 18: // Report text area size: CSI 8 ; rows ; cols t
1089 em.SendRaw(fmt.Appendf(nil, "\x1b[8;%d;%dt", em.size.Y, em.size.X))
1090 }
1091 }
1092 }
1093
1094 // processVerticalMargins implements DECSTBM (set top and bottom margins, VT220.)
1095 func (em *emulator) processVerticalMargins(str string) {
1096 if pi, err := numericParams(str, 2); err == nil {
1097 pi[0] = max(1, pi[0])
1098 if pi[1] == 0 {
1099 pi[1] = int(em.size.Y)
1100 }
1101 pi[0]--
1102 pi[1]--
1103
1104 top := min(Row(pi[0]), em.size.Y-1)
1105 bot := min(Row(pi[1]), em.size.Y-1)
1106
1107 // no change if values are out of range
1108 if bot > top {
1109 em.topMargin = top
1110 em.botMargin = bot
1111 em.setPosition(Coord{X: 0, Y: 0})
1112 }
1113 }
1114 }
1115
1116 // processHorizontalMargins implements DECSLRM (set left and right margins, VT400.)
1117 // It only works if Private Mode 69 (Left and Right margins)
1118 func (em *emulator) processHorizontalMargins(str string) {
1119 if em.getPrivateMode(PmLeftRightMargin) != ModeOn {
1120 // For compat with SCO and ANSI.SYS.
1121 if str == "" {
1122 em.saveCursor()
1123 }
1124 return
1125 }
1126 if pi, err := numericParams(str, 2); err == nil {
1127 pi[0] = max(1, pi[0])
1128 if pi[1] == 0 {
1129 pi[1] = int(em.size.X)
1130 }
1131 pi[0]--
1132 pi[1]--
1133
1134 lm := min(Col(pi[0]), em.size.X-1)
1135 rm := min(Col(pi[1]), em.size.X-1)
1136
1137 // no change if values are out of range
1138 if rm > lm {
1139 em.rtMargin = rm
1140 em.ltMargin = lm
1141 em.setPosition(Coord{X: 0, Y: 0})
1142 }
1143 }
1144 }
1145
1146 // processIndex moves down, unless already on the bottom margin, in which case it scrolls Up.
1147 func (em *emulator) processIndex() {
1148 pos := em.getPosition()
1149 em.autoWrap = false
1150 if pos.Y == em.botMargin && em.ltMargin <= pos.X && pos.X <= em.rtMargin {
1151 em.scrollUp()
1152 } else {
1153 em.processCursorDown("")
1154 }
1155 }
1156
1157 // processCarriageReturn handle CR.
1158 func (em *emulator) processCarriageReturn() {
1159 em.lastIndex = 0
1160 em.setPosition(Coord{0, em.getPosition().Y})
1161 }
1162
1163 // processLineFeed is like IND, but if ANSI mode 20 is set, then a CR is appended as well.
1164 func (em *emulator) processLineFeed() {
1165 em.lastIndex = 0
1166 em.processIndex()
1167 if em.getAnsiMode(AmNewLineMode) == ModeOn {
1168 em.processCarriageReturn()
1169 }
1170 }
1171
1172 // processReverseIndex moves up, unless already on the top margin, in which case it scrolls down.
1173 func (em *emulator) processReverseIndex() {
1174 pos := em.getPosition()
1175 if pos.Y == em.topMargin {
1176 em.scrollDown()
1177 } else {
1178 em.processCursorUp("")
1179 }
1180 }
1181
1182 // processCursorRow implements VPA (set vertical position absolute)
1183 func (em *emulator) processCursorRow(str string) {
1184 if pi, err := numericParams(str, 1); err == nil {
1185 em.autoWrap = false
1186 pos := em.getPosition()
1187 pos.Y = min(Row(max(1, pi[0])), em.size.Y) - 1
1188 em.setPosition(pos)
1189 }
1190 }
1191
1192 // processCursorRowAdvance implements VPR (vertical position relative).
1193 func (em *emulator) processCursorRowAdvance(str string) {
1194 if pi, err := numericParams(str, 1); err == nil {
1195 em.autoWrap = false
1196 pos := em.getPosition()
1197 pos.Y = min(pos.Y+Row(max(1, pi[0])), em.size.Y-1)
1198 em.setPosition(pos)
1199 }
1200 }
1201
1202 // processInsertLine implements IL.
1203 func (em *emulator) processInsertLine(str string) {
1204 // insert line only takes effect within the scrolling region
1205 if em.pos.X < em.ltMargin || em.pos.X > em.rtMargin ||
1206 em.pos.Y < em.topMargin || em.pos.Y > em.botMargin {
1207 return
1208 }
1209
1210 if pi, err := numericParams(str, 1); err == nil {
1211 em.autoWrap = false
1212 num := Row(max(1, pi[0]))
1213 num = min(num, em.botMargin-em.pos.Y+1)
1214
1215 // process as a scroll down at our position.
1216 top := em.topMargin
1217 em.topMargin = em.pos.Y
1218 for range num {
1219 em.scrollDown()
1220 }
1221 em.topMargin = top
1222 em.pos.X = 0
1223 em.setPosition(em.pos)
1224 }
1225 }
1226
1227 // processDeleteLine implements DL.
1228 func (em *emulator) processDeleteLine(str string) {
1229 // delete line only takes effect within the scrolling region
1230 if em.pos.X < em.ltMargin || em.pos.X > em.rtMargin ||
1231 em.pos.Y < em.topMargin || em.pos.Y > em.botMargin {
1232 return
1233 }
1234 if pi, err := numericParams(str, 1); err == nil {
1235 em.autoWrap = false
1236 num := Row(max(1, pi[0]))
1237 num = min(num, em.botMargin-em.pos.Y+1)
1238 if num < 1 {
1239 return
1240 }
1241 // process as a scroll up at our position.
1242 top := em.topMargin
1243 em.topMargin = em.pos.Y
1244 for range num {
1245 em.scrollUp()
1246 }
1247 em.topMargin = top
1248 em.pos.X = 0
1249 em.setPosition(em.pos)
1250 }
1251 }
1252
1253 // processDeleteCharacter implements DCH.
1254 func (em *emulator) processDeleteCharacter(str string) {
1255 // only takes effect within the scrolling region
1256 if em.pos.X < em.ltMargin || em.pos.X > em.rtMargin ||
1257 em.pos.Y < em.topMargin || em.pos.Y > em.botMargin {
1258 return
1259 }
1260 em.bufferingStart()
1261 defer em.bufferingEnd()
1262
1263 if pi, err := numericParams(str, 1); err == nil {
1264 em.autoWrap = false
1265 num := Col(max(1, pi[0]))
1266 num = min(num, em.rtMargin-em.pos.X+1)
1267 if num < 1 {
1268 return
1269 }
1270 // this is essentially a one line scroll left
1271 pos := em.pos
1272
1273 // if we are breaking a wide rune, delete it (but preserve style)
1274 if em.pos.X > 0 {
1275 if ix := em.index(em.pos); em.cells[ix-1].W > 1 {
1276 em.cells[ix-1].C = ""
1277 em.cells[ix-1].W = 0
1278 em.be.Put(Coord{X: em.pos.X - 1, Y: em.pos.Y}, em.cells[ix-1])
1279 }
1280 }
1281
1282 for range num {
1283 src := Coord{X: em.pos.X + 1, Y: em.pos.Y}
1284 dst := Coord{X: em.pos.X, Y: em.pos.Y}
1285 dim := Coord{X: em.rtMargin - em.pos.X, Y: 1}
1286 em.blit(src, dst, dim)
1287 em.eraseCell(Coord{X: em.rtMargin, Y: em.pos.Y})
1288 }
1289 em.pos = pos
1290 em.setPosition(em.pos)
1291 }
1292 }
1293
1294 // processInsertCharacter implements ICH.
1295 func (em *emulator) processInsertCharacter(str string) {
1296 em.autoWrap = false
1297 // only takes effect within the scrolling region -- HOWEVER,
1298 // ICH still resets auto-wrap in this case, unlike DCH.
1299 if em.pos.X < em.ltMargin || em.pos.X > em.rtMargin ||
1300 em.pos.Y < em.topMargin || em.pos.Y > em.botMargin {
1301 return
1302 }
1303 em.bufferingStart()
1304 defer em.bufferingEnd()
1305 if pi, err := numericParams(str, 1); err == nil {
1306 num := Col(max(1, pi[0]))
1307 num = min(num, em.rtMargin-em.pos.X+1)
1308 if num < 1 {
1309 return
1310 }
1311
1312 // this is essentially a one line scroll right
1313 pos := em.pos
1314
1315 // if we are breaking a wide rune, delete it
1316 if em.pos.X > 0 {
1317 if ix := em.index(em.pos); em.cells[ix-1].W > 1 {
1318 em.cells[ix-1].C = ""
1319 em.cells[ix-1].W = 0
1320 em.be.Put(Coord{X: em.pos.X - 1, Y: em.pos.Y}, em.cells[ix-1])
1321 }
1322 }
1323
1324 for range num {
1325 src := Coord{X: em.pos.X, Y: em.pos.Y}
1326 dst := Coord{X: em.pos.X + 1, Y: em.pos.Y}
1327 dim := Coord{X: em.rtMargin - em.pos.X, Y: 1}
1328 em.blit(src, dst, dim)
1329 ix := em.index(Coord{X: em.pos.X, Y: em.pos.Y})
1330 em.cells[ix].C = ""
1331 em.cells[ix].W = 0
1332 em.cells[ix].S = em.style
1333 // NB: We don't use eraseCell, because we need to preserve attributes.
1334 em.be.Put(Coord{X: em.pos.X, Y: em.pos.Y}, em.cells[ix])
1335 }
1336
1337 // if we clipped off the end of a wide character, then delete it.
1338 if ix := em.index(Coord{X: em.rtMargin, Y: em.pos.Y}); em.cells[ix].W > 1 {
1339 em.cells[ix].C = ""
1340 em.cells[ix].W = 0
1341 em.be.Put(Coord{X: em.rtMargin, Y: em.pos.Y}, em.cells[ix])
1342 }
1343
1344 em.pos = pos
1345 em.setPosition(em.pos)
1346 }
1347 }
1348
1349 // processSetMode implements SM (set ANSI mode).
1350 func (em *emulator) processSetMode(str string) {
1351 if pi, err := numericParams(str, 1); err == nil {
1352 for _, pm := range pi {
1353 em.setAnsiMode(AnsiMode(pm), ModeOn)
1354 }
1355 }
1356 }
1357
1358 // processResetMode implements RM (reset ANSI mode).
1359 func (em *emulator) processResetMode(str string) {
1360 if pi, err := numericParams(str, 1); err == nil {
1361 for _, pm := range pi {
1362 em.setAnsiMode(AnsiMode(pm), ModeOff)
1363 }
1364 }
1365 }
1366
1367 // processRequestMode implements DECRQM for ANSI modes.
1368 // Only a single numeric parameter (mode number) can be supplied (VT300+)
1369 func (em *emulator) processRequestMode(str string) {
1370 if m, err := strconv.Atoi(str); err == nil {
1371 am := AnsiMode(m)
1372 status := em.getAnsiMode(am)
1373 em.SendRaw([]byte(am.Reply(status)))
1374 }
1375 }
1376
1377 // processSetPrivateMode implements DECSET (set private mode).
1378 func (em *emulator) processSetPrivateMode(str string) {
1379 if pi, err := numericParams(str, 1); err == nil {
1380 for _, pm := range pi {
1381 em.setPrivateMode(PrivateMode(pm), ModeOn)
1382 }
1383 }
1384 }
1385
1386 // processResetPrivateMode implements DECRST (reset private mode).
1387 func (em *emulator) processResetPrivateMode(str string) {
1388 if pi, err := numericParams(str, 1); err == nil {
1389 for _, pm := range pi {
1390 em.setPrivateMode(PrivateMode(pm), ModeOff)
1391 }
1392 }
1393 }
1394
1395 // processRequestPrivateMode implements DECRQM for private modes.
1396 // Only a single numeric parameter (mode number) can be supplied (VT300+)
1397 func (em *emulator) processRequestPrivateMode(str string) {
1398 if m, err := strconv.Atoi(str); err == nil {
1399 pm := PrivateMode(m)
1400 status := em.getPrivateMode(pm)
1401 em.SendRaw([]byte(pm.Reply(status)))
1402 }
1403 }
1404
1405 // processTabReset implements DECST8C (set tab stops to every 8 chars)
1406 func (em *emulator) processTabReset(str string) {
1407 if pi, err := numericParams(str, 1); err == nil && pi[0] == 5 {
1408 em.tabStops = nil
1409 }
1410 }
1411
1412 // processTabClear implements TBC (clear horizontal tab).
1413 func (em *emulator) processTabClear(str string) {
1414 if pi, err := numericParams(str, 1); err == nil {
1415 switch pi[0] {
1416 case 0: // clear stop at current column
1417 em.clrTabStop(em.getPosition().X)
1418 case 3: // clear all columns
1419 em.tabStops = []Col{} // this is distinct from nil
1420 }
1421 }
1422 }
1423
1424 // processPrimaryAttributes implements send DA.
1425 func (em *emulator) processPrimaryAttributes(str string) {
1426 if pi, err := numericParams(str, 1); err == nil && pi[0] == 0 {
1427 em.sendDA()
1428 }
1429 }
1430
1431 // processExtendedAttributes implements XTVERSION (send terminal name and version).
1432 func (em *emulator) processExtendedAttributes(str string) {
1433 if pi, err := numericParams(str, 1); err == nil && pi[0] == 0 && em.name != "" {
1434 em.SendRaw(fmt.Appendf(nil, "\x1bP>|%s %s\x1b\\", em.name, em.vers))
1435 }
1436 }
1437
1438 // processCursorStyle implements DECSCUSR (set cursor style).
1439 func (em *emulator) processCursorStyle(str string) {
1440 // get previous visibility state, as we don't change it with this call.
1441 visible := em.cursor.IsVisible()
1442 if pi, err := numericParams(str, 1); err == nil {
1443 switch pi[0] {
1444 case 0, 1:
1445 em.cursor = BlinkingBlock
1446 case 2:
1447 em.cursor = SteadyBlock
1448 case 3:
1449 em.cursor = BlinkingUnderline
1450 case 4:
1451 em.cursor = SteadyUnderline
1452 case 5:
1453 em.cursor = BlinkingBar
1454 case 6:
1455 em.cursor = SteadyBar
1456 }
1457 if !visible {
1458 em.cursor = em.cursor.Hide()
1459 }
1460 em.be.SetCursor(em.cursor)
1461 }
1462 }
1463
1464 // processCsi processes CSI sequences.
1465 func (em *emulator) processCsi(final byte) {
1466
1467 // CSI sequences are supported in several different possible ways:
1468 // parameters may have a prefix character that is not numeric, typically
1469 // indicating a whole different mode of operation than the final byte.
1470 // There may also be intermediate bytes, but we only look for one, because
1471 // the use cases we have this are that only a single intermediate byte is
1472 // sometimes used to affect function. (E.g. $ in some cases.)
1473 cmd := ""
1474 if em.inBuf.Len() > 0 {
1475 if b := em.inBuf.Bytes()[0]; b > '9' && b <= '?' {
1476 cmd += string(b)
1477 em.inBuf.ReadByte()
1478 }
1479 }
1480 if l := em.inBuf.Len(); l > 0 {
1481 if b := em.inBuf.Bytes()[l-1]; b >= 0x20 && b <= 0x2F {
1482 cmd += string(b)
1483 em.inBuf.Truncate(l - 1)
1484 }
1485 }
1486 cmd += string(final)
1487
1488 str := em.inBuf.String()
1489 switch cmd {
1490
1491 case "@":
1492 em.processInsertCharacter(str)
1493 case "A":
1494 em.processCursorUp(str)
1495 case "B":
1496 em.processCursorDown(str)
1497 case "C":
1498 em.processCursorForward(str)
1499 case "D":
1500 em.processCursorBackward(str)
1501 case "E":
1502 em.processCursorNextLine(str)
1503 case "F":
1504 em.processCursorPreviousLine(str)
1505 case "G":
1506 em.processCursorColumn(str)
1507 case "H", "f":
1508 em.processCursorPosition(str)
1509 case "I":
1510 em.processCursorTab(str)
1511 case "J":
1512 em.processEraseDisplay(str)
1513 case "K":
1514 em.processEraseLine(str)
1515 case "L":
1516 em.processInsertLine(str)
1517 case "M":
1518 em.processDeleteLine(str)
1519 case "P":
1520 em.processDeleteCharacter(str)
1521 case "S":
1522 em.processScrollUp(str)
1523 case "T":
1524 em.processScrollDown(str)
1525 case "X":
1526 em.processEraseCharacter(str)
1527 case "Z":
1528 em.processCursorBackTab(str)
1529 case "c":
1530 em.processPrimaryAttributes(str)
1531 case "d":
1532 em.processCursorRow(str)
1533 case "e":
1534 em.processCursorRowAdvance(str)
1535 case "g":
1536 em.processTabClear(str)
1537 case "h":
1538 em.processSetMode(str)
1539 case "l":
1540 em.processResetMode(str)
1541 case "m":
1542 em.processSgr(str)
1543 case "n":
1544 em.deviceReport(str)
1545 case "r":
1546 em.processVerticalMargins(str)
1547 case "s":
1548 em.processHorizontalMargins(str)
1549 case "t":
1550 em.processWindowOps(str)
1551 case " q":
1552 em.processCursorStyle(str)
1553 case "?W":
1554 em.processTabReset(str)
1555 case "?h":
1556 em.processSetPrivateMode(str)
1557 case "?l":
1558 em.processResetPrivateMode(str)
1559 case "$p":
1560 em.processRequestMode(str)
1561 case "?$p":
1562 em.processRequestPrivateMode(str)
1563 case ">q":
1564 em.processExtendedAttributes(str)
1565 }
1566 }
1567
1568 // processClipboard handles OSC 52 commands.
1569 func (em *emulator) processClipboard(str string) {
1570 clipper, ok := em.be.(Clipboard)
1571 if !ok {
1572 return
1573 }
1574
1575 // first parameter is the target. We only have a single
1576 // target, and alias all possibilities to the same.
1577 parts := strings.SplitN(str, ";", 2)
1578 if len(parts) != 2 {
1579 return
1580 }
1581
1582 if parts[1] == "?" {
1583 // request for clipboard content
1584 data := clipper.GetClipboard()
1585 if data != nil {
1586 em.SendRaw(fmt.Appendf(nil, "\x1b]52;c;%s\x1b\\", base64.StdEncoding.EncodeToString(data)))
1587 }
1588 return
1589 }
1590
1591 buf := make([]byte, base64.StdEncoding.DecodedLen(len(parts[1])))
1592 if n, err := base64.StdEncoding.Decode(buf, []byte(parts[1])); err == nil {
1593 clipper.SetClipboard(buf[:n])
1594 return
1595 }
1596
1597 clipper.SetClipboard([]byte{})
1598 }
1599
1600 // processHyperLink handles OSC 8 commands.
1601 func (em *emulator) processHyperLink(str string) {
1602 // format is params;URI params are colon separated key value pairs.
1603 // if the URI is absent, then the link is terminated.
1604 parts := strings.SplitN(str, ";", 2)
1605 if len(parts) == 2 {
1606 if parts[1] == "" {
1607 // No URI
1608 em.style = em.style.WithUrl("", "")
1609 return
1610 }
1611 url := parts[1]
1612 id := ""
1613 for pair := range strings.SplitSeq(parts[0], ":") {
1614 if val, ok := strings.CutPrefix(pair, "id="); ok {
1615 id = val
1616 }
1617 }
1618 em.style = em.style.WithUrl(url, id)
1619 }
1620 }
1621
1622 // processOSC processes an operating system command.
1623 func (em *emulator) processOSC() {
1624
1625 // Every OSC we support has a number, semicolon, then string.
1626 ns, str, ok := strings.Cut(em.inBuf.String(), ";")
1627 if !ok {
1628 return
1629 }
1630 if num, err := strconv.Atoi(ns); err != nil {
1631 return
1632 } else {
1633 switch num {
1634 case 2: // Set window title
1635 if t, ok := em.be.(Titler); ok {
1636 // TODO: possibly validate the UTF-8 content?
1637 em.bufferingStart()
1638 defer em.bufferingEnd()
1639 t.SetWindowTitle(str)
1640 }
1641 case 8:
1642 em.processHyperLink(str)
1643 case 52:
1644 em.processClipboard(str)
1645 }
1646 }
1647 }
1648
1649 func (em *emulator) getPosition() Coord {
1650 pos := em.be.GetPosition()
1651 em.pos = pos
1652 return em.pos
1653 }
1654
1655 func (em *emulator) setPosition(pos Coord) {
1656 em.pos = pos
1657 em.be.SetPosition(pos)
1658 }
1659
1660 func (em *emulator) deviceReport(s string) {
1661 switch s {
1662 case "5":
1663 em.SendRaw([]byte("\x1b[0n"))
1664 case "6":
1665 pos := em.getPosition()
1666 em.SendRaw(fmt.Appendf(nil, "\x1b[%d;%dR", pos.Y+1, pos.X+1))
1667 default: // ignore
1668 }
1669 }
1670
1671 func (em *emulator) moveUpN(count Row) {
1672 for range count {
1673 em.moveUp()
1674 }
1675 }
1676
1677 func (em *emulator) moveDownN(count Row) {
1678 for range count {
1679 em.moveDown()
1680 }
1681 }
1682
1683 func (em *emulator) moveLeftN(count Col) {
1684 for range count {
1685 em.moveLeft()
1686 }
1687 }
1688
1689 func (em *emulator) moveRightN(count Col) {
1690 for range count {
1691 em.moveRight()
1692 }
1693 }
1694
1695 // moveDown moves down, to the limit of either bottom margin, or the bottom of the screen if outside the margin.
1696 func (em *emulator) moveDown() {
1697 pos := em.getPosition()
1698 win := em.size
1699 if pos.Y == em.botMargin || pos.Y == win.Y-1 {
1700 return
1701 }
1702 pos.Y++
1703 em.setPosition(pos)
1704 }
1705
1706 // moveUp moves up, to the limit of either top margin, or zero if outside the margin.
1707 func (em *emulator) moveUp() {
1708 pos := em.getPosition()
1709 if pos.Y == 0 || pos.Y == em.topMargin {
1710 return
1711 }
1712 pos.Y--
1713 em.setPosition(pos)
1714 }
1715
1716 func (em *emulator) moveLeft() {
1717 em.autoWrap = false
1718 em.lastIndex = 0
1719 pos := em.getPosition()
1720 if pos.X > 0 {
1721 pos.X--
1722 em.setPosition(pos)
1723 }
1724 }
1725
1726 func (em *emulator) moveRight() {
1727 pos := em.getPosition()
1728 win := em.size
1729 if pos.X < win.X-1 {
1730 pos.X++
1731 em.setPosition(pos)
1732 }
1733 }
1734
1735 // nextLine is like CNL with 1, but it optionally also scrolls.
1736 func (em *emulator) nextLine() {
1737 em.autoWrap = false
1738 if em.pos.Y == em.botMargin {
1739 em.scrollUp()
1740 }
1741 em.moveDown()
1742 em.pos.X = 0
1743 em.setPosition(em.pos)
1744 }
1745
1746 // blit performs a data move operation. It does ignores margins.
1747 func (em *emulator) blit(src, dst, dim Coord) {
1748
1749 em.bufferingStart()
1750 defer em.bufferingEnd()
1751
1752 // save the source and destination for the backend blit
1753 bsrc := src
1754 bdst := dst
1755
1756 lim := em.size
1757
1758 // clip to visible source
1759 if dim.X+src.X > lim.X {
1760 dim.X = lim.X - src.X
1761 }
1762 if dim.Y+src.Y > lim.Y {
1763 dim.Y = lim.Y - src.Y
1764 }
1765 // and clip to final destination
1766 if dim.X+dst.X > lim.X {
1767 dim.X = lim.X - dst.X
1768 }
1769 if dim.Y+dst.Y > lim.Y {
1770 dim.Y = lim.Y - dst.Y
1771 }
1772
1773 // gap represents decrement when shifting to the next row --
1774 // skipping over the irrelevant cells. (The increment in the
1775 // index when going from last cell of row to first cell of next row,
1776 // or vice versa.)
1777 gap := int(lim.X - dim.X)
1778
1779 // the following logic is carefully constructed to avoid expensive
1780 // operations in the loops (only addition or subtraction)
1781 if em.index(src) > em.index(dst) { // source appears later, so we can forward copy
1782 si := em.index(src)
1783 di := em.index(dst)
1784 for range dim.Y {
1785 for range dim.X {
1786 em.cells[di] = em.cells[si]
1787 di++
1788 si++
1789 }
1790 // advance to next row
1791 si += gap
1792 di += gap
1793 }
1794 } else { // source appears earlier, so we have to reverse copy
1795 src.Y += dim.Y - 1
1796 dst.Y += dim.Y - 1
1797 src.X += dim.X - 1
1798 dst.X += dim.X - 1
1799 si := em.index(src)
1800 di := em.index(dst)
1801
1802 for range dim.Y {
1803 for range dim.X {
1804 em.cells[di] = em.cells[si]
1805 si--
1806 di--
1807 }
1808 si -= gap
1809 di -= gap
1810 }
1811 }
1812
1813 // Now we possibly blit underneath. We'll use the underlying
1814 // implementation's blit operation if it has one, else we'll
1815 // just rewrite the cells in linear order.
1816 if b, ok := em.be.(Blitter); ok {
1817 // The backend implements what should be a fast blit.
1818 b.Blit(bsrc, bdst, dim)
1819 } else {
1820 // This does math for each cell, so you're looking at a lot of multiplications
1821 // for a bit display -- 100x100 means 10,000x2 multiplications. This could be
1822 // optimized, but this is really a fallback as every backend really *should* have
1823 // an efficient blit operation. (The ones that don't probably don't keep their own
1824 // state, such as a wrappers on top of TTYs.) In these cases the cost of writing
1825 // the content is probably substantially dominant anyway.
1826 for row := range dim.Y {
1827 for col := range dim.X {
1828 pos := bdst
1829 pos.X += col
1830 pos.Y += row
1831 cell := em.cells[em.index(pos)]
1832 em.be.Put(pos, cell)
1833 }
1834 }
1835 }
1836 }
1837
1838 func (em *emulator) scrollUp() {
1839 dim := Coord{X: em.rtMargin - em.ltMargin + 1, Y: em.botMargin - em.topMargin}
1840 src := Coord{X: em.ltMargin, Y: em.topMargin + 1}
1841 dst := Coord{X: em.ltMargin, Y: em.topMargin}
1842
1843 // TODO: deal with wide characters broken across the margin
1844 pos := em.pos
1845 em.blit(src, dst, dim)
1846 bot := Coord{X: em.ltMargin, Y: em.botMargin}
1847 for bot.X <= em.rtMargin {
1848 em.eraseCell(bot)
1849 bot.X++
1850 }
1851 em.setPosition(pos)
1852 }
1853
1854 func (em *emulator) scrollDown() {
1855 dim := Coord{X: em.rtMargin - em.ltMargin + 1, Y: em.botMargin - em.topMargin}
1856 src := Coord{X: em.ltMargin, Y: em.topMargin}
1857 dst := Coord{X: em.ltMargin, Y: em.topMargin + 1}
1858
1859 pos := em.pos
1860 em.blit(src, dst, dim)
1861 em.setPosition(Coord{X: em.ltMargin, Y: em.topMargin})
1862 top := Coord{X: em.ltMargin, Y: em.topMargin}
1863 for top.X <= em.rtMargin {
1864 em.eraseCell(top)
1865 top.X++
1866 }
1867 em.setPosition(pos)
1868 }
1869
1870 // nextTab advances to the next tab stop, or the end of
1871 // the line if there is no further tab.
1872 func (em *emulator) nextTab() {
1873 em.lastIndex = 0
1874 maxX := em.size.X - 1
1875 curX := em.getPosition().X
1876 if curX == maxX { // already at end
1877 return
1878 }
1879 nextX := maxX
1880 if em.tabStops == nil {
1881 // just advance to the next one
1882 nextX = min((curX+8)&^7, maxX)
1883 } else {
1884 for _, p := range em.tabStops {
1885 if p > curX {
1886 nextX = p
1887 break
1888 }
1889 }
1890 }
1891 em.setPosition(Coord{X: nextX, Y: em.pos.Y})
1892 }
1893
1894 func (em *emulator) prevTab() {
1895 curX := em.getPosition().X
1896 if curX == 0 {
1897 return
1898 }
1899 nextX := curX - 1
1900 if em.tabStops == nil {
1901 nextX &^= 7
1902 } else if i, exist := slices.BinarySearch(em.tabStops, nextX); exist {
1903 nextX = em.tabStops[i]
1904 } else if i > 0 {
1905 nextX = em.tabStops[i-1]
1906 } else {
1907 nextX = 0
1908 }
1909 em.setPosition(Coord{X: nextX, Y: em.pos.Y})
1910 }
1911
1912 // initTabStops initializes the tab stops assuming every 8th column
1913 // is a tab stop. This should only be called if the user is intentionally
1914 // changing the tab stops, because it will no longer support expanding
1915 // tab stops on resizing.
1916 func (em *emulator) initTabStops() {
1917 if em.tabStops == nil {
1918 // no tab stop at offset 0 since that would be pointless
1919 em.tabStops = make([]Col, 0, int(em.size.X/8)+1)
1920 for col := Col(8); col < em.size.X; col += 8 {
1921 em.tabStops = append(em.tabStops, col)
1922 }
1923 }
1924 }
1925
1926 // setTabStop sets a tab stop at the given location.
1927 // This calls initTabStops - please see the description of that function for ramifications.
1928 func (em *emulator) setTabStop(ts Col) {
1929 em.initTabStops()
1930 if index, exist := slices.BinarySearch(em.tabStops, ts); !exist {
1931 em.tabStops = slices.Insert(em.tabStops, index, ts)
1932 }
1933 }
1934
1935 // clrTabStop clears the tab stop at the given column. This calls
1936 // initTabStops - please see the description of that function for ramifications.
1937 func (em *emulator) clrTabStop(ts Col) {
1938 em.initTabStops()
1939 em.tabStops = slices.DeleteFunc(em.tabStops, func(x Col) bool { return x == ts })
1940 }
1941
1942 // index obtains the index in the cells slice for the given coordinates,
1943 // which must be within the bounds of the display size.
1944 func (em *emulator) index(c Coord) int {
1945 return int(c.Y)*int(em.size.X) + int(c.X)
1946 }
1947
1948 // putRune puts out a single rune. This might be a subsequent part of a grapheme cluster, in
1949 // which case it will be emitted together with the preceding base character.
1950 func (em *emulator) putRune(r rune) {
1951 dim := em.size
1952
1953 if lastIdx := em.lastIndex; lastIdx != 0 {
1954 lastIdx--
1955 if pm := em.getPrivateMode(PmGraphemeClusters); pm == ModeOn || pm == ModeOnLocked {
1956 // ASCII-to-ASCII pairs cannot extend a grapheme cluster, except CRLF.
1957 prev := em.cells[lastIdx].C
1958 if len(prev) == 1 && prev[0] < utf8.RuneSelf && !shouldCheckGrapheme(prev[0], r) {
1959 // fall through to the normal single-rune path
1960 } else {
1961 // maybe we need to update the last index
1962 buf := em.graphemeBuf[:0]
1963 need := len(prev) + utf8.UTFMax
1964 if cap(buf) < need {
1965 buf = make([]byte, 0, need)
1966 }
1967 buf = append(buf, prev...)
1968 buf = utf8.AppendRune(buf, r)
1969 em.graphemeIter.SetText(buf)
1970 if em.graphemeIter.Next() && len(em.graphemeIter.Value()) == len(buf) {
1971 // we are adding to a cluster
1972 cluster := em.graphemeIter.Value()
1973 width := em.cells[lastIdx].W
1974 if w := textWidthOptions.Rune(r); w > width {
1975 width = w
1976 }
1977 if isRegionalIndicator(r) && width < 2 {
1978 width = 2
1979 }
1980 if r == '\uFE0F' && width < 2 {
1981 width = 2
1982 }
1983 em.cells[lastIdx].C = em.clusterString(cluster)
1984 em.cells[lastIdx].W = width
1985 col := Col(lastIdx) % dim.X
1986 row := Row(lastIdx / int(dim.X))
1987 // we may have to move position if this switches to wide, so recalculate expected end
1988 next := col + Col(width)
1989 if em.getPrivateMode(PmAutoMargin) == ModeOn && next >= dim.X {
1990 em.autoWrap = true
1991 }
1992 end := next
1993 if end >= dim.X {
1994 end = dim.X - 1
1995 }
1996 if width == 2 && col < dim.X-1 && em.cells[lastIdx+1].W != 0 {
1997 // erase the next cell before putting down a character
1998 em.cells[lastIdx+1].C = ""
1999 em.cells[lastIdx+1].S = em.cells[lastIdx].S
2000 em.cells[lastIdx+1].W = 0
2001 em.be.Put(Coord{X: col + 1, Y: row}, em.cells[lastIdx+1])
2002 }
2003 // we leave the em.lastIndex for now, we might keep extending this cluster
2004 em.be.Put(Coord{X: col, Y: row}, em.cells[lastIdx])
2005 em.setPosition(Coord{X: end, Y: row})
2006 em.graphemeBuf = buf[:0]
2007 return
2008 }
2009 em.graphemeBuf = buf[:0]
2010 }
2011 }
2012 }
2013
2014 if em.autoWrap {
2015 em.nextLine()
2016 }
2017
2018 autoMargin := em.getPrivateMode(PmAutoMargin) == ModeOn
2019
2020 pos := em.getPosition()
2021 w := textWidthOptions.Rune(r)
2022 if autoMargin && pos.X+Col(w) >= dim.X {
2023 em.autoWrap = true
2024 }
2025 index := em.index(pos)
2026 em.cells[index].C = em.runeString(r)
2027 em.cells[index].S = em.style
2028 em.cells[index].W = w
2029 em.be.Put(em.pos, em.cells[index])
2030 em.lastIndex = index + 1
2031
2032 if w == 2 && pos.X < dim.X-1 {
2033 index++
2034 em.cells[index].C = ""
2035 em.cells[index].S = em.style
2036 em.cells[index].W = 0
2037 }
2038 // Advance the cursor. This will stop at the margin.
2039 // Note that if auto margin is enabled, we will have set
2040 // autoWrap above if we were at the margin already.
2041 em.moveRightN(Col(w))
2042 }
2043
2044 func (em *emulator) runeString(r rune) string {
2045 if r < utf8.RuneSelf {
2046 return asciiRuneStrings[r]
2047 }
2048 return em.runeStrings.stringFor(r)
2049 }
2050
2051 func (em *emulator) clusterString(cluster []byte) string {
2052 return em.clusterStrings.stringFor(cluster)
2053 }
2054
2055 func shouldCheckGrapheme(prev byte, r rune) bool {
2056 if r < utf8.RuneSelf {
2057 return prev == '\r' && r == '\n'
2058 }
2059
2060 if unicode.Is(unicode.M, r) {
2061 return true
2062 }
2063 if r == '\u200d' {
2064 return true
2065 }
2066 if r >= 0xFE00 && r <= 0xFE0F {
2067 return true
2068 }
2069 if r >= 0xE0100 && r <= 0xE01EF {
2070 return true
2071 }
2072
2073 return false
2074 }
2075
2076 func isRegionalIndicator(r rune) bool {
2077 return r >= 0x1F1E6 && r <= 0x1F1FF
2078 }
2079
2080 // eraseCell erases a single cell at the given offset.
2081 // It clears attributes, but leaves the colors intact.
2082 func (em *emulator) eraseCell(c Coord) {
2083 s := em.style.WithAttr(Plain)
2084 index := em.index(c)
2085 em.cells[index].C = ""
2086 em.cells[index].S = s
2087 em.cells[index].W = 0
2088 em.be.Put(c, em.cells[index])
2089 }
2090
2091 // eraseBelow erases from (and including) the current cursor position to the end of the window.
2092 func (em *emulator) eraseBelow() {
2093 size := em.size
2094 pos := em.getPosition()
2095 for x := pos.X; x < size.X; x++ {
2096 em.eraseCell(Coord{X: x, Y: pos.Y})
2097 }
2098 for y := pos.Y + 1; y < size.Y; y++ {
2099 for x := Col(0); x < size.X; x++ {
2100 em.eraseCell(Coord{X: x, Y: y})
2101 }
2102 }
2103 em.setPosition(pos)
2104 }
2105
2106 // eraseAbove erases from the origin to (and including) the current cursor position.
2107 func (em *emulator) eraseAbove() {
2108 size := em.size
2109 pos := em.getPosition()
2110 for y := Row(0); y < pos.Y; y++ {
2111 for x := Col(0); x < size.X; x++ {
2112 em.eraseCell(Coord{X: x, Y: y})
2113 }
2114 }
2115 for x := Col(0); x <= pos.X; x++ {
2116 em.eraseCell(Coord{X: x, Y: pos.Y})
2117 }
2118 em.setPosition(pos)
2119 }
2120
2121 // eraseAll erases the entire screen. It uses the color, but resets all other attributes.
2122 func (em *emulator) eraseAll() {
2123 size := em.size
2124 pos := em.getPosition()
2125 for y := Row(0); y < size.Y; y++ {
2126 for x := Col(0); x < size.X; x++ {
2127 em.eraseCell(Coord{X: x, Y: y})
2128 }
2129 }
2130 em.setPosition(pos)
2131 }
2132
2133 // eraseToLineEnd erases to the end of the line, including the cursor position.
2134 func (em *emulator) eraseToLineEnd() {
2135 size := em.size
2136 pos := em.getPosition()
2137 for x := pos.X; x < size.X; x++ {
2138 em.eraseCell(Coord{x, pos.Y})
2139 }
2140 em.setPosition(pos)
2141 }
2142
2143 // eraseToLineStart erases to the start of the line, including the cursor position.
2144 func (em *emulator) eraseToLineStart() {
2145 pos := em.getPosition()
2146 for x := Col(0); x <= pos.X; x++ {
2147 em.eraseCell(Coord{x, pos.Y})
2148 }
2149 em.setPosition(pos)
2150 }
2151
2152 // eraseLine erases the entire line.
2153 func (em *emulator) eraseLine() {
2154 size := em.size
2155 pos := em.getPosition()
2156 for x := range size.X {
2157 em.eraseCell(Coord{x, pos.Y})
2158 }
2159 em.setPosition(pos)
2160 }
2161
2162 // softReset performs a soft reset.
2163 func (em *emulator) softReset() {
2164 // TODO:
2165 // Select default character sets
2166 em.tabStops = nil
2167 em.autoWrap = false
2168 em.style = em.defaultStyle
2169 em.saved = savedCursor{style: em.defaultStyle}
2170 em.topMargin = 0
2171 em.botMargin = em.size.Y - 1
2172 em.ltMargin = 0
2173 em.rtMargin = em.size.X - 1
2174 em.appKeyPad = false
2175 em.be.Reset()
2176 // start by resetting all modes
2177 for _, am := range em.ansiModeKeys() {
2178 em.setAnsiMode(am, ModeOff) // NB: No effect for non-changeable modes
2179 }
2180 for _, pm := range em.privateModeKeys() {
2181 em.setPrivateMode(pm, ModeOff) // NB: No effect for non-changeable modes
2182 }
2183 // and set any that should reset on (auto-margin)
2184 em.setPrivateMode(PmAutoMargin, ModeOn)
2185 em.setPrivateMode(PmAutoRepeat, ModeOn)
2186 em.setPrivateMode(PmShowCursor, ModeOn)
2187 em.setPrivateMode(PmBlinkCursor, ModeOn)
2188 // set default cursor - matches VT defaults
2189 em.cursor = BlinkingBlock
2190 em.be.SetCursor(em.cursor)
2191 em.setPosition(Coord{0, 0})
2192 em.eraseAll()
2193 }
2194
2195 func (em *emulator) ansiModeKeys() []AnsiMode {
2196 em.modeLock.RLock()
2197 defer em.modeLock.RUnlock()
2198
2199 keys := make([]AnsiMode, 0, len(em.ansiModes))
2200 for am := range em.ansiModes {
2201 keys = append(keys, am)
2202 }
2203 return keys
2204 }
2205
2206 func (em *emulator) privateModeKeys() []PrivateMode {
2207 em.modeLock.RLock()
2208 defer em.modeLock.RUnlock()
2209
2210 keys := make([]PrivateMode, 0, len(em.localModes))
2211 for pm := range em.localModes {
2212 keys = append(keys, pm)
2213 }
2214 return keys
2215 }
2216
2217 // sendDA ends the primary device attributes.
2218 func (em *emulator) sendDA() {
2219 buf := &bytes.Buffer{}
2220 _, _ = fmt.Fprintf(buf, "\x1b[?63")
2221 if em.be.Colors() > 0 {
2222 _, _ = fmt.Fprintf(buf, ";22")
2223 }
2224 if _, ok := em.be.(Clipboard); ok {
2225 _, _ = fmt.Fprintf(buf, ";52")
2226 }
2227 // 9 for NRC?
2228 // 15 for graphics?
2229 buf.WriteRune('c')
2230 em.SendRaw(buf.Bytes())
2231 }
2232
2233 // setAnsiMode sets the ANSI mode.
2234 func (em *emulator) setAnsiMode(mode AnsiMode, ms ModeStatus) {
2235 if !ms.Changeable() {
2236 return
2237 }
2238 em.modeLock.Lock()
2239 defer em.modeLock.Unlock()
2240 if old, ok := em.ansiModes[mode]; ok && old.Changeable() {
2241 em.ansiModes[mode] = ms
2242 }
2243 }
2244
2245 func (em *emulator) getAnsiMode(mode AnsiMode) ModeStatus {
2246 em.modeLock.RLock()
2247 defer em.modeLock.RUnlock()
2248 return em.ansiModes[mode]
2249 }
2250
2251 // getPrivateMode returns the value of a DEC private mode.
2252 func (em *emulator) getPrivateMode(pm PrivateMode) ModeStatus {
2253 em.modeLock.RLock()
2254 if ms, ok := em.localModes[pm]; ok {
2255 em.modeLock.RUnlock()
2256 return ms
2257 }
2258 em.modeLock.RUnlock()
2259 return em.be.GetPrivateMode(pm)
2260 }
2261
2262 func (em *emulator) updateMouseReporting() {
2263 mi, ok := em.be.(Mouser)
2264 if !ok {
2265 return
2266 }
2267 em.modeLock.RLock()
2268 report := em.mouseReportingLocked()
2269 em.modeLock.RUnlock()
2270 mi.SetMouse(report)
2271 }
2272
2273 // setPrivateMode sets the DEC private mode.
2274 func (em *emulator) setPrivateMode(pm PrivateMode, ms ModeStatus) {
2275 if !ms.Changeable() {
2276 return
2277 }
2278 em.modeLock.Lock()
2279 old, ok := em.localModes[pm]
2280 if ok && old.Changeable() {
2281 em.localModes[pm] = ms
2282
2283 var (
2284 setMouse bool
2285 report MouseReporting
2286 setCursor bool
2287 cursor CursorStyle
2288 )
2289
2290 switch pm {
2291 case PmMouseButton, PmMouseDrag, PmMouseMotion, PmMouseSgr, PmMouseSgrPixel, PmMouseX10:
2292 report = em.mouseReportingLocked()
2293 setMouse = true
2294 case PmShowCursor:
2295 if ms == ModeOn {
2296 em.cursor = em.cursor.Show()
2297 } else {
2298 em.cursor = em.cursor.Hide()
2299 }
2300 cursor = em.cursor
2301 setCursor = true
2302 case PmBlinkCursor:
2303 if ms == ModeOn {
2304 em.cursor = em.cursor.Blink()
2305 } else {
2306 em.cursor = em.cursor.Steady()
2307
2308 }
2309 cursor = em.cursor
2310 setCursor = true
2311 }
2312 em.modeLock.Unlock()
2313
2314 if setMouse {
2315 if mi, ok := em.be.(Mouser); ok {
2316 mi.SetMouse(report)
2317 }
2318 }
2319 if setCursor {
2320 em.be.SetCursor(cursor)
2321 }
2322 return
2323 }
2324 em.modeLock.Unlock()
2325
2326 if em.be.GetPrivateMode(pm).Changeable() {
2327 _ = em.be.SetPrivateMode(pm, ms)
2328 }
2329 }
2330
2331 func (em *emulator) mouseReportingLocked() MouseReporting {
2332 switch {
2333 case em.localModes[PmMouseButton] == ModeOn:
2334 em.mouseReports = MouseButtons
2335 if em.localModes[PmMouseMotion] == ModeOn {
2336 em.mouseReports = MouseMotion
2337 } else if em.localModes[PmMouseDrag] == ModeOn {
2338 em.mouseReports = MouseDrag
2339 }
2340 case em.localModes[PmMouseX10] == ModeOn:
2341 em.mouseReports = MouseButtons
2342 default:
2343 em.mouseReports = MouseDisabled
2344 }
2345 return em.mouseReports
2346 }
2347
2348 // SendRaw allows raw data to be sent to the application.
2349 // This is done in a thread-safe way, so that content is not intermingled.
2350 func (em *emulator) SendRaw(b []byte) {
2351 em.sendLock.Lock()
2352 defer em.sendLock.Unlock()
2353
2354 // Do not attempt to send *anything* if we are stopped.
2355 select {
2356 case <-em.stopQ:
2357 return
2358 default:
2359 }
2360
2361 // Try to write to the readQ, but if we cannot, then wait until
2362 // either we can, or the stopQ is fired. This ensures that we avoid
2363 // breaking up content if at all possible.
2364 for _, ch := range b {
2365 select {
2366 case em.readQ <- ch:
2367 default:
2368 select {
2369 case em.readQ <- ch:
2370 case <-em.stopQ:
2371 return
2372 }
2373 }
2374 }
2375 }
2376
2377 // KeyEvent injects a keyboard event into the emulator
2378 func (em *emulator) KeyEvent(ev KeyEvent) {
2379
2380 if em.getPrivateMode(PmWin32Input) == ModeOn {
2381 em.keyWin32IM(ev)
2382 } else {
2383 // eliminate "control" keys (which keyboard maps provide) from consideration.
2384 // (We handle control keys explicitly.)
2385 if ev.Utf != "" && ev.Utf[0] < ' ' {
2386 ev.Utf = ""
2387 }
2388 // TODO: more add support for kitty, and maybe modify other keys
2389 em.keyLegacy(ev)
2390 }
2391 }
2392
2393 // ResizeEvent is called by the backend when a resize occurs. A real backend with a child
2394 // process (essentially a "real emulator") should probably also fire SIGWINCH if appropriate.
2395 // That would be the job of something other than this code.
2396 func (em *emulator) ResizeEvent(size Coord) {
2397 select {
2398 case em.writeQ <- size:
2399 case <-em.stopQ:
2400 }
2401 }
2402
2403 func (em *emulator) applyResize(size Coord) {
2404 // resize clobbers our content, until it is redrawn
2405 em.size = size
2406 em.tabStops = slices.DeleteFunc(em.tabStops, func(x Col) bool { return x >= em.size.X })
2407 // resizing resets the margins
2408 em.topMargin = 0
2409 em.botMargin = em.size.Y - 1
2410 em.ltMargin = 0
2411 em.rtMargin = em.size.X - 1
2412 em.cells = make([]Cell, int(em.size.X)*int(em.size.Y))
2413 for i := range em.cells {
2414 em.cells[i].S = em.defaultStyle
2415 }
2416
2417 em.pos = em.getPosition()
2418 if em.getPrivateMode(PmResizeReports) == ModeOn { // NB: we never support "ModeOnLocked"
2419 // NB: for now we do not support pixel sizes
2420 em.SendRaw(fmt.Appendf(nil, "\x1b[48;%d;%d;0;0t", em.size.Y, em.size.X))
2421 }
2422
2423 // Send a SIGWINCH or similar.
2424 em.be.RaiseResize()
2425 }
2426
2427 var legacyKeys = map[Key]struct {
2428 K string // unmodified key
2429 A string // unmodified in application cursor mode (smkx)
2430 S string // with shift (if empty use regular modifier)
2431 C string // with control (if empty use regular modifier)
2432 CS string // with ctrl-shift
2433 }{
2434 KeyF1: {K: "\x1bOP"}, // SS3 P
2435 KeyF2: {K: "\x1bOQ"}, // SS3 Q
2436 KeyF3: {K: "\x1bOR"}, // SS3 R
2437 KeyF4: {K: "\x1bOS"}, // SS3 S
2438 KeyF5: {K: "\x1b[15~"},
2439 KeyF6: {K: "\x1b[17~"},
2440 KeyF7: {K: "\x1b[18~"},
2441 KeyF8: {K: "\x1b[19~"},
2442 KeyF9: {K: "\x1b[20~"},
2443 KeyF10: {K: "\x1b[21~"},
2444 KeyF11: {K: "\x1b[23~"},
2445 KeyF12: {K: "\x1b[24~"},
2446 KeyF13: {K: "\x1b[25~"},
2447 KeyF14: {K: "\x1b[26~"},
2448 KeyF15: {K: "\x1b[28~"},
2449 KeyF16: {K: "\x1b[29~"},
2450 KeyF17: {K: "\x1b[31~"},
2451 KeyF18: {K: "\x1b[32~"},
2452 KeyF19: {K: "\x1b[33~"},
2453 KeyF20: {K: "\x1b[34~"},
2454 KeyUp: {K: "\x1b[A", A: "\x1bOA"},
2455 KeyDown: {K: "\x1b[B", A: "\x1bOB"},
2456 KeyRight: {K: "\x1b[C", A: "\x1bOC"},
2457 KeyLeft: {K: "\x1b[D", A: "\x1bOD"},
2458 KeyHome: {K: "\x1b[H", A: "\x1bOH"},
2459 KeyEnd: {K: "\x1b[F", A: "\x1bOF"},
2460 KeyPgUp: {K: "\x1b[5~"},
2461 KeyPgDn: {K: "\x1b[6~"},
2462 KeyDelete: {K: "\x1b[3~"},
2463 KeyInsert: {K: "\x1b[2~"},
2464 KeyMenu: {K: "\x1b[29~"}, // also F16
2465 KeyTab: {K: "\t", S: "\x1b[Z", CS: "\x1b[Z"},
2466 KeyBackspace: {K: "\x7f", S: "\x7f", C: "\x08", CS: "\x08"},
2467 KeySpace: {K: " ", S: " ", C: "\x00", CS: "\x00"},
2468 KeyEnter: {K: "\r", S: "\r", CS: "\r"}, // NB: consider using kitty encoding here
2469 KeyPadEnter: {K: "\r", S: "\r", CS: "\r"}, // NB: consider using kitty encoding here
2470 KeyEsc: {K: "\x1b", S: "\x1b", C: "\x1b"},
2471 }
2472
2473 var legacyControls = map[Key]string{
2474 // These ones are weird legacy control sequences that we mostly
2475 // do not care about. We don't include shifted variants.
2476 Key2: "\x00",
2477 Key3: "\x1b",
2478 Key4: "\x1c",
2479 Key5: "\x1d",
2480 Key6: "\x1e",
2481 Key7: "\x1f",
2482 Key8: "\x7f",
2483 KeyLBrace: "\x1b",
2484 KeySlash: "\x1c",
2485 KeyRBrace: "\x1d",
2486 }
2487
2488 // legacyPadKeys are keys that are on the keypad, when not in numeric keypad mode.
2489 // Note that num lock overrides this.
2490 var legacyPadKeys = map[Key]struct {
2491 app string
2492 num string
2493 }{
2494 KeyPadEnter: {"\x1bOM", "\r"},
2495 KeyPadMul: {"\x1bOj", "*"},
2496 KeyPadAdd: {"\x1bOk", "+"},
2497 KeyPadSub: {"\x1bOm", "-"},
2498 KeyPadDiv: {"\x1bOo", "/"},
2499 KeyPadDec: {"\x1b[3~", "."}, // Del
2500 KeyPad0: {"\x1b[2~", "0"}, // Ins
2501 KeyPad1: {"\x1bOF", "1"}, // End
2502 KeyPad2: {"\x1b[B", "2"}, // Down
2503 KeyPad3: {"\x1b[6~", "3"}, // PgDn
2504 KeyPad4: {"\x1b[D", "4"}, // Left
2505 KeyPad5: {"\x1b[E", "5"}, // Clear/Begin
2506 KeyPad6: {"\x1b[C", "6"}, // Right
2507 KeyPad7: {"\x1bOH", "7"}, // Home
2508 KeyPad8: {"\x1b[A", "8"}, // Up
2509 KeyPad9: {"\x1b[5~", "9"}, // PgUp
2510 KeyPadEqual: {"\x1bOX", "="},
2511 }
2512
2513 // repeatRaw is called to provide key repeat. We limit key repeating to just 40,
2514 // and we ensure that at least one is included. We only repeat if key repeat is enabled.
2515 func (em *emulator) repeatRaw(ev KeyEvent, data []byte) {
2516 if pm := em.getPrivateMode(PmAutoRepeat); pm == ModeOn || pm == ModeOnLocked {
2517 for range min(max(1, ev.Repeat), 40) {
2518 em.SendRaw(data)
2519 }
2520 } else {
2521 if ev.Repeat == 0 {
2522 em.SendRaw(data)
2523 }
2524 }
2525 }
2526
2527 // noRepeatRaw is used to send a key that should never repeat.
2528 // It will only send if the repeat count is zero.
2529 func (em *emulator) noRepeatRaw(ev KeyEvent, data []byte) {
2530 if ev.Repeat == 0 {
2531 em.SendRaw(data)
2532 }
2533 }
2534
2535 // keyLegacy handles a keyboard event when in legacy vt220 style mode.
2536 func (em *emulator) keyLegacy(ev KeyEvent) {
2537 if !ev.Down { // legacy protocol does not support key release
2538 return
2539 }
2540 if ev.Mod.IsMeta() || ev.Mod.IsHyper() { // legacy protocol does not support these
2541 return
2542 }
2543
2544 // Shift-Ctrl keys are never sent in the legacy protocol. We do have to ensure
2545 // that if we are sending other Utf (for example with AltGr), then we still might
2546 // send it, but this is only an issue for non-ASCII runes. Also, this filter only
2547 // applies for "regular" keys (i.e. not function keys, cursor keys, etc.)
2548 if ev.Mod.IsShift() && ev.Mod.IsCtrl() && (ev.Utf == "" || ev.Utf[0] < 0x80) {
2549 if base := ev.Key.KittyBase(); base >= ' ' && base < 0x80 {
2550 return
2551 }
2552 }
2553
2554 // keypad sequences
2555 if v, ok := legacyPadKeys[ev.Key]; ok {
2556 if ev.Mod&ModNumLock == 0 {
2557 if em.appKeyPad {
2558 em.repeatRaw(ev, []byte(v.app))
2559 } else {
2560 em.repeatRaw(ev, []byte(v.num))
2561 }
2562 return
2563 } else {
2564 ev.Utf = v.num
2565 }
2566 }
2567
2568 // For control keys (e.g. control-J) we never emit a rune directly -- but we might later
2569 // add after decoding the key accordingly.
2570 if ev.Utf != "" && (ev.Mod == ModLCtrl || ev.Mod == ModRCtrl || ev.Utf[0] < ' ') {
2571 ev.Utf = ""
2572 }
2573
2574 if ev.Utf != "" {
2575 if ev.Utf[0] < 0x80 && ev.Mod.IsAlt() { // ASCII might get alt
2576 em.noRepeatRaw(ev, fmt.Appendf(nil, "\x1b%s", ev.Utf))
2577 } else { // otherwise send the UTF as-is
2578 em.repeatRaw(ev, []byte(ev.Utf))
2579 }
2580 return
2581 }
2582
2583 // some weird number control sequences - legacy compatibility
2584 // We do not repeat these.
2585 if v, ok := legacyControls[ev.Key]; ok && (ev.Mod == ModLCtrl || ev.Mod == ModRCtrl) {
2586 em.noRepeatRaw(ev, []byte(v))
2587 return
2588 }
2589
2590 if v, ok := legacyKeys[ev.Key]; ok {
2591 str := ""
2592 match := false
2593 if !ev.Mod.IsShift() && !ev.Mod.IsCtrl() {
2594 if em.getPrivateMode(PmAppCursor) == ModeOn && v.A != "" {
2595 str = v.A
2596 } else {
2597 str = v.K
2598 }
2599 // AnsiMode 20 sends newline, but only in legacy mode.
2600 if str == "\r" && em.getAnsiMode(AmNewLineMode) == ModeOn {
2601 str = "\r\n"
2602 }
2603 match = true
2604 } else if ev.Mod.IsShift() && !ev.Mod.IsCtrl() {
2605 if str = v.S; str != "" {
2606 match = true
2607 }
2608 } else if ev.Mod.IsCtrl() && !ev.Mod.IsShift() {
2609 if str = v.C; str != "" {
2610 match = true
2611 }
2612 } else { // IsCtrl & IsShift
2613 if str = v.CS; str != "" {
2614 match = true
2615 }
2616 }
2617 if !match {
2618 // No specific modifiers present, lets add them. There are two cases,
2619 // one for SS3 based keys and another for CSI based keys. SS3 based
2620 // keys are converted to CSI - 1 ; mod ; final
2621 // Note: legacy encoding does not use modifiers for alt or super - alt will be
2622 // determined by sending an escape prefix.
2623 mod := 0
2624 if ev.Mod.IsShift() {
2625 mod |= 1
2626 }
2627 if ev.Mod.IsCtrl() {
2628 mod |= 4
2629 }
2630 if strings.HasPrefix(v.K, "\x1bO") {
2631 str = fmt.Sprintf("\x1b[1;%d%c", mod+1, v.K[len(v.K)-1])
2632 } else {
2633 str = fmt.Sprintf("%s;%d%c", v.K[:len(v.K)-1], mod+1, v.K[len(v.K)-1])
2634 }
2635 }
2636 if ev.Mod.IsAlt() {
2637 // no repeating ALT sequences
2638 em.noRepeatRaw(ev, append([]byte{'\x1b'}, []byte(str)...)) // alt sends leading escape
2639 } else if ev.Mod.IsCtrl() {
2640 // no repeating CTRL sequences
2641 em.noRepeatRaw(ev, []byte(str))
2642 } else {
2643 // but other sequences (should just be shifted or unmodified)
2644 // are fine. (E.g. we want to allow repeats of cursor keys)
2645 em.repeatRaw(ev, []byte(str))
2646 }
2647 return
2648 }
2649
2650 // fallback control key handling
2651 if ev.Key >= KeyA && ev.Key <= KeyZ && ev.Mod.IsCtrl() {
2652 b := byte(ev.Key-KeyA) + 1 /* ctrl-A */
2653 if ev.Mod.IsAlt() {
2654 em.noRepeatRaw(ev, []byte{'\x1b', b})
2655 } else {
2656 em.noRepeatRaw(ev, []byte{b})
2657 }
2658 return
2659 }
2660 }
2661
2662 var win32NoRepeat = map[Key]bool{
2663 KeyLShift: true,
2664 KeyRShift: true,
2665 KeyLCtrl: true,
2666 KeyRCtrl: true,
2667 KeyLAlt: true,
2668 KeyRAlt: true,
2669 KeyLMeta: true,
2670 KeyRMeta: true,
2671 KeyCapsLock: true,
2672 KeyNumLock: true,
2673 KeyEnter: true,
2674 KeyScrLock: true,
2675 KeyPause: true,
2676 KeyPrtScr: true,
2677 }
2678
2679 // keyWin32IM generates the sequence for a key event when in Win32 input mode.
2680 // Win32 input mode is ESC [ Vk ; Sc ; Uc ; Kd ; Cs ; Rc _
2681 // Note that we specifically do NOT doubly encode non-keyboard events -- those
2682 // are already unambiguously handled within the protocol. (Windows Terminal behaves
2683 // the same way, but most 3rd party terminals do doubly encode.)
2684 func (em *emulator) keyWin32IM(ev KeyEvent) {
2685 // Some keys that never repeat
2686 if pm := em.getPrivateMode(PmAutoRepeat); pm == ModeOff || pm == ModeOffLocked {
2687 if ev.Repeat != 0 {
2688 return
2689 }
2690 }
2691 r := rune(0)
2692 if ev.Utf != "" {
2693 runes := []rune(ev.Utf)
2694 if len(runes) == 1 {
2695 r = runes[0]
2696 }
2697 }
2698 kd := 0
2699 if ev.Down {
2700 kd = 1
2701 }
2702 cs := 0
2703 // Modifiers
2704 if ev.Mod&ModRAlt != 0 {
2705 cs |= 0x01
2706 }
2707 if ev.Mod&ModLAlt != 0 {
2708 cs |= 0x02
2709 }
2710 if ev.Mod&ModRCtrl != 0 {
2711 cs |= 0x04
2712 }
2713 if ev.Mod&ModLCtrl != 0 {
2714 cs |= 0x08
2715 }
2716 if ev.Mod.IsShift() {
2717 cs |= 0x10
2718 }
2719 if ev.Mod.IsNumLock() {
2720 cs |= 0x20
2721 }
2722 // NB: 0x40 is for scroll lock, we don't support it for now
2723 if ev.Mod.IsCapsLock() {
2724 cs |= 0x80
2725 }
2726 switch ev.Key {
2727 case KeyPadEnter:
2728 case KeyPadDiv:
2729 case KeyInsert:
2730 case KeyDelete:
2731 case KeyHome:
2732 case KeyEnd:
2733 case KeyPgUp:
2734 case KeyPgDn:
2735 cs |= 0x100 // enhanced
2736 }
2737 if win32NoRepeat[ev.Key] {
2738 if ev.Repeat > 0 {
2739 return
2740 }
2741 ev.Repeat = 1
2742 }
2743 em.SendRaw(fmt.Appendf(nil, "\x1b[%d;%d;%d;%d;%d;%d_", ev.VK, ev.SC, r, kd, cs, max(1, ev.Repeat)))
2744 }
2745
2746 func (em *emulator) MouseEvent(ev MouseEvent) {
2747 if pm := em.getPrivateMode(PmMouseButton); pm == ModeOn {
2748
2749 if em.getPrivateMode(PmMouseDrag) != ModeOn && em.getPrivateMode(PmMouseMotion) != ModeOn {
2750 // suppress motion events if the user didn't request
2751 if ev.Button == NoButton {
2752 return // if entire event was just motion, bail
2753 }
2754 ev.Motion = false
2755 }
2756
2757 if pm = em.getPrivateMode(PmMouseSgr); pm == ModeOn {
2758 btn := ev.encodeButton()
2759 if ev.Down {
2760 em.SendRaw(fmt.Appendf(nil, "\x1b[<%d;%d;%dM", btn, ev.Position.X+1, ev.Position.Y+1))
2761 } else {
2762 em.SendRaw(fmt.Appendf(nil, "\x1b[<%d;%d;%dm", btn, ev.Position.X+1, ev.Position.Y+1))
2763 }
2764 } else {
2765 // Old style reporting (via 1000h).
2766 // Limitations of legacy VT200 reporting are that the coordinates must be between
2767 // 1 and 223 inclusive, and that once any release occurs all buttons are assumed
2768 // to be released. (Please use SGR mode if at all possible.)
2769 // Further, this mode is not CSI compliant as the encoded values that arrive ahead of
2770 // the final character may be within the range of technically legal CSI final bytes.
2771 if !ev.Down {
2772 ev.Button = NoButton
2773 }
2774 btn := ev.encodeButton()
2775 data := append([]byte{'\x1b', '[', 'M', btn + 32},
2776 byte(min(ev.Position.X+1, 223)+32),
2777 byte(min(ev.Position.Y+1, 223)+32))
2778 em.SendRaw(data)
2779 }
2780
2781 } else if pm := em.getPrivateMode(PmMouseX10); pm == ModeOn && ev.Down {
2782 // legacy X10 reporting only
2783 x := byte(min(ev.Position.X+1, 223)) + 32
2784 y := byte(min(ev.Position.Y+1, 223)) + 32
2785 // NB: we intentionally reverse buttons 2 & 3 (for xterm compatibility)
2786 switch ev.Button {
2787 case Button1:
2788 em.SendRaw([]byte{'\x1b', '[', 'M', ' ', x, y})
2789 case Button2:
2790 em.SendRaw([]byte{'\x1b', '[', 'M', '"', x, y})
2791 case Button3:
2792 em.SendRaw([]byte{'\x1b', '[', 'M', '!', x, y})
2793 }
2794 }
2795 }
2796
2797 func (em *emulator) FocusEvent(focused bool) {
2798 if pm := em.getPrivateMode(PmFocusReports); pm == ModeOn {
2799 if focused {
2800 em.SendRaw([]byte{'\x1b', '[', 'I'})
2801 } else {
2802 em.SendRaw([]byte{'\x1b', '[', 'O'})
2803 }
2804 }
2805 }
2806
2807 // SetId sets the terminal name and version.
2808 func (em *emulator) SetId(name string, version string) {
2809 em.name = name
2810 em.vers = version
2811 }
2812
2813 // Start the terminal emulator.
2814 func (em *emulator) Start() error {
2815 select {
2816 case <-em.stopQ:
2817 default:
2818 // already running
2819 return errors.New("terminal already started")
2820 }
2821 stopQ := make(chan bool)
2822 em.stopQ = stopQ
2823 go em.run(stopQ)
2824 return nil
2825 }
2826
2827 // Stop the terminal emulator. This also wakes any blocked
2828 // Read or Write calls, which will return an error.
2829 func (em *emulator) Stop() error {
2830 select {
2831 case <-em.stopQ:
2832 default:
2833 close(em.stopQ)
2834 }
2835 return nil
2836 }
2837
2838 // Drain pending output to the terminal emulator.
2839 func (em *emulator) Drain() error {
2840 q := make(chan bool)
2841 select {
2842 case em.writeQ <- q:
2843 case <-em.stopQ:
2844 }
2845 select {
2846 case <-q:
2847 case <-em.stopQ:
2848 }
2849 // make sure to wake the reader
2850 select {
2851 case em.readQ <- true:
2852 default:
2853 }
2854 return nil
2855 }
2856
2857 // Write data to the emulator (commands).
2858 func (em *emulator) Write(data []byte) (n int, err error) {
2859 stopQ := em.stopQ
2860 writeQ := em.writeQ
2861 drainQ := make(chan bool)
2862 select {
2863 case writeQ <- data:
2864 // we add the drainQ for synchronization, so that we only
2865 // return after the the emulator has processed this.
2866 select {
2867 case <-stopQ:
2868 return 0, errors.New("terminal emulator stopped")
2869 case writeQ <- drainQ:
2870 }
2871 select {
2872 case <-stopQ:
2873 return 0, errors.New("terminal emulator stopped")
2874 case <-drainQ:
2875 return len(data), nil
2876 }
2877 case <-stopQ:
2878 return 0, errors.New("terminal emulator stopped")
2879 }
2880 }
2881
2882 // Read data (key events, etc.) from the emulator.
2883 func (em *emulator) Read(data []byte) (n int, err error) {
2884 stopQ := em.stopQ
2885 readQ := em.readQ
2886
2887 n = 0
2888 if len(data) < 1 {
2889 return 0, nil
2890 }
2891 select {
2892 case <-stopQ:
2893 return 0, errors.New("terminal emulator stopped")
2894 case v := <-readQ:
2895 // The data arriving in the channel may be a byte, or it might be a bool
2896 // trying to force a wake up. Note that the bool may be intermingled with other
2897 // bytes, so we check it. Also data may have arrived since the bool was posted,
2898 // so make sure we don't terminate until we have collected all the relevant data
2899 // that we can (up to the limit of what was requested.)
2900 if ch, ok := v.(byte); ok {
2901 data[n] = ch
2902 n++
2903 }
2904 for n < len(data) {
2905 select {
2906 case v = <-readQ:
2907 if ch, ok := v.(byte); ok {
2908 data[n] = ch
2909 n++
2910 }
2911 default:
2912 return n, nil
2913 }
2914 }
2915 return n, nil
2916 }
2917 }
2918
2919 func (em *emulator) run(stopQ <-chan bool) {
2920 for {
2921 select {
2922 case item := <-em.writeQ:
2923 switch d := item.(type) {
2924 case byte:
2925 em.inb(d)
2926 case []byte:
2927 for _, ch := range d {
2928 em.inb(ch)
2929 }
2930 case chan bool:
2931 close(d)
2932
2933 case Coord: // resize notification
2934 em.applyResize(d)
2935 }
2936 case <-stopQ:
2937 return
2938 }
2939 }
2940 }