aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/term/screen.go
blob: 14bfcfbd716472c5024288abd8c266a29704342f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package term

import (
	"github.com/gdamore/tcell/v2"
)

type Screen struct {
	scr tcell.Screen
	onResize func() bool
	QuitC chan struct{}
}

func NewScreen() (*Screen, error) {
	scr, err := tcell.NewScreen()
	if err != nil{
		return nil, err
	}
	err = scr.Init()
	if err != nil{
		return nil, err
	}
	return &Screen{
		scr: scr,
		QuitC: make(chan struct{}),
	}, nil
}

func (scr *Screen) Close() {
	scr.scr.Fini()
}

func (scr *Screen) Size() (int, int) {
	return scr.scr.Size()
}

func (scr *Screen) Clear(style Style) {
	scr.scr.SetStyle(tcell.Style(style))
	scr.scr.Clear()
}

func (scr *Screen) OnResize(handler func() bool) {
	scr.onResize = handler
}

func (scr *Screen) Show() {
	scr.scr.Show()
}

func (scr *Screen) DoEventLoop() {
	for {
		scr.scr.Show()

		ev := scr.scr.PollEvent()
		switch ev := ev.(type) {
		case *tcell.EventResize:
			if scr.onResize != nil {
				if quit := scr.onResize(); quit {
					return
				}
			}
			scr.scr.Sync()
		case *tcell.EventKey:
			if ev.Key() == tcell.KeyEscape || ev.Key() == tcell.KeyCtrlC || ev.Rune() == 'q' {
				close(scr.QuitC)
				return
			}
			scr.scr.Sync()
		}
	}
}