-
Notifications
You must be signed in to change notification settings - Fork 1
/
tui.go
296 lines (266 loc) · 9.38 KB
/
tui.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
package main
import (
"fmt"
"log/slog"
"strings"
"time"
"github.com/charmbracelet/bubbles/table"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/shirou/gopsutil/v4/cpu"
"github.com/shirou/gopsutil/v4/mem"
)
type model struct {
width int
height int
lastUpdate time.Time
processTable table.Model
tableStyle table.Styles
baseStyle lipgloss.Style
viewStyle lipgloss.Style
CpuUsage cpu.TimesStat
MemUsage mem.VirtualMemoryStat
}
type TickMsg time.Time
type Theme struct {
Primary lipgloss.AdaptiveColor
Secondary lipgloss.AdaptiveColor
Highlight lipgloss.AdaptiveColor
Border lipgloss.AdaptiveColor
Green lipgloss.AdaptiveColor
Red lipgloss.AdaptiveColor
}
var Color = Theme{
Primary: lipgloss.AdaptiveColor{Light: "#000000", Dark: "#FFFFFF"},
Secondary: lipgloss.AdaptiveColor{Light: "#969B86", Dark: "#696969"},
Highlight: lipgloss.AdaptiveColor{Light: "#8b2def", Dark: "#8b2def"},
Border: lipgloss.AdaptiveColor{Light: "#D9DCCF", Dark: "#383838"},
Green: lipgloss.AdaptiveColor{Light: "#00FF00", Dark: "#00FF00"},
Red: lipgloss.AdaptiveColor{Light: "#FF0000", Dark: "#FF0000"},
}
// Calls the tickEvery function to set up a command that sends a TickMsg every second.
// This command will be executed immediately when the program starts, initiating the periodic updates.
func (m model) Init() tea.Cmd {
return tickEvery()
}
func tickEvery() tea.Cmd {
// tea.Every function is a helper function from the Bubble Tea framework
// that schedules a command to run at regular intervals.
return tea.Every(time.Second,
// Callback function that takes the current time (t time.Time) as a parameter and returns a message (tea.Msg).
// This callback is invoked every second.
func(t time.Time) tea.Msg {
return TickMsg(t)
})
}
func (m model) View() string {
// Sets the width of the column to the width of the terminal (m.width) and adds padding of 1 unit on the top.
// Render is a method from the lipgloss package that applies the defined style and returns a function that can render styled content.
column := m.baseStyle.Width(m.width).Padding(1, 0, 0, 0).Render
// Set the content to match the terminal dimensions (m.width and m.height).
content := m.baseStyle.
Width(m.width).
Height(m.height).
Render(
// Vertically join multiple elements aligned to the left.
lipgloss.JoinVertical(lipgloss.Left,
column(m.viewHeader()),
column(m.viewProcess()),
),
)
return content
}
// Takes a tea.Msg as input and uses a type switch to handle different types of messages.
// Each case in the switch statement corresponds to a specific message type.
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
// message is sent when the window size changes
// save to reflect the new dimensions of the terminal window.
case tea.WindowSizeMsg:
m.height = msg.Height
m.width = msg.Width
// message is sent when a key is pressed.
case tea.KeyMsg:
switch msg.String() {
// Toggles the focus state of the process table
case "esc":
if m.processTable.Focused() {
m.tableStyle.Selected = m.baseStyle
m.processTable.SetStyles(m.tableStyle)
m.processTable.Blur()
} else {
m.tableStyle.Selected = m.tableStyle.Selected.Background(Color.Highlight)
m.processTable.SetStyles(m.tableStyle)
m.processTable.Focus()
}
// Moves the focus up in the process table if the table is focused.
case "up", "k":
if m.processTable.Focused() {
m.processTable.MoveUp(1)
}
// Moves the focus down in the process table if the table is focused.
case "down", "j":
if m.processTable.Focused() {
m.processTable.MoveDown(1)
}
// Quits the program by returning the tea.Quit command.
case "q", "ctrl+c":
return m, tea.Quit
}
// This custom message is sent periodically by the tickEvery function.
// The model's lastUpdate field is updated to the current time.
// Fetching CPU Stats, Memory Stats & Processes
// Returning Command: The tickEvery command is returned to ensure that the TickMsg continues to be sent periodically.
case TickMsg:
m.lastUpdate = time.Time(msg)
cpuStats, err := GetCPUStats()
if err != nil {
slog.Error("Could not get CPU info", "error", err)
} else {
m.CpuUsage = cpuStats
}
memStats, err := GetMEMStats()
if err != nil {
slog.Error("Could not get memory info", "error", err)
} else {
m.MemUsage = memStats
}
procs, err := GetProcesses(5)
if err != nil {
slog.Error("Could not get processes", "error", err)
} else {
rows := []table.Row{}
for _, p := range procs {
memString, memUnit := convertBytes(p.Memory)
rows = append(rows, table.Row{
fmt.Sprintf("%d", p.PID),
p.Name,
fmt.Sprintf("%.2f%%", p.CPUPercent),
fmt.Sprintf("%s %s", memString, memUnit),
p.Username,
p.RunningTime,
})
}
m.processTable.SetRows(rows)
}
return m, tickEvery()
}
// If the message type does not match any of the handled cases, the model is returned unchanged, and no new command is issued.
return m, nil
}
// Uses lipgloss.JoinVertical and lipgloss.JoinHorizontal to arrange the header content.
// It displays the last update time and various system statistics (CPU and memory usage) in a structured format.
func (m model) viewHeader() string {
// defines the style for list items, including borders, border color, height, and padding.
list := m.baseStyle.
Border(lipgloss.NormalBorder(), false, true, false, false).
BorderForeground(Color.Border).
Height(4).
Padding(0, 1)
// applies bold styling to the text.
listHeader := m.baseStyle.Bold(true).Render
// helper function that formats a key-value pair with an optional suffix. It aligns the value to the right and renders it with the specified style.
listItem := func(key string, value string, suffix ...string) string {
finalSuffix := ""
if len(suffix) > 0 {
finalSuffix = suffix[0]
}
listItemValue := m.baseStyle.Align(lipgloss.Right).Render(fmt.Sprintf("%s%s", value, finalSuffix))
listItemKey := func(key string) string {
return m.baseStyle.Render(key + ":")
}
return fmt.Sprintf("%s %s", listItemKey(key), listItemValue)
}
return m.viewStyle.Render(
lipgloss.JoinVertical(lipgloss.Top,
fmt.Sprintf("Last update: %d milliseconds ago\n", time.Now().Sub(m.lastUpdate).Milliseconds()),
lipgloss.JoinHorizontal(lipgloss.Top,
// Progress Bars
list.Render(
lipgloss.JoinVertical(lipgloss.Left,
listHeader("% Usage"),
listItem("CPU", fmt.Sprintf("%s %.1f", progressBar(100-m.CpuUsage.Idle, m.baseStyle), 100-m.CpuUsage.Idle), "%"),
listItem("MEM", fmt.Sprintf("%s %.1f", progressBar(m.MemUsage.UsedPercent, m.baseStyle), m.MemUsage.UsedPercent), "%"),
),
),
// CPU
list.Border(lipgloss.NormalBorder(), false).Render(
lipgloss.JoinVertical(lipgloss.Left,
listHeader("CPU"),
listItem("user", fmt.Sprintf("%.1f", m.CpuUsage.User), "%"),
listItem("sys", fmt.Sprintf("%.1f", m.CpuUsage.System), "%"),
listItem("idle", fmt.Sprintf("%.1f", m.CpuUsage.Idle), "%"),
),
),
list.Border(lipgloss.NormalBorder(), false).Render(
lipgloss.JoinVertical(lipgloss.Left,
listHeader(""),
listItem("nice", fmt.Sprintf("%.1f", m.CpuUsage.Nice), "%"),
listItem("iowait", fmt.Sprintf("%.1f", m.CpuUsage.Iowait), "%"),
listItem("irq", fmt.Sprintf("%.1f", m.CpuUsage.Irq), "%"),
),
),
list.Render(
lipgloss.JoinVertical(lipgloss.Left,
listHeader(""),
listItem("softirq", fmt.Sprintf("%.1f", m.CpuUsage.Softirq), "%"),
listItem("steal", fmt.Sprintf("%.1f", m.CpuUsage.Steal), "%"),
listItem("guest", fmt.Sprintf("%.1f", m.CpuUsage.Guest), "%"),
),
),
// MEM
list.Border(lipgloss.NormalBorder(), false).Render(
lipgloss.JoinVertical(lipgloss.Left,
listHeader("MEM"),
func() string {
value, unit := convertBytes(m.MemUsage.Total)
return listItem("total", value, unit)
}(),
func() string {
value, unit := convertBytes(m.MemUsage.Used)
return listItem("used", value, unit)
}(),
func() string {
value, unit := convertBytes(m.MemUsage.Available)
return listItem("free", value, unit)
}(),
),
),
list.Render(
lipgloss.JoinVertical(lipgloss.Left,
listHeader(""),
func() string {
value, unit := convertBytes(m.MemUsage.Active)
return listItem("active", value, unit)
}(),
func() string {
value, unit := convertBytes(m.MemUsage.Buffers)
return listItem("buffers", value, unit)
}(),
func() string {
value, unit := convertBytes(m.MemUsage.Cached)
return listItem("cached", value, unit)
}(),
),
),
),
),
)
}
func (m model) viewProcess() string {
return m.viewStyle.Render(m.processTable.View())
}
// creates a visual representation of a percentage as a progress bar.
func progressBar(percentage float64, baseStyle lipgloss.Style) string {
totalBars := 20
fillBars := int(percentage / 100 * float64(totalBars))
// renders the filled part of the progress bar with a green color.
filled := baseStyle.
Foreground(Color.Green).
Render(strings.Repeat("|", fillBars))
// renders the empty part of the progress bar with a secondary color.
empty := baseStyle.
Foreground(Color.Secondary).
Render(strings.Repeat("|", totalBars-fillBars))
return baseStyle.Render(fmt.Sprintf("%s%s%s%s", "[", filled, empty, "]"))
}