Skip to content

Instantly share code, notes, and snippets.

@lsmag
Created February 15, 2017 00:15
Show Gist options
  • Save lsmag/439e828646f07c403c1ea1b5356f1119 to your computer and use it in GitHub Desktop.
Save lsmag/439e828646f07c403c1ea1b5356f1119 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
##
## Check this url for the original reference:
## https://github.com/12foo/dotfiles/blob/master/tag-x11/config/herbstluftwm/topbar.py
## https://github.com/krypt-n/bar
##
##
import os
import sys
import select
import atexit
import subprocess
import commands
from datetime import datetime
FOCUSED_TAG_FOCUSED_MONITOR = '#'
FOCUSED_TAG_UNFOCUSED_MONITOR = '+'
UNFOCUSED_TAG_WITH_PROGRAMS = ':'
EMPTY_TAG = '.'
TAG_NEEDING_ATTENTION = '!'
TAG_ALIGN_LEFT = '%{l}'
TAG_ALIGN_CENTER = '%{c}'
TAG_ALIGN_RIGHT = '%{r}'
DARK_COLOR = '#3C3C3C'
LIGHT_COLOR = '#D1D1D1'
FOCUS_COLOR = '#DC5981'
ATTENTION_COLOR = '#900000'
def fg(color, text):
return ''.join(['%{F', color, '}', text, '%{F-}'])
def bg(color, text):
return ''.join(['%{B', color, '}', text, '%{B-}'])
def pattern(bg_color, fg_color, text):
return bg(bg_color, fg(fg_color, ' %s ' % text))
class Widget(object):
@classmethod
def available(cls):
"""Determines if widget is available/makes sense on this system."""
return True
def __init__(self, id, pipe, hooks):
self.id = id
def render(self):
return ''
def update(self, line):
pass
class Datetime(Widget):
def render(self):
return ' %s ' % datetime.now().strftime('%d/%m/%Y %H:%M:%S')
class Text(Widget):
def __init__(self, id, text):
super(Widget, self)
self.id = id
self.text = text
def render(self):
return self.text
class HerbstluftwmTags(Widget):
def __init__(self, id, pipe, hooks):
self.client = subprocess.Popen(['herbstclient', '--idle', 'tag_changed'], stdout=pipe)
atexit.register(self.client.kill)
self.id = id
self.tags = []
hooks['tag_changed'] = self
def update(self, line):
out = commands.getoutput('herbstclient tag_status')
self.tags = out.decode('utf-8').strip().split('\t')
def render(self):
out = []
for i, tag in enumerate(self.tags):
if tag[0] == FOCUSED_TAG_FOCUSED_MONITOR:
out.append(pattern(FOCUS_COLOR, LIGHT_COLOR, '%{+u}' + tag[1:] + '%{-u}'))
elif tag[0] in [FOCUSED_TAG_UNFOCUSED_MONITOR, UNFOCUSED_TAG_WITH_PROGRAMS]:
out.append(pattern(LIGHT_COLOR, DARK_COLOR, tag[1:]))
elif tag[0] == EMPTY_TAG:
out.append(pattern(DARK_COLOR, LIGHT_COLOR, tag[1:]))
elif tag[0] == TAG_NEEDING_ATTENTION:
out.append(pattern(ATTENTION_COLOR, LIGHT_COLOR, tag[1:]))
return ' '.join(out)
class CommandWidget(Widget):
def render(self):
out = commands.getoutput(self.COMMAND)
return ' %s:%s ' % (self.LABEL, out.decode('utf-8').split('\n')[0])
class Memory(CommandWidget):
LABEL = 'mem'
COMMAND = '/usr/lib/i3blocks/memory'
class Swap(CommandWidget):
LABEL = 'swap'
COMMAND = 'BLOCK_INSTANCE=swap /usr/lib/i3blocks/memory'
class CPUUsage(CommandWidget):
LABEL = 'cpu'
COMMAND = '/usr/lib/i3blocks/cpu_usage'
class Temperature(CommandWidget):
LABEL = 'temp'
COMMAND = '/usr/lib/i3blocks/temperature'
class Battery(CommandWidget):
LABEL = 'battery'
COMMAND = '/usr/lib/i3blocks/battery'
WIDGETS = [TAG_ALIGN_LEFT,
HerbstluftwmTags,
TAG_ALIGN_CENTER,
Memory,
Swap,
CPUUsage,
Battery,
Datetime]
def main():
sread, swrite = os.pipe()
hooks = {}
widgets = []
for i, wc in enumerate(WIDGETS):
if isinstance(wc, basestring):
w = Text(i, wc)
widgets.append(w)
elif wc.available():
w = wc(i, swrite, hooks)
w.update(None)
widgets.append(w)
# Print the first output
buffer = [w.render() for w in widgets]
print ''.join(buffer)
sys.stdout.flush()
while True:
ready, _, _ = select.select([sread], [], [], 5)
if len(ready) > 0:
for p in ready:
lines = os.read(ready[0], 4096).decode('utf-8').splitlines()
for line in lines:
for title, hook in hooks.iteritems():
if line.startswith(title):
hook.update(line)
buffer.pop(hook.id)
buffer.insert(hook.id, hook.render())
else:
# Atualiza os widgets a cada 5s se não teve mudança
buffer = [w.render() for w in widgets]
print ''.join(buffer)
sys.stdout.flush()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment