wmtools/brightness.nim

117 lines
2.8 KiB
Nim
Raw Normal View History

2022-04-28 21:58:40 +02:00
import base
import std/[os,strutils,osproc,math]
2022-02-06 21:10:06 +01:00
const backlight = "intel_backlight"
const default_bg = yellow
const default_fg = black
const BACKLIGHT_CMD = "xbacklight"
const UP_X = BACKLIGHT_CMD & " -inc %v" # %v is amount by
const DOWN_X = BACKLIGHT_CMD & " -dec %v" # %v is amount by
const SET_X = BACKLIGHT_CMD & " -set %v" # %v is amount by
const BACKLIGHT_CMD_WL = "brightnessctl"
const UP_WL = BACKLIGHT_CMD_WL & " set %v%+"
const DOWN_WL = BACKLIGHT_CMD_WL & " set %v%-"
const SET_WL = BACKLIGHT_CMD_WL & " set %v%"
var CMD = BACKLIGHT_CMD
var UP = UP_X
var DOWN = DOWN_X
var SET = SET_X
const default_value = "5"
2022-02-06 21:10:06 +01:00
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()
2022-02-06 21:10:06 +01:00
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(UP,"%v",default_value)
discard execCmd(cmd)
proc brightnessDown() =
let cmd = replace(DOWN,"%v",default_value)
discard execCmd(cmd)
proc getBrightness*(run_once: bool = false) =
2022-02-12 14:20:21 +01:00
var last_pcnt: float = 0
while true:
let current = parseInt(strip(readFile("/sys/class/backlight/" & backlight & "/actual_brightness")))
2022-02-12 14:20:21 +01:00
let pcnt = (current/limit)*100
if pcnt != last_pcnt:
let text = getDesign(pcnt)
var data = newInfo("Brightness")
2022-02-27 15:57:40 +01:00
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)
2022-05-01 19:09:07 +02:00
if option in args:
case option:
of "up":
brightnessUp()
getBrightness(true)
2022-05-01 19:09:07 +02:00
of "down":
brightnessDown()
getBrightness(true)
2022-05-01 19:09:07 +02:00
else:
try:
let i = parseInt(option)
let cmd = replace(SET,"%v",$i)
discard execCmd(cmd)
getBrightness(true)
2022-05-01 19:09:07 +02:00
except:
echo getCurrentExceptionMsg()
2022-02-12 14:20:21 +01:00
if run_once:
break
if stoploop:
break
2022-02-12 14:20:21 +01:00
last_pcnt = pcnt
sleep(1000)
2022-02-06 21:10:06 +01:00
proc main() =
if limit == -1:
switchTwmMode()
return
getBrightness()
2022-02-06 21:10:06 +01:00
if isMainModule:
block start:
for arg in args:
case arg:
of "-w":
CMD = BACKLIGHT_CMD_WL
UP = UP_WL
DOWN = DOWN_WL
SET = SET_WL
of "up":
brightnessUp()
break start
of "down":
brightnessDown()
break start
main()