summaryrefslogtreecommitdiffstats
path: root/widgets/temp.go
blob: 7c0a358402c4a4a253a5ff81067fefd7804d0315 (plain)
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
package widgets

import (
	"fmt"
	"image"
	"sort"
	"time"

	ui "github.com/gizak/termui/v3"

	"github.com/xxxserxxx/gotop/utils"
)

type TempScale int

const (
	Celsius    TempScale = 0
	Fahrenheit           = 1
	Disabled             = 2
)

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
}

// TODO: state:deferred 156 Added temperatures for NVidia GPUs (azak-azkaran/master). Crashes on non-nvidia machines.
func NewTempWidget(tempScale TempScale) *TempWidget {
	self := &TempWidget{
		Block:          ui.NewBlock(),
		updateInterval: time.Second * 5,
		Data:           make(map[string]int),
		TempThreshold:  80,
		TempScale:      tempScale,
	}
	self.Title = " Temperatures "

	if tempScale == Fahrenheit {
		self.TempThreshold = utils.CelsiusToFahrenheit(self.TempThreshold)
	}

	self.update()

	go func() {
		for range time.NewTicker(self.updateInterval).C {
			self.Lock()
			self.update()
			self.Unlock()
		}
	}()

	return self
}

// Custom Draw method instead of inheriting from a generic Widget.
func (self *TempWidget) Draw(buf *ui.Buffer) {
	self.Block.Draw(buf)

	var keys []string
	for key := range self.Data {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	for y, key := range keys {
		if y+1 > self.Inner.Dy() {
			break
		}

		var fg ui.Color
		if self.Data[key] < self.TempThreshold {
			fg = self.TempLowColor
		} else {
			fg = self.TempHighColor
		}

		s := ui.TrimString(key, (self.Inner.Dx() - 4))
		buf.SetString(s,
			ui.Theme.Default,
			image.Pt(self.Inner.Min.X, self.Inner.Min.Y+y),
		)

		// TODO: state:merge #184 or #177 degree symbol (BartWillems/master, fleaz/master)
		switch self.TempScale {
		case Fahrenheit:
			buf.SetString(
				fmt.Sprintf("%3dF", self.Data[key]),
				ui.NewStyle(fg),
				image.Pt(self.Inner.Max.X-4, self.Inner.Min.Y+y),
			)
		case Celsius:
			buf.SetString(
				fmt.Sprintf("%3dC", self.Data[key]),
				ui.NewStyle(fg),
				image.Pt(self.Inner.Max.X-4, self.Inner.Min.Y+y),
			)
		}
	}
}