forked from gizak/termui
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathgrid.go
More file actions
131 lines (113 loc) · 2.47 KB
/
grid.go
File metadata and controls
131 lines (113 loc) · 2.47 KB
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
package gotui
// NewGrid returns a new Grid.
func NewGrid() *Grid {
g := &Grid{
Block: *NewBlock(),
}
g.Border = false
return g
}
// NewCol creates a new column with the given size ratio and items.
func NewCol(ratio float64, i ...any) GridItem {
_, ok := i[0].(Drawable)
entry := i[0]
if !ok {
entry = i
}
return GridItem{
Type: col,
Entry: entry,
IsLeaf: ok,
ratio: ratio,
}
}
// NewRow creates a new row with the given size ratio and items.
func NewRow(ratio float64, i ...any) GridItem {
_, ok := i[0].(Drawable)
entry := i[0]
if !ok {
entry = i
}
return GridItem{
Type: row,
Entry: entry,
IsLeaf: ok,
ratio: ratio,
}
}
// Set sets the items in the grid.
func (g *Grid) Set(entries ...any) {
entry := GridItem{
Type: row,
Entry: entries,
IsLeaf: false,
ratio: 1.0,
}
g.setHelper(entry, 1.0, 1.0)
}
func (g *Grid) setHelper(item GridItem, parentWidthRatio, parentHeightRatio float64) {
var HeightRatio float64
var WidthRatio float64
switch item.Type {
case col:
HeightRatio = 1.0
WidthRatio = item.ratio
case row:
HeightRatio = item.ratio
WidthRatio = 1.0
}
item.WidthRatio = parentWidthRatio * WidthRatio
item.HeightRatio = parentHeightRatio * HeightRatio
if item.IsLeaf {
g.Items = append(g.Items, &item)
} else {
XRatio := 0.0
YRatio := 0.0
cols := false
rows := false
children := InterfaceSlice(item.Entry)
for i := range children {
if children[i] == nil {
continue
}
child, _ := children[i].(GridItem)
child.XRatio = item.XRatio + (item.WidthRatio * XRatio)
child.YRatio = item.YRatio + (item.HeightRatio * YRatio)
switch child.Type {
case col:
cols = true
XRatio += child.ratio
if rows {
item.HeightRatio /= 2
}
case row:
rows = true
YRatio += child.ratio
if cols {
item.WidthRatio /= 2
}
}
g.setHelper(child, item.WidthRatio, item.HeightRatio)
}
}
}
// Draw draws the grid to the buffer.
func (g *Grid) Draw(buf *Buffer) {
for _, item := range g.Items {
entry, _ := item.Entry.(Drawable)
xStart := int(float64(g.Dx())*item.XRatio) + g.Min.X
yStart := int(float64(g.Dy())*item.YRatio) + g.Min.Y
xEnd := int(float64(g.Dx())*(item.XRatio+item.WidthRatio)) + g.Min.X
yEnd := int(float64(g.Dy())*(item.YRatio+item.HeightRatio)) + g.Min.Y
if xEnd > g.Max.X {
xEnd = g.Max.X
}
if yEnd > g.Max.Y {
yEnd = g.Max.Y
}
entry.SetRect(xStart, yStart, xEnd, yEnd)
entry.Lock()
entry.Draw(buf)
entry.Unlock()
}
}