aboutsummaryrefslogtreecommitdiff
path: root/i3/bin/i3status.py
blob: ce562b1b9907d36e2ee39301b58b725db0a6e7dd (plain) (blame)
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
#!/usr/bin/env python
import json
from select import select
from subprocess import Popen, PIPE
import sys

def remove_empty_outputs(obj):
    return [o for o in obj if o['full_text'].strip() != '']

first = True
def print_i3stat(j):
    global first
    j = remove_empty_outputs(j)
    sys.stdout.write(('' if first else ',') + json.dumps(j) + '\n')
    sys.stdout.flush()
    first = False

def parse_i3stat(s):
    if s[0] == ',':
        s = s[1:]
    j = json.loads(s)
    return j

def parse_kbdlayout(s):
    colors = { 'us(intl)' : '#66ccff',
            'us(dvorak-intl)' : '#dc68fc',
            'ru(phonetic)' : '#ff3300',
            'il(biblicalSIL)' : '#66ff66'
            }
    try:
        color = colors[s]
    except:
        color = '#cccccc'
    return [{'full_text': s, 'color': color}]

def merge_status_items(*args):
    return [item for sublist in args for item in sublist]

if __name__ == '__main__':
    timeout = 0.1

    # open subprocesses
    i3stat = Popen(['i3status'], stdout=PIPE, bufsize=1, close_fds=True)
    kbdlayout = Popen(['unbuffer', 'kbdlayout'], 
            stdout=PIPE, bufsize=1, close_fds=True)
    # skip i3status header
    sys.stdout.write(i3stat.stdout.readline())
    sys.stdout.write(i3stat.stdout.readline())

    stat, kbd, clg = [], [], []
    try:
        stdouts = [p.stdout for p in [i3stat, kbdlayout]]
        while True:
            fs = select(stdouts, [], [])[0]
            for f in fs:
                line = f.readline()[:-1]
                if f == kbdlayout.stdout:
                    kbd = parse_kbdlayout(line)
                elif f == i3stat.stdout:
                    stat = parse_i3stat(line)
    
            print_i3stat(merge_status_items(kbd, clg, stat))

    except Exception, e:
        print(e)
        i3stat.kill()
        kbdlayout.kill()