xmtop/widgets/temp.go

103 lines
1.9 KiB
Go
Raw Normal View History

2018-02-18 23:25:02 -08:00
package widgets
import (
"fmt"
2018-12-31 16:55:50 -08:00
"image"
2018-03-03 17:05:52 -08:00
"sort"
2018-02-18 23:25:02 -08:00
"time"
2019-03-07 23:15:41 -08:00
ui "github.com/gizak/termui/v3"
2019-02-28 16:29:52 -08:00
2020-02-13 16:26:28 -06:00
"github.com/xxxserxxx/gotop/utils"
2019-02-28 16:29:52 -08:00
)
type TempScale int
const (
2020-01-22 01:21:57 +08:00
Celsius TempScale = 0
2019-02-28 16:29:52 -08:00
Fahrenheit = 1
Disabled = 2
2018-02-18 23:25:02 -08:00
)
2019-02-28 16:29:52 -08:00
type TempWidget struct {
*ui.Block // inherits from Block instead of a premade Widget
updateInterval time.Duration
Data map[string]int
TempThreshold int
TempLowColor ui.Color
TempHighColor ui.Color
TempScale TempScale
2018-02-18 23:25:02 -08:00
}
func NewTempWidget(tempScale TempScale) *TempWidget {
2019-02-28 16:29:52 -08:00
self := &TempWidget{
Block: ui.NewBlock(),
updateInterval: time.Second * 5,
Data: make(map[string]int),
TempThreshold: 80,
TempScale: tempScale,
}
2018-12-31 16:55:50 -08:00
self.Title = " Temperatures "
2018-02-18 23:25:02 -08:00
2019-02-28 16:29:52 -08:00
if tempScale == Fahrenheit {
self.TempThreshold = utils.CelsiusToFahrenheit(self.TempThreshold)
}
2018-04-12 20:00:34 -07:00
self.update()
2018-02-18 23:25:02 -08:00
go func() {
2019-02-28 16:29:52 -08:00
for range time.NewTicker(self.updateInterval).C {
self.Lock()
2018-03-27 14:27:23 -07:00
self.update()
self.Unlock()
2018-02-18 23:25:02 -08:00
}
}()
2018-03-27 14:27:23 -07:00
return self
2018-02-18 23:25:02 -08:00
}
2019-02-28 16:29:52 -08:00
// Custom Draw method instead of inheriting from a generic Widget.
func (self *TempWidget) Draw(buf *ui.Buffer) {
2018-12-31 16:55:50 -08:00
self.Block.Draw(buf)
2018-03-03 17:05:52 -08:00
var keys []string
2018-05-10 20:32:23 -07:00
for key := range self.Data {
keys = append(keys, key)
2018-03-03 17:05:52 -08:00
}
sort.Strings(keys)
for y, key := range keys {
2018-12-31 16:55:50 -08:00
if y+1 > self.Inner.Dy() {
break
}
2019-02-28 16:29:52 -08:00
var fg ui.Color
if self.Data[key] < self.TempThreshold {
fg = self.TempLowColor
} else {
fg = self.TempHighColor
}
2018-12-31 16:55:50 -08:00
s := ui.TrimString(key, (self.Inner.Dx() - 4))
buf.SetString(s,
ui.Theme.Default,
2019-01-14 19:47:44 -08:00
image.Pt(self.Inner.Min.X, self.Inner.Min.Y+y),
2018-12-31 16:55:50 -08:00
)
2019-02-28 16:29:52 -08:00
switch self.TempScale {
case Fahrenheit:
2018-12-31 16:55:50 -08:00
buf.SetString(
fmt.Sprintf("%3dF", self.Data[key]),
ui.NewStyle(fg),
image.Pt(self.Inner.Max.X-4, self.Inner.Min.Y+y),
2018-12-31 16:55:50 -08:00
)
2020-01-22 01:21:57 +08:00
case Celsius:
2018-12-31 16:55:50 -08:00
buf.SetString(
fmt.Sprintf("%3dC", self.Data[key]),
ui.NewStyle(fg),
2019-01-14 19:47:44 -08:00
image.Pt(self.Inner.Max.X-4, self.Inner.Min.Y+y),
2018-12-31 16:55:50 -08:00
)
}
}
}