-
Notifications
You must be signed in to change notification settings - Fork 0
/
window.go
139 lines (103 loc) · 2.09 KB
/
window.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Copyright 2015 Ghislain Guiot <[email protected]>. All rights reserved.
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.
package termutil
import "github.com/nsf/termbox-go"
type UpdateFunc func() []Row
type EventFunc func(termbox.Event)
type Window struct {
X, Y int
SizeX, SizeY int
// AutoResize does not allow a fix SizeX and SizeY
AutoResize bool
rows []Row
UpdateFunc UpdateFunc
EventFunc EventFunc
parent *Window
SubWindows []*Window
}
func (w *Window) update() {
if w.UpdateFunc != nil {
w.rows = w.UpdateFunc()
}
for _, sub := range w.SubWindows {
sub.update()
}
}
func (w *Window) draw() {
w.drawWin()
for _, sub := range w.SubWindows {
sub.draw()
}
}
func (w *Window) drawWin() {
ax := w.AbsX()
ay := w.AbsY()
termX, termY := termbox.Size()
sizeY := termY - ay
if sizeY > w.SizeY {
sizeY = w.SizeY
}
if sizeY > len(w.rows) {
sizeY = len(w.rows)
}
for y := ay; y-ay < sizeY; y++ {
sizeX := termX - ax
if sizeX > w.SizeX {
sizeX = w.SizeX
}
if sizeX > len(w.rows[y-ay]) {
sizeX = len(w.rows[y-ay])
}
for x := ax; x-ax < sizeX; x++ {
c := w.rows[y-ay][x-ax]
termbox.SetCell(x, y, c.C, c.Fg, c.Bg)
}
}
}
func (w *Window) resize() {
if w.AutoResize {
if w.parent == nil {
w.SizeX, w.SizeY = termbox.Size()
} else {
w.SizeX = w.parent.SizeX - w.AbsX()
w.SizeY = w.parent.SizeY - w.AbsY()
}
}
for _, sub := range w.SubWindows {
sub.resize()
}
}
func (w *Window) AbsX() int {
var x int
if w.parent != nil {
x = w.parent.AbsX()
}
return w.X + x
}
func (w *Window) AbsY() int {
var y int
if w.parent != nil {
y = w.parent.AbsY()
}
return w.Y + y
}
func (w *Window) NewSubWindow() *Window {
win := &Window{
parent: w,
SizeX: w.SizeX,
SizeY: w.SizeY,
AutoResize: true,
}
w.SubWindows = append(w.SubWindows, win)
return win
}
func NewWindow() *Window {
win := &Window{
AutoResize: true,
}
win.SizeX, win.SizeY = termbox.Size()
Screen.windows = append(Screen.windows, win)
Screen.current = win
return win
}