i3_workspaces.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #!/usr/bin/env python
  2. #
  3. # Print i3 workspaces on every change.
  4. #
  5. # Format:
  6. # For every workspace (x = workspace name)
  7. # - "FOCx" -> Focused workspace
  8. # - "INAx" -> Inactive workspace
  9. # - "ACTx" -> Ative workspace
  10. # - "URGx" -> Urgent workspace
  11. #
  12. # Uses i3py.py -> https://github.com/ziberna/i3-py
  13. # Based in wsbar.py en examples dir
  14. #
  15. # 16 feb 2015 - Electro7
  16. import sys
  17. import time
  18. import subprocess
  19. import i3
  20. class State(object):
  21. # workspace states
  22. focused = 'FOC'
  23. active = 'ACT'
  24. inactive = 'INA'
  25. urgent = 'URG'
  26. def get_state(self, workspace, output):
  27. if workspace['focused']:
  28. if output['current_workspace'] == workspace['name']:
  29. return self.focused
  30. else:
  31. return self.active
  32. if workspace['urgent']:
  33. return self.urgent
  34. else:
  35. return self.inactive
  36. class i3ws(object):
  37. ws_format = '%s%s '
  38. end_format = 'WSP%s'
  39. state = State()
  40. def __init__(self, state=None):
  41. if state:
  42. self.state = state
  43. # socket
  44. self.socket = i3.Socket()
  45. # Output to console
  46. workspaces = self.socket.get('get_workspaces')
  47. outputs = self.socket.get('get_outputs')
  48. self.display(self.format(workspaces, outputs))
  49. # Subscribe to an event
  50. callback = lambda data, event, _: self.change(data, event)
  51. self.subscription = i3.Subscription(callback, 'workspace')
  52. def change(self, event, workspaces):
  53. # Receives event and workspace data
  54. if 'change' in event:
  55. outputs = self.socket.get('get_outputs')
  56. text = self.format(workspaces, outputs)
  57. self.display(text)
  58. def format(self, workspaces, outputs):
  59. # Formats the text according to the workspace data given.
  60. out = ''
  61. for workspace in workspaces:
  62. output = None
  63. for output_ in outputs:
  64. if output_['name'] == workspace['output']:
  65. output = output_
  66. break
  67. if not output:
  68. continue
  69. st = self.state.get_state(workspace, output)
  70. name = workspace['name']
  71. item= self.ws_format % (st, name)
  72. out += item
  73. return self.end_format % out
  74. def display(self, text):
  75. # Displays the text in stout
  76. print(text)
  77. sys.stdout.flush()
  78. def quit(self):
  79. # Quits the i3ws; closes the subscription and terminates
  80. self.subscription.close()
  81. if __name__ == '__main__':
  82. ws = i3ws()
  83. try:
  84. while True:
  85. time.sleep(1)
  86. except KeyboardInterrupt:
  87. print('') # force new line
  88. finally:
  89. ws.quit()