-
Notifications
You must be signed in to change notification settings - Fork 33
/
main.go
1498 lines (1389 loc) · 43 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2024-2025 Carsen Klock under MIT License
// mactop is a simple terminal based Apple Silicon power monitor written in Go Lang! github.com/context-labs/mactop
package main
/*
#cgo LDFLAGS: -framework CoreFoundation -framework IOKit
#include <mach/mach_host.h>
#include <mach/processor_info.h>
#include <mach/mach_init.h>
extern kern_return_t vm_deallocate(vm_map_t target_task, vm_address_t address, vm_size_t size);
*/
import "C"
import (
"bufio"
"bytes"
"fmt"
"image"
"log"
"math"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"time"
"unsafe"
ui "github.com/gizak/termui/v3"
w "github.com/gizak/termui/v3/widgets"
"github.com/shirou/gopsutil/mem"
"howett.net/plist"
)
var (
version = "v0.2.2"
cpuGauge, gpuGauge, memoryGauge *w.Gauge
modelText, PowerChart, NetworkInfo, helpText *w.Paragraph
grid *ui.Grid
processList *w.List
sparkline, gpuSparkline *w.Sparkline
sparklineGroup, gpuSparklineGroup *w.SparklineGroup
cpuCoreWidget *CPUCoreWidget
selectedProcess int
powerValues = make([]float64, 35)
lastUpdateTime time.Time
stderrLogger = log.New(os.Stderr, "", 0)
currentGridLayout = "default"
showHelp, partyMode = false, false
updateInterval = 1000
done = make(chan struct{})
currentColorIndex = 0
colorOptions = []ui.Color{ui.ColorWhite, ui.ColorGreen, ui.ColorBlue, ui.ColorCyan, ui.ColorMagenta, ui.ColorYellow, ui.ColorRed}
partyTicker *time.Ticker
lastCPUTimes []CPUUsage
firstRun = true
processHistory = make(map[int]*ProcessMetrics)
lastProcessUpdateTime = time.Now()
currentSort = "CPU" // Default sort by CPU
sortReverse = false // Toggle for reverse sorting
columns = []string{"PID", "USER", "VIRT", "RES", "CPU", "MEM", "TIME", "CMD"}
selectedColumn = 4 // Default to CPU (0-based index)
minPower = math.MaxFloat64
maxPowerSeen = 0.1
powerHistory = make([]float64, 100)
maxPower = 0.0 // Track maximum power for better scaling
gpuValues = make([]float64, 65)
)
type CPUUsage struct {
User float64
System float64
Idle float64
Nice float64
}
type CPUMetrics struct {
EClusterActive, EClusterFreqMHz, PClusterActive, PClusterFreqMHz int
ECores, PCores []int
CoreMetrics map[string]int
CPUW, GPUW, PackageW float64
CoreUsages []float64
Throttled bool
}
type NetDiskMetrics struct {
OutPacketsPerSec, OutBytesPerSec, InPacketsPerSec, InBytesPerSec, ReadOpsPerSec, WriteOpsPerSec, ReadKBytesPerSec, WriteKBytesPerSec float64
}
type GPUMetrics struct {
FreqMHz, Active int
}
type ProcessMetrics struct {
PID int
CPU, LastTime, Memory float64
VSZ, RSS int64
User, TTY, State, Started, Time, Command string
LastUpdated time.Time
}
type MemoryMetrics struct {
Total, Used, Available, SwapTotal, SwapUsed uint64
}
type EventThrottler struct {
timer *time.Timer
gracePeriod time.Duration
C chan struct{}
}
type CPUCoreWidget struct {
*ui.Block
cores []float64
labels []string
eCoreCount, pCoreCount int
modelName string
}
func NewEventThrottler(gracePeriod time.Duration) *EventThrottler {
return &EventThrottler{
timer: nil,
gracePeriod: gracePeriod,
C: make(chan struct{}, 1),
}
}
func NewCPUMetrics() CPUMetrics {
return CPUMetrics{
CoreMetrics: make(map[string]int),
ECores: make([]int, 0),
PCores: make([]int, 0),
}
}
func (e *EventThrottler) Notify() {
if e.timer != nil {
return
}
e.timer = time.AfterFunc(e.gracePeriod, func() {
e.timer = nil
select {
case e.C <- struct{}{}:
default:
}
})
}
func GetCPUPercentages() ([]float64, error) {
currentTimes, err := GetCPUUsage()
if err != nil {
return nil, err
}
if firstRun {
lastCPUTimes = currentTimes
firstRun = false
return make([]float64, len(currentTimes)), nil
}
percentages := make([]float64, len(currentTimes))
for i := range currentTimes {
totalDelta := (currentTimes[i].User - lastCPUTimes[i].User) +
(currentTimes[i].System - lastCPUTimes[i].System) +
(currentTimes[i].Idle - lastCPUTimes[i].Idle) +
(currentTimes[i].Nice - lastCPUTimes[i].Nice)
activeDelta := (currentTimes[i].User - lastCPUTimes[i].User) +
(currentTimes[i].System - lastCPUTimes[i].System) +
(currentTimes[i].Nice - lastCPUTimes[i].Nice)
if totalDelta > 0 {
percentages[i] = (activeDelta / totalDelta) * 100.0
}
if percentages[i] < 0 {
percentages[i] = 0
} else if percentages[i] > 100 {
percentages[i] = 100
}
}
lastCPUTimes = currentTimes
return percentages, nil
}
func GetCPUUsage() ([]CPUUsage, error) {
var numCPUs C.natural_t
var cpuLoad *C.processor_cpu_load_info_data_t
var cpuMsgCount C.mach_msg_type_number_t
host := C.mach_host_self()
kernReturn := C.host_processor_info(
host,
C.PROCESSOR_CPU_LOAD_INFO,
&numCPUs,
(*C.processor_info_array_t)(unsafe.Pointer(&cpuLoad)),
&cpuMsgCount,
)
if kernReturn != C.KERN_SUCCESS {
return nil, fmt.Errorf("error getting CPU info: %d", kernReturn)
}
defer C.vm_deallocate(
C.mach_task_self_,
(C.vm_address_t)(uintptr(unsafe.Pointer(cpuLoad))),
C.vm_size_t(cpuMsgCount)*C.sizeof_processor_cpu_load_info_data_t,
)
cpuLoadInfo := (*[1 << 30]C.processor_cpu_load_info_data_t)(unsafe.Pointer(cpuLoad))[:numCPUs:numCPUs]
cpuUsage := make([]CPUUsage, numCPUs)
for i := 0; i < int(numCPUs); i++ {
cpuUsage[i] = CPUUsage{
User: float64(cpuLoadInfo[i].cpu_ticks[C.CPU_STATE_USER]),
System: float64(cpuLoadInfo[i].cpu_ticks[C.CPU_STATE_SYSTEM]),
Idle: float64(cpuLoadInfo[i].cpu_ticks[C.CPU_STATE_IDLE]),
Nice: float64(cpuLoadInfo[i].cpu_ticks[C.CPU_STATE_NICE]),
}
}
return cpuUsage, nil
}
func NewCPUCoreWidget(modelInfo map[string]interface{}) *CPUCoreWidget {
eCoreCount, _ := modelInfo["e_core_count"].(int)
pCoreCount, _ := modelInfo["p_core_count"].(int)
modelName, _ := modelInfo["name"].(string)
totalCores := eCoreCount + pCoreCount
labels := make([]string, totalCores)
for i := 0; i < eCoreCount; i++ {
labels[i] = fmt.Sprintf("E%d", i)
}
for i := 0; i < pCoreCount; i++ {
labels[i+eCoreCount] = fmt.Sprintf("P%d", i)
}
return &CPUCoreWidget{
Block: ui.NewBlock(),
cores: make([]float64, totalCores),
labels: labels,
eCoreCount: eCoreCount,
pCoreCount: pCoreCount,
modelName: modelName,
}
}
func (w *CPUCoreWidget) UpdateUsage(usage []float64) {
w.cores = make([]float64, len(usage))
copy(w.cores, usage)
}
func (w *CPUCoreWidget) Draw(buf *ui.Buffer) {
w.Block.Draw(buf)
if len(w.cores) == 0 {
return
}
themeColor := w.BorderStyle.Fg
totalCores := len(w.cores)
cols := 4 // default for <= 16 cores
if totalCores > 16 {
cols = 8 // switch to 8 columns for > 16 cores
}
availableWidth := w.Inner.Dx()
availableHeight := w.Inner.Dy()
minColWidth := 20 // minimum width needed for a readable core display
if (availableWidth / cols) < minColWidth {
cols = max(1, availableWidth/minColWidth)
}
rows := (totalCores + cols - 1) / cols
if rows > availableHeight {
rows = availableHeight
cols = (totalCores + rows - 1) / rows // Recalculate columns
}
barWidth := availableWidth / cols
labelWidth := 2 // Width for core labels
for i := 0; i < totalCores; i++ {
col := i % cols
row := i / cols
actualIndex := col*rows + row
if actualIndex >= totalCores || row >= rows {
continue
}
x := w.Inner.Min.X + (col * barWidth)
y := w.Inner.Min.Y + row
if y >= w.Inner.Max.Y {
continue
}
usage := w.cores[actualIndex]
label := fmt.Sprintf("%d", actualIndex)
buf.SetString(label, ui.NewStyle(themeColor), image.Pt(x, y))
availWidth := barWidth - labelWidth - 2 // -2 for brackets
if x+labelWidth+availWidth > w.Inner.Max.X {
availWidth = w.Inner.Max.X - x - labelWidth
}
if availWidth < 9 {
continue
}
usedWidth := int((usage / 100.0) * float64(availWidth-7))
buf.SetString("[", ui.NewStyle(ui.ColorWhite),
image.Pt(x+labelWidth, y))
for bx := 0; bx < availWidth-7; bx++ {
char := " "
var color ui.Color
if bx < usedWidth {
char = "❚"
switch {
case usage >= 60:
color = ui.ColorRed
case usage >= 40:
color = ui.ColorYellow
case usage >= 30:
color = ui.ColorCyan
default:
color = themeColor
}
} else {
color = themeColor
}
buf.SetString(char, ui.NewStyle(color),
image.Pt(x+labelWidth+1+bx, y))
}
percentage := fmt.Sprintf("%5.1f%%", usage)
buf.SetString(percentage, ui.NewStyle(245),
image.Pt(x+labelWidth+availWidth-7, y))
buf.SetString("]", ui.NewStyle(ui.ColorWhite),
image.Pt(x+labelWidth+availWidth-1, y))
}
}
func setupUI() {
appleSiliconModel := getSOCInfo()
modelText, helpText = w.NewParagraph(), w.NewParagraph()
modelText.Title = "Apple Silicon"
helpText.Title = "mactop help menu"
modelName, ok := appleSiliconModel["name"].(string)
if !ok {
modelName = "Unknown Model"
}
eCoreCount, ok := appleSiliconModel["e_core_count"].(int)
if !ok {
eCoreCount = 0 // Default or error value
}
pCoreCount, ok := appleSiliconModel["p_core_count"].(int)
if !ok {
pCoreCount = 0
}
gpuCoreCount, ok := appleSiliconModel["gpu_core_count"].(string)
if !ok {
gpuCoreCount = "?"
}
modelText.Text = fmt.Sprintf("%s\nTotal Cores: %d\nE-Cores: %d\nP-Cores: %d\nGPU Cores: %s",
modelName,
eCoreCount+pCoreCount,
eCoreCount,
pCoreCount,
gpuCoreCount,
)
helpText.Text = "mactop is open source monitoring tool for Apple Silicon authored by Carsen Klock in Go Lang!\n\nRepo: github.com/context-labs/mactop\n\nControls:\n- r: Refresh the UI data manually\n- c: Cycle through UI color themes\n- p: Toggle party mode (color cycling)\n- l: Toggle the main display's layout\n- h or ?: Toggle this help menu\n- q or <C-c>: Quit the application\n\nStart Flags:\n--help, -h: Show this help menu\n--version, -v: Show the version of mactop\n--interval, -i: Set the powermetrics update interval in milliseconds. Default is 1000.\n--color, -c: Set the UI color. Default is none. Options are 'green', 'red', 'blue', 'cyan', 'magenta', 'yellow', and 'white'.\n\nVersion: " + version
stderrLogger.Printf("Model: %s\nE-Core Count: %d\nP-Core Count: %d\nGPU Core Count: %s", modelName, eCoreCount, pCoreCount, gpuCoreCount)
processList = w.NewList()
processList.Title = "Process List"
processList.TextStyle = ui.NewStyle(ui.ColorGreen)
processList.WrapText = false
processList.SelectedRowStyle = ui.NewStyle(ui.ColorBlack, ui.ColorGreen)
processList.Rows = []string{}
processList.SelectedRow = 0
gauges := []*w.Gauge{
w.NewGauge(), w.NewGauge(), w.NewGauge(),
}
titles := []string{"E-CPU Usage", "P-CPU Usage", "GPU Usage", "Memory Usage"}
colors := []ui.Color{ui.ColorGreen, ui.ColorYellow, ui.ColorMagenta, ui.ColorBlue, ui.ColorCyan}
for i, gauge := range gauges {
gauge.Percent = 0
gauge.Title = titles[i]
gauge.BarColor = colors[i]
}
cpuGauge, gpuGauge, memoryGauge = gauges[0], gauges[1], gauges[2]
PowerChart, NetworkInfo = w.NewParagraph(), w.NewParagraph()
PowerChart.Title, NetworkInfo.Title = "Power Usage", "Network & Disk Info"
termWidth, _ := ui.TerminalDimensions()
numPoints := (termWidth / 2) / 2
powerValues = make([]float64, numPoints)
gpuValues = make([]float64, numPoints)
sparkline = w.NewSparkline()
sparkline.LineColor = ui.ColorGreen
sparkline.MaxHeight = 10
sparkline.Data = powerValues
sparklineGroup = w.NewSparklineGroup(sparkline)
gpuSparkline = w.NewSparkline()
gpuSparkline.LineColor = ui.ColorGreen
gpuSparkline.MaxHeight = 10
gpuSparkline.Data = gpuValues
gpuSparklineGroup = w.NewSparklineGroup(gpuSparkline)
gpuSparklineGroup.Title = "GPU Usage History"
updateProcessList()
cpuCoreWidget = NewCPUCoreWidget(appleSiliconModel)
eCoreCount = appleSiliconModel["e_core_count"].(int)
pCoreCount = appleSiliconModel["p_core_count"].(int)
cpuCoreWidget.Title = fmt.Sprintf("mactop - %d Cores (%dE/%dP)",
eCoreCount+pCoreCount,
eCoreCount,
pCoreCount,
)
cpuGauge.Title = fmt.Sprintf("mactop - %d Cores (%dE/%dP)",
eCoreCount+pCoreCount,
eCoreCount,
pCoreCount,
)
}
func setupGrid() {
grid = ui.NewGrid()
grid.Set(
ui.NewRow(1.0/4,
ui.NewCol(1.0, cpuGauge),
// ui.NewCol(1.0/2, gpuSparklineGroup),
),
ui.NewRow(2.0/4,
ui.NewCol(1.0/2,
ui.NewRow(1.0/2, gpuGauge),
ui.NewRow(1.0/2,
ui.NewCol(1.0/2, PowerChart),
ui.NewCol(1.0/2, sparklineGroup),
),
),
ui.NewCol(1.0/2,
ui.NewRow(1.0/2, memoryGauge),
ui.NewRow(1.0/2,
ui.NewCol(1.0/3, modelText),
ui.NewCol(2.0/3, NetworkInfo),
),
),
),
ui.NewRow(1.0/4,
ui.NewCol(1.0, processList),
),
)
}
func switchGridLayout() {
if currentGridLayout == "default" {
newGrid := ui.NewGrid()
newGrid.Set(
ui.NewRow(1.0/2, // This row now takes half the height of the grid
ui.NewCol(1.0/2, cpuCoreWidget), ui.NewCol(1.0/2, ui.NewRow(1.0/2, gpuGauge), ui.NewCol(1.0, ui.NewRow(1.0, memoryGauge))), // ui.NewCol(1.0/2, ui.NewRow(1.0, ProcessInfo)), // ProcessInfo spans this entire column
),
ui.NewRow(1.0/4,
ui.NewCol(1.0/6, modelText), ui.NewCol(1.0/3, NetworkInfo), ui.NewCol(1.0/4, PowerChart), ui.NewCol(1.0/4, sparklineGroup),
),
ui.NewRow(1.0/4,
ui.NewCol(1.0, processList),
),
)
termWidth, termHeight := ui.TerminalDimensions()
newGrid.SetRect(0, 0, termWidth, termHeight)
grid = newGrid
currentGridLayout = "alternative"
} else {
newGrid := ui.NewGrid()
newGrid.Set(
ui.NewRow(1.0/4,
ui.NewCol(1.0, cpuGauge),
),
ui.NewRow(2.0/4,
ui.NewCol(1.0/2,
ui.NewRow(1.0/2, gpuGauge),
ui.NewRow(1.0/2,
ui.NewCol(1.0/2, PowerChart),
ui.NewCol(1.0/2, sparklineGroup),
),
),
ui.NewCol(1.0/2,
ui.NewRow(1.0/2, memoryGauge),
ui.NewRow(1.0/2,
ui.NewCol(1.0/3, modelText),
ui.NewCol(2.0/3, NetworkInfo),
),
),
),
ui.NewRow(1.0/4,
ui.NewCol(1.0, processList),
),
)
termWidth, termHeight := ui.TerminalDimensions()
newGrid.SetRect(0, 0, termWidth, termHeight)
grid = newGrid
currentGridLayout = "default"
}
}
func toggleHelpMenu() {
showHelp = !showHelp
if showHelp {
newGrid := ui.NewGrid()
newGrid.Set(
ui.NewRow(1.0,
ui.NewCol(1.0, helpText),
),
)
termWidth, termHeight := ui.TerminalDimensions()
helpTextGridWidth := termWidth
helpTextGridHeight := termHeight
x := (termWidth - helpTextGridWidth) / 2
y := (termHeight - helpTextGridHeight) / 2
newGrid.SetRect(x, y, x+helpTextGridWidth, y+helpTextGridHeight)
grid = newGrid
} else {
currentGridLayout = map[bool]string{
true: "alternative",
false: "default",
}[currentGridLayout == "default"]
switchGridLayout()
}
ui.Clear()
ui.Render(grid)
}
func togglePartyMode() {
partyMode = !partyMode
if partyMode {
partyTicker = time.NewTicker(time.Duration(updateInterval/2) * time.Millisecond)
go func() {
for range partyTicker.C {
if !partyMode {
partyTicker.Stop()
return
}
cycleColors()
ui.Clear()
ui.Render(grid)
}
}()
} else if partyTicker != nil {
partyTicker.Stop()
}
}
func StderrToLogfile(logfile *os.File) {
syscall.Dup2(int(logfile.Fd()), 2)
}
func parseTimeString(timeStr string) float64 {
var hours, minutes int
var seconds float64
if strings.Contains(timeStr, "h") {
parts := strings.Split(timeStr, "h")
fmt.Sscanf(parts[0], "%d", &hours)
fmt.Sscanf(parts[1], "%d:%f", &minutes, &seconds)
} else {
fmt.Sscanf(timeStr, "%d:%f", &minutes, &seconds)
}
return float64(hours*3600) + float64(minutes*60) + seconds
}
func formatTime(seconds float64) string {
hours := int(seconds) / 3600
minutes := (int(seconds) / 60) % 60
secs := int(seconds) % 60
centisecs := int((seconds - float64(int(seconds))) * 100)
if hours > 0 {
return fmt.Sprintf("%dh%02d:%02d", hours, minutes, secs)
}
return fmt.Sprintf("%02d:%02d.%02d", minutes, secs, centisecs)
}
func formatMemorySize(bytes int64) string {
const (
KB = 1024
MB = KB * 1024
GB = MB * 1024
)
switch {
case bytes >= GB:
return fmt.Sprintf("%.1fG", float64(bytes)/float64(GB))
case bytes >= MB:
return fmt.Sprintf("%dM", bytes/MB)
case bytes >= KB:
return fmt.Sprintf("%dK", bytes/KB)
default:
return fmt.Sprintf("%dB", bytes)
}
}
func formatResMemorySize(bytes int64) string {
const (
KB = 1024
MB = KB * 1024
GB = MB * 1024
)
if bytes < MB { // If value seems too small, assume it's in KB
bytes *= KB
}
switch {
case bytes >= GB:
return fmt.Sprintf("%.1fG", float64(bytes)/float64(GB))
case bytes >= MB:
return fmt.Sprintf("%dM", bytes/MB)
case bytes >= KB:
return fmt.Sprintf("%dK", bytes/KB)
default:
return fmt.Sprintf("%dB", bytes)
}
}
func truncateWithEllipsis(s string, maxLen int) string {
if maxLen <= 3 {
return "..."
}
if len(s) <= maxLen {
return s
}
return s[:maxLen-3] + "..."
}
func updateProcessList() {
processes := getProcessList()
themeColor := processList.TextStyle.Fg
themeColorStr := "white" // Default color in case theme color isn't recognized
switch themeColor {
case ui.ColorRed:
themeColorStr = "red"
case ui.ColorGreen:
themeColorStr = "green"
case ui.ColorYellow:
themeColorStr = "yellow"
case ui.ColorBlue:
themeColorStr = "blue"
case ui.ColorMagenta:
themeColorStr = "magenta"
case ui.ColorCyan:
themeColorStr = "cyan"
case ui.ColorWhite:
themeColorStr = "white"
}
termWidth, _ := 200, 200 // Fixed for calling repeatedly
minWidth := 40 // Set a minimum width to prevent crashes
availableWidth := max(termWidth-2, minWidth)
maxWidths := map[string]int{
"PID": 5, // Minimum for PID
"USER": 12, // Fixed maximum width for USER
"VIRT": 6, // For memory format
"RES": 6, // For memory format
"CPU": 6, // For "XX.X%"
"MEM": 5, // For "X.X%"
"TIME": 8, // For time format
"CMD": 13, // Minimum for command
}
usedWidth := 0
for col, width := range maxWidths {
if col != "CMD" {
usedWidth += width + 1 // +1 for separator
}
}
maxWidths["CMD"] = availableWidth - usedWidth
header := ""
for i, col := range columns {
width := maxWidths[col]
format := ""
switch col {
case "PID":
format = fmt.Sprintf("%%%ds", width) // Right-align
case "USER":
format = fmt.Sprintf("%%-%ds", width) // Left-align
case "VIRT", "RES":
format = fmt.Sprintf("%%%ds", width) // Right-align
case "CPU", "MEM":
format = fmt.Sprintf("%%%ds", width) // Right-align
case "TIME":
format = fmt.Sprintf("%%%ds", width) // Right-align
case "CMD":
format = fmt.Sprintf("%%-%ds", width) // Left-align
}
colText := fmt.Sprintf(format, col)
if i == selectedColumn {
if sortReverse {
header += fmt.Sprintf("[%s↑](fg:black,bg:%s)", colText, themeColorStr)
} else {
header += fmt.Sprintf("[%s↓](fg:black,bg:%s)", colText, themeColorStr)
}
} else {
header += fmt.Sprintf("[%s](fg:%s)", colText, themeColorStr)
}
if i < len(columns)-1 {
header += "|"
}
}
sort.Slice(processes, func(i, j int) bool {
var result bool
switch columns[selectedColumn] {
case "PID":
result = processes[i].PID < processes[j].PID
case "USER":
result = strings.ToLower(processes[i].User) < strings.ToLower(processes[j].User)
case "VIRT":
result = processes[i].VSZ > processes[j].VSZ
case "RES":
result = processes[i].RSS > processes[j].RSS
case "CPU":
result = processes[i].CPU > processes[j].CPU
case "MEM":
result = processes[i].Memory > processes[j].Memory
case "TIME":
iTime := parseTimeString(processes[i].Time)
jTime := parseTimeString(processes[j].Time)
result = iTime > jTime
case "CMD":
result = strings.ToLower(processes[i].Command) < strings.ToLower(processes[j].Command)
default:
result = processes[i].CPU > processes[j].CPU
}
if sortReverse {
return !result
}
return result
})
items := make([]string, len(processes)+1) // +1 for header
items[0] = header
for i, p := range processes {
seconds := parseTimeString(p.Time)
timeStr := formatTime(seconds)
virtStr := formatMemorySize(p.VSZ)
resStr := formatResMemorySize(p.RSS)
username := truncateWithEllipsis(p.User, maxWidths["USER"])
items[i+1] = fmt.Sprintf("%*d %-*s %*s %*s %*.1f%% %*.1f%% %*s %-s",
maxWidths["PID"], p.PID,
maxWidths["USER"], username,
maxWidths["VIRT"], virtStr,
maxWidths["RES"], resStr,
maxWidths["CPU"]-1, p.CPU, // -1 for % symbol
maxWidths["MEM"]-1, p.Memory, // -1 for % symbol
maxWidths["TIME"], timeStr,
truncateWithEllipsis(p.Command, maxWidths["CMD"]),
)
}
processList.Title = "Process List (↑/↓ scroll, ←/→ select column, Enter/Space to sort)"
processList.Rows = items
}
func handleProcessListEvents(e ui.Event) {
switch e.ID {
case "<Up>":
if processList.SelectedRow > 0 {
processList.SelectedRow--
}
case "<Down>":
if processList.SelectedRow < len(processList.Rows)-1 {
processList.SelectedRow++
}
case "<Left>":
if selectedColumn > 0 {
selectedColumn--
updateProcessList()
}
case "<Right>":
if selectedColumn < len(columns)-1 {
selectedColumn++
updateProcessList()
}
case "<Enter>", "<Space>":
sortReverse = !sortReverse
updateProcessList()
}
ui.Render(processList, grid)
}
func cycleColors() {
currentColorIndex = (currentColorIndex + 1) % len(colorOptions)
color := colorOptions[currentColorIndex]
ui.Theme.Block.Title.Fg, ui.Theme.Block.Border.Fg, ui.Theme.Paragraph.Text.Fg, ui.Theme.Gauge.Label.Fg, ui.Theme.Gauge.Bar = color, color, color, color, color
ui.Theme.BarChart.Bars = []ui.Color{color}
cpuGauge.BarColor, gpuGauge.BarColor, memoryGauge.BarColor = color, color, color
processList.TextStyle, NetworkInfo.TextStyle, PowerChart.TextStyle = ui.NewStyle(color), ui.NewStyle(color), ui.NewStyle(color)
processList.SelectedRowStyle, modelText.TextStyle, helpText.TextStyle = ui.NewStyle(ui.ColorBlack, color), ui.NewStyle(color), ui.NewStyle(color)
cpuGauge.BorderStyle.Fg, cpuGauge.TitleStyle.Fg = color, color
gpuGauge.BorderStyle.Fg, gpuGauge.TitleStyle.Fg, memoryGauge.BorderStyle.Fg, memoryGauge.TitleStyle.Fg = color, color, color, color
processList.BorderStyle.Fg, processList.TitleStyle.Fg, NetworkInfo.BorderStyle.Fg, NetworkInfo.TitleStyle.Fg = color, color, color, color
PowerChart.BorderStyle.Fg, PowerChart.TitleStyle.Fg = color, color
modelText.BorderStyle.Fg, modelText.TitleStyle.Fg, helpText.BorderStyle.Fg, helpText.TitleStyle.Fg = color, color, color, color
if sparkline != nil {
sparkline.LineColor = color
sparkline.TitleStyle = ui.NewStyle(color)
}
if sparklineGroup != nil {
sparklineGroup.BorderStyle = ui.NewStyle(color)
sparklineGroup.TitleStyle = ui.NewStyle(color)
}
cpuCoreWidget.BorderStyle.Fg, cpuCoreWidget.TitleStyle.Fg = color, color
processList.TextStyle = ui.NewStyle(color)
processList.SelectedRowStyle = ui.NewStyle(ui.ColorBlack, color)
processList.BorderStyle.Fg = color
processList.TitleStyle.Fg = color
updateProcessList()
ui.Render(processList)
}
func main() {
var (
colorName string
interval int
err error
setColor, setInterval bool
)
for i := 1; i < len(os.Args); i++ {
switch os.Args[i] {
case "--help", "-h":
fmt.Print("Usage: mactop [--help] [--version] [--interval] [--color]\n--help: Show this help message\n--version: Show the version of mactop\n--interval: Set the powermetrics update interval in milliseconds. Default is 1000.\n--color: Set the UI color. Default is none. Options are 'green', 'red', 'blue', 'cyan', 'magenta', 'yellow', and 'white'. (-c green)\n\nYou must use sudo to run mactop, as powermetrics requires root privileges.\n\nFor more information, see https://github.com/context-labs/mactop written by Carsen Klock.\n")
os.Exit(0)
case "--version", "-v":
fmt.Println("mactop version:", version)
os.Exit(0)
case "--test", "-t":
if i+1 < len(os.Args) {
testInput := os.Args[i+1]
fmt.Printf("Test input received: %s\n", testInput)
os.Exit(0)
}
case "--color", "-c":
if i+1 < len(os.Args) {
colorName = strings.ToLower(os.Args[i+1])
setColor = true
i++
} else {
fmt.Println("Error: --color flag requires a color value")
os.Exit(1)
}
case "--interval", "-i":
if i+1 < len(os.Args) {
interval, err = strconv.Atoi(os.Args[i+1])
if err != nil {
fmt.Println("Invalid interval:", err)
os.Exit(1)
}
setInterval = true
i++
} else {
fmt.Println("Error: --interval flag requires an interval value")
os.Exit(1)
}
}
}
if os.Geteuid() != 0 {
fmt.Println("Welcome to mactop! Please try again and run mactop with sudo privileges!")
fmt.Println("Usage: sudo mactop")
os.Exit(1)
}
logfile, err := setupLogfile()
if err != nil {
stderrLogger.Fatalf("failed to setup log file: %v", err)
}
defer logfile.Close()
if err := ui.Init(); err != nil {
stderrLogger.Fatalf("failed to initialize termui: %v", err)
}
defer ui.Close()
StderrToLogfile(logfile)
if setColor {
var color ui.Color
switch colorName {
case "green":
color = ui.ColorGreen
case "red":
color = ui.ColorRed
case "blue":
color = ui.ColorBlue
case "cyan":
color = ui.ColorCyan
case "magenta":
color = ui.ColorMagenta
case "yellow":
color = ui.ColorYellow
case "white":
color = ui.ColorWhite
default:
stderrLogger.Printf("Unsupported color: %s. Using default color.\n", colorName)
color = ui.ColorWhite
}
ui.Theme.Block.Title.Fg, ui.Theme.Block.Border.Fg, ui.Theme.Paragraph.Text.Fg, ui.Theme.Gauge.Label.Fg, ui.Theme.Gauge.Bar = color, color, color, color, color
ui.Theme.BarChart.Bars = []ui.Color{color}
setupUI()
cpuGauge.BarColor, gpuGauge.BarColor, memoryGauge.BarColor = color, color, color
processList.TextStyle = ui.NewStyle(color)
processList.SelectedRowStyle = ui.NewStyle(ui.ColorBlack, color)
} else {
setupUI()
}
if setInterval {
updateInterval = interval
}
setupGrid()
termWidth, termHeight := ui.TerminalDimensions()
grid.SetRect(0, 0, termWidth, termHeight)
cpuMetricsChan := make(chan CPUMetrics, 1)
gpuMetricsChan := make(chan GPUMetrics, 1)
netdiskMetricsChan := make(chan NetDiskMetrics, 1)
go collectMetrics(done, cpuMetricsChan, gpuMetricsChan, netdiskMetricsChan)
go func() {
ticker := time.NewTicker(time.Duration(updateInterval) * time.Millisecond)
defer ticker.Stop()
for {
select {
case cpuMetrics := <-cpuMetricsChan:
updateCPUUI(cpuMetrics)
updateTotalPowerChart(cpuMetrics.PackageW)
ui.Render(grid)
case gpuMetrics := <-gpuMetricsChan:
updateGPUUI(gpuMetrics)
ui.Render(grid)
case netdiskMetrics := <-netdiskMetricsChan:
updateNetDiskUI(netdiskMetrics)
ui.Render(grid)
case <-ticker.C:
percentages, err := GetCPUPercentages()
if err != nil {
stderrLogger.Printf("Error getting CPU percentages: %v\n", err)
continue
}
cpuCoreWidget.UpdateUsage(percentages)
var totalUsage float64
for _, usage := range percentages {
totalUsage += usage
}
totalUsage /= float64(len(percentages))
cpuCoreWidget.Title = fmt.Sprintf("mactop - %d Cores (%dE/%dP) %.2f%%",
cpuCoreWidget.eCoreCount+cpuCoreWidget.pCoreCount,
cpuCoreWidget.eCoreCount,
cpuCoreWidget.pCoreCount,
totalUsage,
)
updateProcessList()
ui.Render(grid)
case <-done:
return
}
}
}()
ui.Render(grid)
done := make(chan struct{})
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
defer func() {
if partyTicker != nil {
partyTicker.Stop()
}
}()
lastUpdateTime = time.Now()
uiEvents := ui.PollEvents()
for {
select {
case e := <-uiEvents:
handleProcessListEvents(e)
switch e.ID {
case "q", "<C-c>":
close(done)
ui.Close()
os.Exit(0)
return
case "<Resize>":
payload := e.Payload.(ui.Resize)
grid.SetRect(0, 0, payload.Width, payload.Height)
ui.Render(grid)
case "r":
termWidth, termHeight := ui.TerminalDimensions()
grid.SetRect(0, 0, termWidth, termHeight)