forked from jojomi/gonsole
-
Notifications
You must be signed in to change notification settings - Fork 4
/
layout.go
141 lines (120 loc) · 2.53 KB
/
layout.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
140
141
package gonsole
import (
"fmt"
"math"
"regexp"
"strconv"
)
type Box struct {
Left int
Top int
Width int
Height int
}
func (b Box) Right() int {
return b.Left + b.Width - 1
}
func (b Box) Bottom() int {
return b.Top + b.Height - 1
}
func (b Box) Absolute(bParent Box) Box {
return Box{
Left: bParent.Left + b.Left,
Top: bParent.Top + b.Top,
Width: b.Width,
Height: b.Height,
}
}
func (b Box) Plus(s Sides) Box {
return Box{
Left: b.Left - s.Left,
Top: b.Top - s.Top,
Width: b.Width + s.Left + s.Right,
Height: b.Height + s.Top + s.Bottom,
}
}
func (b Box) Minus(s Sides) Box {
return Box{
Left: b.Left + s.Left,
Top: b.Top + s.Top,
Width: b.Width - s.Left - s.Right,
Height: b.Height - s.Top - s.Bottom,
}
}
func (b Box) Position() Position {
return Position{
Left: strconv.Itoa(b.Left),
Top: strconv.Itoa(b.Top),
Width: strconv.Itoa(b.Width),
Height: strconv.Itoa(b.Height),
}
}
type Sides struct {
Top int
Right int
Bottom int
Left int
}
func (s Sides) Plus(s2 Sides) Sides {
return Sides{
Left: s.Left + s2.Left,
Top: s.Top + s2.Top,
Right: s.Right + s2.Right,
Bottom: s.Bottom + s2.Bottom,
}
}
func (s Sides) Minus(s2 Sides) Sides {
return Sides{
Left: s.Left - s2.Left,
Top: s.Top - s2.Top,
Right: s.Right - s2.Right,
Bottom: s.Bottom - s2.Bottom,
}
}
type Position struct {
Left string
Top string
Width string
Height string
}
func calcPosition(m int, p string) int {
re := regexp.MustCompile(`^(\d+%?)([+-]\d+)?$`)
values := re.FindStringSubmatch(p)
if len(values) < 2 {
panic(fmt.Sprintf("invalid position '%s'", p))
}
value := 0
if values[1][len(values[1])-1:] == "%" {
percent, err := strconv.Atoi(values[1][:len(values[1])-1])
if err != nil || percent > 100 || percent < 0 {
panic(fmt.Sprintf("invalid percent value in position '%s'", p))
}
value = int(math.Ceil(float64(m) * (float64(percent) / 100)))
} else {
v, err := strconv.Atoi(values[1])
if err != nil {
panic(fmt.Sprintf("invalid value in position '%s'", p))
}
value = v
}
if values[2] != "" {
offset, err := strconv.Atoi(values[2][1:])
if err != nil || offset < 0 {
panic(fmt.Sprintf("invalid offset value in position '%s'", p))
}
if values[2][0] == '+' {
value += offset
} else {
value -= offset
}
}
return value
}
func (p Position) Box(w, h int) Box {
return Box{
Left: calcPosition(w, p.Left),
Top: calcPosition(h, p.Top),
Width: calcPosition(w, p.Width),
Height: calcPosition(h, p.Height),
}
}