wmtools/brightness.nim

104 lines
2.5 KiB
Nim

import base
import std/[os,strutils,osproc,math]
const backlight = "intel_backlight"
const default_bg = yellow
const default_fg = black
const backlight_cmd = "xbacklight"
const backlight_up = backlight_cmd & " -inc %v" # %v is amount by
const backlight_down = backlight_cmd & " -dec %v" # %v is amount by
const backlight_set = backlight_cmd & " -set %v" # %v is amount by
const default_value = "5"
proc getLimit(): int =
try:
let back_l = readFile("/sys/class/backlight/" & backlight & "/max_brightness")
return parseInt(strip(back_l))
except:
echo "Error getting backlight max : ", getCurrentExceptionMsg()
return -1
let limit = getLimit()
proc getDesign(pcnt: float): string =
var icon = "🌑"
case pcnt:
of 85..100:
icon = "🌕"
of 75..85:
icon = "🌖"
of 50..75:
icon = "🌗"
of 35..50:
icon = "🌘"
else:
icon = "🌑"
let percent = toInt(round(pcnt,0))
let text = icon & " " & $percent & "%"
return text
proc brightnessUp() =
let cmd = replace(backlight_up,"%v",default_value)
discard execCmd(cmd)
proc brightnessDown() =
let cmd = replace(backlight_down,"%v",default_value)
discard execCmd(cmd)
proc getBrightness*(run_once: bool = false) =
var last_pcnt: float = 0
while true:
let current = parseInt(strip(readFile("/sys/class/backlight/" & backlight & "/actual_brightness")))
let pcnt = (current/limit)*100
if pcnt != last_pcnt:
let text = getDesign(pcnt)
var data = newInfo("Brightness")
data.full_text = text
data.selected_bg = default_fg
data.selected_fg = default_bg
# i3bar stuff
data.border = default_fg
let args = @["up", "down"]
let option = outputData(data,args)
if option in args:
case option:
of "up":
brightnessUp()
getBrightness(true)
of "down":
brightnessDown()
getBrightness(true)
else:
try:
let i = parseInt(option)
let cmd = replace(backlight_set,"%v",$i)
discard execCmd(cmd)
getBrightness(true)
except:
echo getCurrentExceptionMsg()
if run_once:
break
if stoploop:
break
last_pcnt = pcnt
sleep(1000)
proc main() =
if limit == -1:
switchTwmMode()
return
getBrightness()
if isMainModule:
block start:
for arg in args:
case arg:
of "up":
brightnessUp()
break start
of "down":
brightnessDown()
break start
main()