utility-screen/screen_main.go
2015-11-30 08:17:53 -06:00

79 lines
2.0 KiB
Go

package main
import (
"fmt"
"os/exec"
"strconv"
"strings"
"time"
"gogs.bullercodeworks.com/brian/termbox-util"
"github.com/nsf/termbox-go"
)
type mainScreen struct {
initialized bool
tabIdx int
battStat *termboxUtil.ProgressBar
}
func (screen *mainScreen) handleKeyEvent(event termbox.Event) int {
if event.Type == termbox.EventKey {
if event.Key == termbox.KeyEsc {
return exitScreenIndex
} else if event.Ch == 'r' {
// Refresh data
screen.battStat.SetProgress(getBatteryPct())
} else if event.Ch == 'q' {
return exitScreenIndex
}
}
return mainScreenIndex
}
func (screen *mainScreen) performLayout(style style) {
if !screen.initialized {
w, _ := termbox.Size()
screen.battStat = termboxUtil.CreateProgressBar(100, w-14, 1, style.defaultFg, style.defaultBg)
screen.battStat.SetProgress(getBatteryPct())
}
}
func (screen *mainScreen) drawScreen(style style) {
w, h := termbox.Size()
termboxUtil.DrawStringAtPoint(time.Now().Format("15:04 MST"), 0, 0, style.defaultFg, style.defaultBg)
termboxUtil.DrawStringAtPoint(time.Now().Format("02 Jan 2006"), 0, 1, style.defaultFg, style.defaultBg)
screen.battStat.Draw()
termboxUtil.DrawStringAtPoint(fmt.Sprintf("% 3d%s", screen.battStat.GetPercent(), "%"),
screen.battStat.GetX()+screen.battStat.GetWidth(),
screen.battStat.GetY(), style.defaultFg, style.defaultBg)
quitTxt := "(q)uit"
termboxUtil.DrawStringAtPoint(quitTxt, (w - len(quitTxt)), h-1, style.defaultFg, style.defaultBg)
}
func getBatteryPct() int {
powerApp := "upower"
powerArg1 := "-i"
powerArg2 := "/org/freedesktop/UPower/devices/battery_BAT0"
cmd := exec.Command(powerApp, powerArg1, powerArg2)
stdout, err := cmd.Output()
if err != nil {
return -1
}
tst := string(stdout)
for _, k := range strings.Split(tst, "\n") {
pair := strings.Split(k, ":")
if len(pair) > 1 {
pair[0] = strings.Trim(pair[0], " ")
pair[1] = strings.Trim(pair[1], " %")
if pair[0] == "percentage" {
if pct, err := strconv.Atoi(pair[1]); err == nil {
return pct
}
}
}
}
return -1
}