-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
345 lines (297 loc) · 8.32 KB
/
main.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"container/ring"
_ "embed"
"flag"
"fmt"
"math"
"os"
"os/exec"
"strings"
"time"
"github.com/veandco/go-sdl2/sdl"
"github.com/veandco/go-sdl2/ttf"
"golang.org/x/exp/maps"
)
var (
interval = 1 * time.Second
title = "netwatch"
windowWidth int32 = 180
windowHeight int32 = 100
windowMargin int32 = 5
panelHeight int32 = 45
targetSize int32 = 90
panelWidth = windowWidth - (windowMargin * 2)
fontName = "noto.ttf"
fontSize int32 = 11
fg = sdl.Color{0xFF, 0xFF, 0xFF, 0xFF}
bg = sdl.Color{0x64, 0x64, 0x64, 0xFF}
errColor = sdl.Color{0xFF, 0x64, 0x64, 0xFF}
plotColors = []sdl.Color{
{0x00, 0xFF, 0x00, 0xFF},
{0x00, 0x00, 0xFF, 0xFF},
{0xFF, 0x7F, 0x00, 0xFF},
}
//go:embed fonts/noto.ttf
fontData []byte
)
func errbox(format string, args ...interface{}) {
sdl.Init(sdl.INIT_VIDEO)
window, _ := sdl.CreateWindow(title, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 100, 100, sdl.WINDOW_HIDDEN)
sdl.ShowSimpleMessageBox(10, "Error", fmt.Sprintf(format, args...), window)
window.Destroy()
os.Exit(1)
}
func drawText(renderer *sdl.Renderer, font *ttf.Font, color sdl.Color, x int32, y int32, text string) (int32, int32) {
var surface *sdl.Surface
var texture *sdl.Texture
surface, _ = font.RenderUTF8Blended(text, color)
texture, _ = renderer.CreateTextureFromSurface(surface)
_, _, w, h, _ := texture.Query()
renderer.Copy(texture, nil, &sdl.Rect{x, y, w, h})
surface.Free()
texture.Destroy()
return w, h
}
func plotRing(r *ring.Ring, name string, tgtnum int32, renderer *sdl.Renderer, font *ttf.Font, fg sdl.Color) {
var minv, maxv, avg, lst, tot float64 = 10000.0, 0, 0, 0, 0
var i, h int32 = 0, 0
var txt string
var vs int32 = (tgtnum * targetSize) + 1
var data, prev []float64
renderer.SetDrawColor(fg.R, fg.G, fg.B, fg.A)
renderer.DrawRect(&sdl.Rect{windowMargin, vs + windowMargin + 15, windowWidth - (windowMargin * 2), panelHeight})
drawText(renderer, font, fg, windowMargin, vs+windowMargin-3, name)
r.Do(func(x interface{}) {
data, _ = x.([]float64)
for _, v := range data {
lst = v
if v > maxv {
maxv = v
}
if v < minv {
minv = v
}
if v > 0 {
tot += v
i++
}
}
})
avg = tot / float64(i)
i = 0
vh := func(v float64) int32 {
return int32((v/maxv)*float64(panelHeight-2)) - 1
}
r.Do(func(x interface{}) {
prev = data
data, _ = x.([]float64)
for j, v := range data {
if math.IsNaN(v) {
h = panelHeight - 1
renderer.SetDrawColor(errColor.R, errColor.G, errColor.B, errColor.A)
} else if v > 0 {
h = vh(v)
if len(plotColors) > j {
renderer.SetDrawColor(plotColors[j].R, plotColors[j].G, plotColors[j].B, plotColors[j].A)
}
} else {
h = 2
renderer.SetDrawColor(0x00, 0xFF, 0x00, 0xFF)
}
x, y1, y2 := windowMargin+i, vs+windowMargin+panelHeight+13, vs+windowMargin+panelHeight+13
if j > 0 && len(prev) > j {
y1 -= min(vh(v), vh(prev[j]))
y2 -= max(vh(v), vh(prev[j]))
} else {
y1 -= h
}
renderer.DrawLine(x, y1, x, y2)
}
i++
})
txt = fmt.Sprintf("L=%.1f M=%.1f A=%.1f", lst, maxv, avg)
drawText(renderer, font, fg, windowMargin, vs+windowMargin+panelHeight+15, txt)
}
type panel struct {
typ, target string
channel chan []float64
ring *ring.Ring
color sdl.Color
}
func parsePanels(args []string) ([]*panel, error) {
if len(args) < 1 {
return nil, fmt.Errorf("No args specified")
} else if len(args) > int(^byte(0)) {
return nil, fmt.Errorf("Too many targets specified")
}
a := make([]*panel, len(args))
for i, arg := range args {
tokens := strings.Split(arg, ":")
if len(tokens) != 2 {
return nil, fmt.Errorf("Could not parse panel: %q", arg)
}
p, ok := probes[tokens[0]]
if !ok {
return nil, fmt.Errorf("Unsupported panel type: %q", tokens[0])
}
c := make(chan []float64)
err := p(tokens[1], c)
if err != nil {
return nil, fmt.Errorf("Error initializing %s: %w", tokens[0], err)
}
a[i] = &panel{
typ: tokens[0],
target: tokens[1],
channel: c,
ring: ring.New(int(panelWidth - 2)),
color: fg,
}
}
return a, nil
}
func update(panels []*panel) {
for _, panel := range panels {
select {
case v := <-panel.channel:
panel.ring.Value = v
panel.ring = panel.ring.Next()
panel.color = fg
default:
panel.color = errColor
}
}
}
func main() {
// Parse CLI args
var foreground bool
var fullScreen bool
var bgColor string
var fgColor string
var intervalSeconds int
flag.Usage = func() {
errbox("Usage:\n%s type:target [type:target [...]]\n\nPanel types are:\n%s",
os.Args[0], strings.Join(maps.Keys(probes), ", "))
}
flag.BoolVar(&fullScreen, "fs", false, "Run in full screen mode")
flag.StringVar(&bgColor, "bg", "", "Background Color in Hex RRGGBB")
flag.StringVar(&fgColor, "fg", "", "Border and Text Color in Hex RRGGBB")
flag.BoolVar(&foreground, "f", false, "Run in foreground, do not detach from terminal")
flag.IntVar(&intervalSeconds, "t", 5, "Time between updates in seconds")
flag.Parse()
interval = time.Duration(intervalSeconds) * time.Second
if !foreground {
cwd, err := os.Getwd()
if err != nil {
errbox("Getcwd error: %s\n", err)
}
args := []string{"-f"}
args = append(args, os.Args[1:]...)
cmd := exec.Command(os.Args[0], args...)
cmd.Dir = cwd
if err := cmd.Start(); err != nil {
errbox("Startup error: %s\n", err)
}
cmd.Process.Release()
os.Exit(0)
}
panels, err := parsePanels(flag.Args())
if err != nil {
errbox(err.Error())
}
if len(bgColor) == 6 {
n, err := fmt.Sscanf(bgColor, "%2x%2x%2x", &bg.R, &bg.G, &bg.B)
if err != nil || n != 3 {
errbox("Unable to parse bg background color")
}
}
if len(fgColor) == 6 {
n, err := fmt.Sscanf(fgColor, "%2x%2x%2x", &fg.R, &fg.G, &fg.B)
if err != nil || n != 3 {
errbox("Unable to parse fg foreground color")
}
}
// SDL Init
if err := sdl.Init(sdl.INIT_VIDEO); err != nil {
errbox("Failed to initialize SDL:\n %s\n", err)
}
if err := ttf.Init(); err != nil {
errbox("Failed to initialize TTF:\n %s\n", err)
}
window, err := sdl.CreateWindow(title, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, windowWidth, int32(len(panels))*targetSize, sdl.WINDOW_OPENGL)
if err != nil {
errbox("Failed to create window:\n %s\n", err)
}
defer window.Destroy()
if fullScreen {
window.SetFullscreen(sdl.WINDOW_FULLSCREEN_DESKTOP)
}
windowWidth, windowHeight = window.GetSize()
panelWidth = windowWidth - (windowMargin * 2)
renderer, err := sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED)
if err != nil {
errbox("Failed to create renderer:\n %s\n", err)
}
defer renderer.Destroy()
// Font init
tmp, err := os.CreateTemp(os.TempDir(), fontName)
if err != nil {
errbox("Unable to create temp file:\n%s\n", err)
}
defer os.Remove(tmp.Name())
if _, err := tmp.Write(fontData); err != nil {
errbox("Unable to write temp font:\n%s\n", err)
}
tmp.Close()
font, err := ttf.OpenFont(tmp.Name(), int(fontSize))
if err != nil {
errbox("Failed to open font:\n %s\n", err)
}
// Update loop. Rendering is delegated to the main thread, as required on
// some platforms.
render := make(chan interface{})
go func() {
update(panels)
render <- nil
for range time.Tick(interval) {
update(panels)
render <- nil
}
}()
// Event loop
for {
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
switch event.(type) {
case *sdl.QuitEvent:
os.Exit(0)
}
}
select {
case <-render:
renderer.SetDrawColor(bg.R, bg.G, bg.B, 0xFF)
renderer.Clear()
for i, panel := range panels {
plotRing(panel.ring, fmt.Sprintf("%s:%s", panel.typ, panel.target),
int32(i), renderer, font, panel.color)
}
renderer.Present()
default:
}
sdl.Delay(50)
}
}