Last active
December 24, 2019 01:32
-
-
Save jo-makar/c28c63d3c7bd9142ccf3e5a708ce3f74 to your computer and use it in GitHub Desktop.
Framework to restore/build an i3 session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Restore/build an i3 session | |
import argparse, json, logging, queue, subprocess, threading | |
if __name__ == '__main__': | |
def i3msg(args): | |
cmd = ['i3-msg'] + args | |
logging.info('cmd = %r', cmd) | |
subprocess.check_call(cmd, stderr=subprocess.STDOUT, encoding='utf-8') | |
class IpcThread(threading.Thread): | |
def __init__(self): | |
threading.Thread.__init__(self) | |
self.daemon = True | |
self.queue = queue.Queue() | |
def run(self): | |
with subprocess.Popen(['i3-msg', '-t', 'subscribe', '-m', '["window"]'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8') as proc: | |
for line in proc.stdout: | |
logging.debug('ipc: %s', line) | |
if json.loads(line)['change'] == 'new': | |
self.queue.put(json.loads(line)['container']['window']) | |
def launch(cmd, timeout=30): | |
# One effective way to know when a command has successfully launched is by tracking the creation of its window. | |
# A separate thread is used to monitor "window" events for this, with a queue indicating windows creation with their ids. | |
while not ipc.queue.empty(): | |
ipc.queue.get() | |
i3msg(['exec --no-startup-id ' + cmd]) | |
return ipc.queue.get(timeout=timeout) | |
focus = lambda x: i3msg(['focus', x]) | |
layout = lambda x: i3msg(['layout', x]) | |
splitvert = lambda: i3msg(['split', 'v']) | |
workspace = lambda x: i3msg(['workspace', str(x)]) | |
def window_type(wid, text): | |
cmd = ['xdotool', 'type', '--window', str(wid), text] | |
subprocess.check_call(cmd, stderr=subprocess.STDOUT, encoding='utf-8') | |
logging.basicConfig(format='%(asctime)s:%(threadName)s:%(levelname)s:%(message)s', level=logging.INFO) | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--debug', '-d', action='store_true') | |
args = parser.parse_args() | |
if args.debug: | |
logging.getLogger().setLevel(logging.DEBUG) | |
ipc = IpcThread() | |
ipc.start() | |
workspace(0) | |
wid = launch('xterm') | |
window_type(wid, 'cd ~/todo\n') | |
workspace(1) | |
launch('google-chrome --new-window "https://mail.google.com/mail/u/0/#inbox"') | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment