xmtop/src/widgets/temp.go

81 lines
1.5 KiB
Go
Raw Normal View History

2018-02-19 15:25:02 +08:00
package widgets
// Temp is too customized to inherit from a generic widget so we create a customized one here.
// Temp defines its own Buffer method directly.
2018-02-19 15:25:02 +08:00
import (
"fmt"
2018-03-04 09:05:52 +08:00
"sort"
2018-02-19 15:25:02 +08:00
"time"
2018-03-30 06:48:43 +08:00
ui "github.com/cjbassi/termui"
2018-02-19 15:25:02 +08:00
)
type Temp struct {
*ui.Block
interval time.Duration
Data map[string]int
Threshold int
TempLow ui.Color
TempHigh ui.Color
Fahrenheit bool
2018-02-19 15:25:02 +08:00
}
func NewTemp(fahrenheit bool) *Temp {
2018-03-28 05:27:23 +08:00
self := &Temp{
Block: ui.NewBlock(),
interval: time.Second * 5,
2018-03-04 09:05:52 +08:00
Data: make(map[string]int),
Threshold: 80, // temp at which color should change
}
2018-03-28 05:27:23 +08:00
self.Label = "Temperatures"
2018-02-19 15:25:02 +08:00
if fahrenheit {
self.Fahrenheit = true
self.Threshold = int(self.Threshold*9/5 + 32)
}
2018-04-13 11:00:34 +08:00
self.update()
2018-02-19 15:25:02 +08:00
go func() {
ticker := time.NewTicker(self.interval)
2018-02-19 15:25:02 +08:00
for range ticker.C {
2018-03-28 05:27:23 +08:00
self.update()
2018-02-19 15:25:02 +08:00
}
}()
2018-03-28 05:27:23 +08:00
return self
2018-02-19 15:25:02 +08:00
}
2018-05-11 11:32:23 +08:00
// Buffer implements ui.Bufferer interface and renders the widget.
2018-03-28 05:27:23 +08:00
func (self *Temp) Buffer() *ui.Buffer {
buf := self.Block.Buffer()
2018-03-04 09:05:52 +08:00
var keys []string
2018-05-11 11:32:23 +08:00
for key := range self.Data {
keys = append(keys, key)
2018-03-04 09:05:52 +08:00
}
sort.Strings(keys)
for y, key := range keys {
2018-03-28 05:27:23 +08:00
if y+1 > self.Y {
break
}
2018-03-28 05:27:23 +08:00
fg := self.TempLow
if self.Data[key] >= self.Threshold {
fg = self.TempHigh
}
2018-03-28 05:27:23 +08:00
s := ui.MaxString(key, (self.X - 4))
buf.SetString(1, y+1, s, self.Fg, self.Bg)
if self.Fahrenheit {
buf.SetString(self.X-3, y+1, fmt.Sprintf("%3dF", self.Data[key]), fg, self.Bg)
} else {
buf.SetString(self.X-3, y+1, fmt.Sprintf("%3dC", self.Data[key]), fg, self.Bg)
}
}
return buf
}