Debian Codegraph @

vt/mock.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 "slices"
19 "sync"
20 "time"
21
22 "github.com/gdamore/tcell/v3/color"
23 "github.com/gdamore/tcell/v3/tty"
24 )
25
26 // mockTerm implements MockTerm.
27 type mockTerm struct {
28 mb MockBackend
29 em Emulator
30 ks *KeyboardState
31 }
32
33 // Stop the terminal.
34 func (mt *mockTerm) Stop() error {
35 return mt.em.Stop()
36 }
37
38 // Start the terminal.
39 func (mt *mockTerm) Start() error {
40 return mt.em.Start()
41 }
42
43 // Drain all output from the terminal, ensuring
44 // any queued commands are processed.
45 func (mt *mockTerm) Drain() error {
46 return mt.em.Drain()
47 }
48
49 // Read data from the terminal. This is called by a terminal
50 // application (e.g. via tcell Tty.) Read data will include
51 // key strokes, mouse events, and responses to terminal queries.
52 func (mt *mockTerm) Read(data []byte) (int, error) {
53 return mt.em.Read(data)
54 }
55
56 // Write data to the terminal, typically either commands or data
57 // that should be displayed on the virtual screen.
58 func (mt *mockTerm) Write(b []byte) (n int, err error) {
59 return mt.em.Write(b)
60 }
61
62 // WindowSize obtains the dimensions of the window.
63 func (mt *mockTerm) WindowSize() (tty.WindowSize, error) {
64 sz := mt.mb.GetSize()
65 // No pixel sizes for now
66 return tty.WindowSize{Width: int(sz.X), Height: int(sz.Y)}, nil
67 }
68
69 // NotifyResize registers a channel to be signaled when a resize has occurred.
70 // In real terminal emulators this would be posted (non-blocking) by a signal handler.
71 func (mt *mockTerm) NotifyResize(resizeq chan<- bool) {
72 if rs, ok := mt.mb.(Resizer); ok {
73 rs.NotifyResize(resizeq)
74 }
75 }
76
77 // Close closes the terminal, after which it should no longer be used. Stop is implied.
78 func (mt *mockTerm) Close() error {
79 return mt.Stop()
80 }
81
82 // Pos returns the cursor position.
83 func (mt *mockTerm) Pos() Coord {
84 return mt.mb.GetPosition()
85 }
86
87 // GetCell returns the contents of the cell at the given coordinates, or a zero value
88 // if the coordinates are out of range.
89 func (mt *mockTerm) GetCell(pos Coord) Cell {
90 return mt.mb.GetCell(pos)
91 }
92
93 // Bells counts the number of times the bell has rung.
94 func (mt *mockTerm) Bells() int {
95 return mt.mb.Bells()
96 }
97
98 // KeyEvent is used to inject a key event. Call this to inject
99 // a synthetic, fully specified key event. Most uses should just use
100 // the KeyPress, KeyRelease, or even simpler KeyTap APIs.
101 func (mt *mockTerm) KeyEvent(ev KeyEvent) {
102 mt.em.KeyEvent(ev)
103 if ev.Key == KeyEsc {
104 // Inject a delay to simulate human typing.
105 // Necessary to disambiguate Escape from other sequences.
106 time.Sleep(time.Millisecond * 150)
107 }
108 }
109
110 // KeyPress implements MockTerm.KeyPress.
111 func (mt *mockTerm) KeyPress(k Key) {
112 if event := mt.ks.Pressed(k); event != nil {
113 mt.KeyEvent(*event)
114 }
115 }
116
117 // KeyRelease implements MockTerm.KeyRelease.
118 func (mt *mockTerm) KeyRelease(k Key) {
119 if event := mt.ks.Released(k); event != nil {
120 mt.KeyEvent(*event)
121 }
122 }
123
124 // KeyTap implements MockTerm.KeyTap.
125 func (mt *mockTerm) KeyTap(keys ...Key) {
126 for _, k := range keys {
127 mt.KeyPress(k)
128 }
129 for _, k := range slices.Backward(keys) {
130 mt.KeyRelease(k)
131 }
132 }
133
134 // SetRepeat sets the repeat interval for the keyboard.
135 // Set the interval to zero to disable repeat.
136 func (mt *mockTerm) SetRepeat(delay, interval time.Duration) {
137 mt.ks.SetRepeat(delay, interval)
138 }
139
140 // MouseEvent implements MockTerm.MouseEvent.
141 func (mt *mockTerm) MouseEvent(ev MouseEvent) {
142 mt.em.MouseEvent(ev)
143 }
144
145 // FocusEvent implements MockTerm.FocusEvent.
146 func (mt *mockTerm) FocusEvent(focused bool) {
147 mt.em.FocusEvent(focused)
148 }
149
150 // GetTitle returns the current window title.
151 func (mt *mockTerm) GetTitle() string {
152 return mt.mb.GetTitle()
153 }
154
155 // SetSize is used to change the terminal size.
156 func (mt *mockTerm) SetSize(size Coord) {
157 mt.mb.SetSize(size)
158 mt.em.ResizeEvent(size)
159 }
160
161 // Backend returns the backend for testing.
162 func (mt *mockTerm) Backend() MockBackend {
163 return mt.mb
164 }
165
166 // SendRaw is used to inject raw bytes to the read stream of the app.
167 // Use this for fuzz testing.
168 func (mt *mockTerm) SendRaw(data []byte) {
169 mt.em.SendRaw(data)
170 }
171
172 // SetLayout sets the keyboard layout.
173 func (mt *mockTerm) SetLayout(km *Layout) {
174 mt.ks.SetLayout(km)
175 }
176
177 // MockTerm is a mock terminal (emulator). It can be used to
178 // test the emulator itself, or to test applications (or tcell) that
179 // uses the terminal. It also implements the Tty interface used
180 // by tcell itself.
181 type MockTerm interface {
182 tty.Tty
183
184 // Pos reports the current cursor position.
185 Pos() Coord
186
187 // GetCell returns the cell at the given coordinates.
188 // The coordinates must be valid.
189 GetCell(Coord) Cell
190
191 // Bells returns the number of times the bell has been rung.
192 Bells() int
193
194 // Inject a keyboard event - this is a full event, and bypasses
195 // the layout and keyboard state processor.
196 KeyEvent(KeyEvent)
197
198 // Inject a key press.
199 KeyPress(Key)
200
201 // Inject a key release.
202 KeyRelease(Key)
203
204 // SetRepeat configures keyboard repeating. Repeat keystrokes
205 // will be assumed after the key has been held for at least delay,
206 // with new keys added each interval.
207 SetRepeat(delay, interval time.Duration)
208
209 // Inject one or more key press and releases.
210 // The keys are pressed in the order, and released in reverse order.
211 // Thus modifiers should be listed first. This should not be used
212 // to simulate typing a sequence (e.g. a word), but if you wanted to
213 // test say N-Key rollover you could do that here.
214 KeyTap(...Key)
215
216 // Inject a mouse event.
217 MouseEvent(MouseEvent)
218
219 // Inject a focus event.
220 FocusEvent(bool)
221
222 // GetTitle obtains the current window title.
223 GetTitle() string
224
225 // SetSize is used to resize the terminal.
226 SetSize(Coord)
227
228 // SendRaw is used to send raw data to the application.
229 // This is mostly intended to facilitate fuzz testing the application.
230 SendRaw([]byte)
231
232 // Backend returns the backend (used for testing).
233 Backend() MockBackend
234
235 // SetLayout sets the keyboard layout to use.
236 // If not specified, a US standard ANSI keyboard will be assumed.
237 SetLayout(*Layout)
238 }
239
240 type noMockBlit struct {
241 MockBackend
242 Blit struct{} // prevents use as Blitter
243 }
244
245 // NewMockTerm gives a mock terminal emulator.
246 func NewMockTerm(opts ...MockOpt) MockTerm {
247 mt := &mockTerm{}
248 mt.mb = NewMockBackend(opts...)
249 var be MockBackend = mt.mb
250 emOpts := []EmulatorOpt{}
251 for _, o := range opts {
252 switch o.(type) {
253 case MockOptNoBlit:
254 be = &noMockBlit{be, struct{}{}}
255 case MockOpt8BitControls:
256 emOpts = append(emOpts, EmulatorOpt8BitControls{})
257 }
258 }
259 mt.em = NewEmulator(be, emOpts...)
260 mt.em.SetId("TCellMock", "1.0")
261 mt.ks = &KeyboardState{}
262 return mt
263 }
264
265 // MockBackend provides additional mock-specific capabilities on top of Backend.
266 // This is meant to facilitate test cases
267 type MockBackend interface {
268 Backend
269
270 // GetCell returns the cell at the given position, or an empty cell if the
271 // position is out of the bounds of the window.
272 GetCell(Coord) Cell
273
274 // Bells counts the number of bells rung.
275 Bells() int
276
277 // GetTitle gets the current window title.
278 GetTitle() string
279
280 // SetSize is used to resize the window.
281 // Newly added cells are empty, and content in old cells that out of range is lost.
282 SetSize(Coord)
283
284 // GetCursor is used to obtain the current cursor style.
285 GetCursor() CursorStyle
286
287 // SetClipboard sets the clipboard contents (copy buffer).
288 SetClipboard([]byte)
289
290 // GetClipboard returns the clipboard (copy buffer).
291 GetClipboard() []byte
292
293 // IsAdvancedKeyboard returns true, as we always support the full keyboard protocol.
294 IsAdvancedKeyboard() bool
295 }
296
297 // mockBackend is a mock of a backend device for use with the emulator.
298 // It implements the following interfaces:
299 // vt.Backend, vt.Beeper, vt.Colorer, vt.Titler, vt.Resizer, vt.Blitter
300 type mockBackend struct {
301 cells []Cell // Content of cells
302 size Coord
303 pos Coord
304 colors int
305 style Style
306 defaultStyle Style
307 notifyQ chan<- bool
308 resized bool
309 newSize Coord
310 modes map[PrivateMode]ModeStatus
311 bells int
312 errs int
313 title string
314 clipboard []byte
315 cursor CursorStyle
316 lock sync.Mutex
317 }
318
319 func (mb *mockBackend) GetSize() Coord {
320 mb.lock.Lock()
321 defer mb.lock.Unlock()
322 mb.checkSize()
323 return mb.size
324 }
325
326 func (mb *mockBackend) Beep() {
327 mb.lock.Lock()
328 mb.bells++
329 mb.lock.Unlock()
330 }
331
332 func (mb *mockBackend) SetMouse(MouseReporting) {}
333
334 func (mb *mockBackend) GetPrivateMode(pm PrivateMode) ModeStatus {
335 mb.lock.Lock()
336 defer mb.lock.Unlock()
337 // note default (zero) value is ModeNA
338 return mb.modes[pm]
339 }
340
341 func (mb *mockBackend) SetPrivateMode(pm PrivateMode, status ModeStatus) error {
342 mb.lock.Lock()
343 defer mb.lock.Unlock()
344 if old := mb.modes[pm]; old == ModeOn || old == ModeOff {
345 if status == ModeOn || status == ModeOff {
346 mb.modes[pm] = status
347 } else {
348 mb.errs++
349 }
350 } else {
351 mb.errs++
352 }
353 return nil
354 }
355
356 func (mb *mockBackend) Put(pos Coord, cell Cell) { // grapheme string, width int, style Style) {
357 mb.lock.Lock()
358 defer mb.lock.Unlock()
359 mb.checkSize()
360
361 if index := mb.index(pos); index >= 0 {
362 mb.cells[index] = cell
363
364 // writing to a cell right after a wide
365 // character clears that wide character (but leaves style/attributes)
366 if cell.W > 0 && pos.X > 0 && mb.cells[index-1].W > 1 {
367 mb.cells[index-1].C = ""
368 mb.cells[index-1].W = 0
369 }
370
371 // wide characters delete the next cell
372 if cell.W == 2 && pos.X < mb.size.X-1 {
373 mb.cells[index+1].C = ""
374 mb.cells[index+1].W = 0
375 mb.cells[index+1].S = cell.S
376 }
377 } else {
378 mb.errs++
379 }
380 }
381
382 func (mb *mockBackend) isPositionValid(pos Coord) bool {
383 mb.checkSize()
384
385 return pos.X < mb.size.X && pos.Y < mb.size.Y && pos.X >= 0 && pos.Y >= 0
386 }
387
388 // index calculates the index in the cells array. If the coordinates are invalid,
389 // -1 will be returned.
390 func (mb *mockBackend) index(pos Coord) int {
391 mb.checkSize()
392
393 if !mb.isPositionValid(pos) {
394 return -1
395 }
396 return int(pos.X) + int(pos.Y)*int(mb.size.X)
397 }
398
399 func (mb *mockBackend) GetCell(pos Coord) Cell {
400 mb.lock.Lock()
401 defer mb.lock.Unlock()
402
403 if index := mb.index(pos); index >= 0 {
404 return mb.cells[index]
405 }
406 return Cell{S: BaseStyle}
407 }
408
409 func (mb *mockBackend) Bells() int {
410 mb.lock.Lock()
411 defer mb.lock.Unlock()
412 return mb.bells
413 }
414
415 func (mb *mockBackend) GetPosition() Coord {
416 mb.lock.Lock()
417 defer mb.lock.Unlock()
418 mb.checkSize()
419 return mb.pos
420 }
421
422 func (mb *mockBackend) SetPosition(pos Coord) {
423 mb.lock.Lock()
424 defer mb.lock.Unlock()
425 mb.checkSize()
426 pos.X = min(mb.size.X-1, max(0, pos.X))
427 pos.Y = min(mb.size.Y-1, max(0, pos.Y))
428 mb.pos = pos
429 }
430
431 func (mb *mockBackend) Colors() int {
432 return mb.colors
433 }
434
435 func (mb *mockBackend) SetStyle(style Style) {
436 mb.lock.Lock()
437 defer mb.lock.Unlock()
438
439 mb.style = style
440 }
441
442 // SetWindowTitle implements the Titler interface.
443 func (mb *mockBackend) SetWindowTitle(title string) {
444 mb.lock.Lock()
445 defer mb.lock.Unlock()
446
447 mb.title = title
448 }
449
450 // GetTitle allows test code to observe what was set with SetWindowTitle.
451 func (mb *mockBackend) GetTitle() string {
452 mb.lock.Lock()
453 defer mb.lock.Unlock()
454
455 return mb.title
456 }
457
458 // NotifyResize registers a channel to be written to (non-blocking) if the
459 // backend changes size.
460 func (mb *mockBackend) NotifyResize(rq chan<- bool) {
461 mb.lock.Lock()
462 defer mb.lock.Unlock()
463
464 mb.notifyQ = rq
465 }
466
467 // checkSize performs a possible terminal resize. Cells that are
468 // added are treated as empty, while cells that are removed are just lost.
469 // (Note that at least one other emulator erases content on a resize. There is no
470 // standard for what to do here.) This is done inline when calculating the index.
471 // The caller is expected to hold mb.lock.
472 func (mb *mockBackend) checkSize() {
473 if !mb.resized {
474 return
475 }
476 size := mb.newSize
477 old := mb.cells
478 ox := int(mb.size.X)
479 oy := int(mb.size.Y)
480 nx := int(size.X)
481 ny := int(size.Y)
482 cells := make([]Cell, int(size.Y)*int(size.X))
483 for i := range cells {
484 cells[i].S = BaseStyle
485 }
486 for y := range min(ny, oy) {
487 for x := range min(nx, ox) {
488 cells[y*nx+x] = old[y*ox+x]
489 }
490 }
491 mb.cells = cells
492 mb.size = size
493 mb.pos.X = min(mb.pos.X, size.X-1)
494 mb.pos.Y = min(mb.pos.Y, size.Y-1)
495 mb.resized = false
496 }
497
498 func (mb *mockBackend) RaiseResize() {
499 mb.lock.Lock()
500 defer mb.lock.Unlock()
501
502 if rq := mb.notifyQ; rq != nil {
503 select {
504 case rq <- true:
505 default:
506 }
507 }
508 }
509
510 // SetSize is used to change the size of the virtual terminal.
511 func (mb *mockBackend) SetSize(size Coord) {
512 mb.lock.Lock()
513 mb.resized = true
514 mb.newSize = size
515 mb.lock.Unlock()
516 }
517
518 // Reset the terminal to startup defaults.
519 func (mb *mockBackend) Reset() {
520 mb.lock.Lock()
521 defer mb.lock.Unlock()
522
523 mb.style = mb.defaultStyle
524
525 mb.title = ""
526 mb.errs = 0
527 mb.bells = 0
528 mb.pos = Coord{X: 0, Y: 0}
529 mb.modes[PmShowCursor] = ModeOn
530 mb.modes[PmBlinkCursor] = ModeOn
531 mb.modes[PmGraphemeClusters] = ModeOff
532 }
533
534 func (mb *mockBackend) Blit(src, dst, dim Coord) {
535 mb.lock.Lock()
536 defer mb.lock.Unlock()
537
538 mb.checkSize()
539
540 // clip to visible source
541 if dim.X+src.X > mb.size.X {
542 dim.X = mb.size.X - src.X
543 }
544 if dim.Y+src.Y > mb.size.Y {
545 dim.Y = mb.size.Y - src.Y
546 }
547 // and clip to final destination
548 if dim.X+dst.X > mb.size.X {
549 dim.X = mb.size.X - dst.X
550 }
551 if dim.Y+dst.Y > mb.size.Y {
552 dim.Y = mb.size.Y - dst.Y
553 }
554
555 // gap represents decrement when shifting to the next row --
556 // skipping over the irrelevant cells. (The increment in the
557 // index when going from last cell of row to first cell of next row,
558 // or vice versa.)
559 gap := int(mb.size.X - dim.X)
560
561 // the following logic is carefully constructed to avoid expensive
562 // operations in the loops (only addition or subtraction)
563 if mb.index(src) > mb.index(dst) { // source appears later, so we can forward copy
564 si := mb.index(src)
565 di := mb.index(dst)
566 for range dim.Y {
567 for range dim.X {
568 mb.cells[di] = mb.cells[si]
569 di++
570 si++
571 }
572 // advance to next row
573 si += gap
574 di += gap
575 }
576 } else { // source appears earlier, so we have to reverse copy
577 src.Y += dim.Y - 1
578 dst.Y += dim.Y - 1
579 src.X += dim.X - 1
580 dst.X += dim.X - 1
581 si := mb.index(src)
582 di := mb.index(dst)
583
584 for range dim.Y {
585 for range dim.X {
586 mb.cells[di] = mb.cells[si]
587 si--
588 di--
589 }
590 si -= gap
591 di -= gap
592 }
593 }
594 }
595
596 // Buffering is not supported by the mockBackend, and there is little point in it.
597 func (mb *mockBackend) Buffering(bool) {}
598
599 // SetCursor is used to set how the cursor is displayed.
600 func (mb *mockBackend) SetCursor(cs CursorStyle) {
601 mb.lock.Lock()
602 defer mb.lock.Unlock()
603 mb.cursor = cs
604 }
605
606 // GetCursor returns the current cursor style.
607 func (mb *mockBackend) GetCursor() CursorStyle {
608 mb.lock.Lock()
609 defer mb.lock.Unlock()
610 return mb.cursor
611 }
612
613 // SetClipboard sets the current clipboard contents.
614 func (mb *mockBackend) SetClipboard(data []byte) {
615 mb.lock.Lock()
616 defer mb.lock.Unlock()
617 mb.clipboard = data
618 }
619
620 // GetClipboard gets the current clipboard contents.
621 func (mb *mockBackend) GetClipboard() []byte {
622 mb.lock.Lock()
623 defer mb.lock.Unlock()
624 return mb.clipboard
625 }
626
627 // IsAdvancedKeyboard returns true - we always implement
628 // the raw keyboard protocol.
629 func (mb *mockBackend) IsAdvancedKeyboard() bool { return true }
630
631 // MockOpt is an interface by which options can change the behavior of the mocked terminal.
632 // This is intended to permit easier testing.
633 type MockOpt interface{ SetMockOpt(mb *mockBackend) }
634
635 // MockOptSize changes the default terminal size, which is normally 80x24.
636 type MockOptSize Coord
637
638 func (o MockOptSize) SetMockOpt(mb *mockBackend) { mb.size = Coord(o) }
639
640 // MockOptColors changes the number of colors the terminal supports.
641 type MockOptColors int
642
643 func (o MockOptColors) SetMockOpt(mb *mockBackend) { mb.colors = int(o) }
644
645 // MockOptNoBlit suppresses the blitter interface.
646 type MockOptNoBlit struct{}
647
648 func (MockOptNoBlit) SetMockOpt(mb *mockBackend) {}
649
650 // MockOpt8BitControls enables raw 8-bit and UTF-8 encoded C1 controls in the
651 // emulator. The default is to accept only 7-bit ESC-prefixed controls.
652 type MockOpt8BitControls struct{}
653
654 func (MockOpt8BitControls) SetMockOpt(mb *mockBackend) {}
655
656 // NewMockBackend returns a MockBackend modified by the given options.
657 // The default is a fully featured 256-color backend with initial size 80x24.
658 func NewMockBackend(options ...MockOpt) MockBackend {
659 mb := &mockBackend{
660 size: Coord{X: 80, Y: 24},
661 colors: 256,
662 style: BaseStyle,
663 defaultStyle: BaseStyle.WithFg(color.Silver).WithBg(color.Black),
664 cursor: BlinkingBlock,
665 }
666
667 for _, opt := range options {
668 opt.SetMockOpt(mb)
669 }
670
671 if mb.colors > 0 {
672 mb.style = mb.defaultStyle
673 }
674 mb.cells = make([]Cell, int(mb.size.X)*int(mb.size.Y))
675 for i := range mb.cells {
676 mb.cells[i].S = BaseStyle
677 }
678
679 mb.modes = make(map[PrivateMode]ModeStatus)
680 mb.modes[PmShowCursor] = ModeOn
681 mb.modes[PmBlinkCursor] = ModeOn
682 mb.modes[PmGraphemeClusters] = ModeOff
683 mb.modes[PmSyncOutput] = ModeOff
684 return mb
685 }