Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import json 

2import select 

3import sys 

4import threading 

5 

6 

7def read_sys(): 

8 """Read a line from :attr:`sys.stdin` (i3bar), strip and return it.""" 

9 return sys.stdin.readline().strip().lstrip(',') 

10 

11 

12def write_sys(s): 

13 """Write given string ``s`` to :attr:`sys.stdout` (i3bar) and flush.""" 

14 sys.stdout.write(s) 

15 sys.stdout.flush() 

16 

17 

18class I3BarEventThread(threading.Thread): 

19 

20 #: :class:`bool` - set to ``False`` to stop the loop in :meth:`run` 

21 CONTINUE = True 

22 

23 #: :class:`bool` - :attr:`threading.Thread.daemon` 

24 daemon = True 

25 

26 #: function to call for each event 

27 on_click = None 

28 

29 def __init__(self, on_click, logger, *args, **kwargs): 

30 self.on_click = on_click 

31 self.logger = logger 

32 super(I3BarEventThread, self).__init__(*args, **kwargs) 

33 

34 def run(self): 

35 """ 

36 Wait for i3bar events on :attr:`sys.stdin` and call :attr:`on_click`. 

37 """ 

38 self.logger.info('I3BarEventTread running') 

39 

40 while self.CONTINUE: 

41 while sys.stdin in select.select([sys.stdin], [], [], 0.5)[0] and self.CONTINUE: 

42 line = read_sys() 

43 

44 if line: 

45 if line == '[': # first event starts with array-start-line 

46 line = read_sys() 

47 

48 event = json.loads(line) 

49 self.logger.debug('Click %s' % event) 

50 self.on_click( 

51 event['name'], 

52 event['instance'], 

53 event['button'], 

54 event['x'], 

55 event['y'], 

56 ) 

57 else: 

58 # exit 

59 self.logger.warning('i3bar unexpectedly closed') 

60 self.CONTINUE = False 

61