alternating_layouts.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env python3
  2. import getopt
  3. import sys
  4. import os
  5. from i3ipc import Connection, Event
  6. def find_parent(i3, window_id):
  7. """
  8. Find the parent of a given window id
  9. """
  10. def finder(con, parent):
  11. if con.id == window_id:
  12. return parent
  13. for node in con.nodes:
  14. res = finder(node, con)
  15. if res:
  16. return res
  17. return None
  18. return finder(i3.get_tree(), None)
  19. def set_layout(i3, e):
  20. """
  21. Set the layout/split for the currently
  22. focused window to either vertical or
  23. horizontal, depending on its width/height
  24. """
  25. win = e.container
  26. parent = find_parent(i3, win.id)
  27. if (parent and parent.layout != 'tabbed'
  28. and parent.layout != 'stacked'):
  29. if win.rect.height > win.rect.width:
  30. i3.command('split v')
  31. else:
  32. i3.command('split h')
  33. def print_help():
  34. print("Usage: " + sys.argv[0] + " [-p path/to/pid.file]")
  35. print("")
  36. print("Options:")
  37. print(" -p path/to/pid.file Saves the PID for this program in the filename specified")
  38. print("")
  39. def main():
  40. """
  41. Main function - listen for window focus
  42. changes and call set_layout when focus
  43. changes
  44. """
  45. opt_list, _ = getopt.getopt(sys.argv[1:], 'hp:')
  46. pid_file = None
  47. for opt in opt_list:
  48. if opt[0] == "-h":
  49. print_help()
  50. sys.exit()
  51. if opt[0] == "-p":
  52. pid_file = opt[1]
  53. if pid_file:
  54. with open(pid_file, 'w') as f:
  55. f.write(str(os.getpid()))
  56. i3 = Connection()
  57. i3.on(Event.WINDOW_FOCUS, set_layout)
  58. i3.main()
  59. if __name__ == "__main__":
  60. main()