aboutsummaryrefslogblamecommitdiffstats
path: root/xpybar/config/adjbacklight
blob: a48026258d9881e1e08b0342cbb8081bfb14aec3 (plain) (tree)

























































































                                                                                                                                 
# -*- python -*-
import os
import sys
import time

OUTPUT, HEIGHT, YPOS, TOP = 0, 2 * 12, 0, True

LEFT_BUTTON = 1
MIDDLE_BUTTON = 2
RIGHT_BUTTON = 3
SCROLL_UP = 4
SCROLL_DOWN = 5
SCROLL_LEFT = 6
SCROLL_RIGHT = 7
FORWARD_BUTTON = 8                                                                                                               
BACKWARD_BUTTON = 9

r, w = os.pipe()
pid = os.fork()
if not pid:
    os.dup2(r, 0)
    os.close(w)
    os.execlp('adjbacklight', 'adjbacklight')
    sys.exit(1)
os.close(r)

def get_backlight():
    r, w = os.pipe()
    pid = os.fork()
    if not pid:
        os.dup2(w, 1)
        os.execlp('adjbacklight', 'adjbacklight', '-g')
        sys.exit(1)
    os.close(w)
    ret = b''
    while True:
        bs = os.read(r, 512)
        if not bs:
            break
        ret += bs
    os.close(r)
    os.waitpid(pid, 0)
    ret = float(ret.decode('utf-8', 'replace').rstrip('%\n')) / 100
    return ret

def set_backlight():
    if 0 <= backlight <= 1:
        os.write(w, b'%f%%\n' % (backlight * 100))
        time.sleep(0.0001)

backlight = get_backlight()

def redraw():
    x = int(bar.width * backlight + 0.5)
    bar.change_colour(bar.foreground)
    bar.window.fill_rectangle(bar.gc, 0, 0, x, HEIGHT)
    bar.change_colour(bar.background)
    bar.window.fill_rectangle(bar.gc, x, 0, bar.width - x, HEIGHT)

import x as _x
_get_event_mask = _x.get_event_mask
def get_event_mask():
    return _get_event_mask() | Xlib.X.ButtonMotionMask
_x.get_event_mask = get_event_mask

def unhandled_event(e):
    global backlight
    if isinstance(e, Xlib.protocol.event.ButtonPress):
        button, x = e.detail, e.event_x
        if button == LEFT_BUTTON:
            backlight = min(max(0, x / bar.width), 1)
            set_backlight()
            bar.invalidate()
        elif button == SCROLL_UP:
            backlight = min(backlight + 0.05, 1)
            set_backlight()
            bar.invalidate()
        elif button == SCROLL_DOWN:
            backlight = max(backlight - 0.05, 0)
            set_backlight()
            bar.invalidate()
        elif button in (MIDDLE_BUTTON, RIGHT_BUTTON, FORWARD_BUTTON, BACKWARD_BUTTON):
            os.close(w)
            os.waitpid(pid, 0)
            raise KeyboardInterrupt()
    elif isinstance(e, Xlib.protocol.event.MotionNotify):
        if e.detail == 0:
            backlight = min(max(0, e.event_x / bar.width), 1)
            set_backlight()
            bar.invalidate()