Skip to content

Instantly share code, notes, and snippets.

@sochotnicky
Created September 13, 2021 07:55
Show Gist options
  • Save sochotnicky/17caa9504d7b5afdacc7bdae93f68d9c to your computer and use it in GitHub Desktop.
Save sochotnicky/17caa9504d7b5afdacc7bdae93f68d9c to your computer and use it in GitHub Desktop.
sway_switch_windows.py
#!/usr/bin/python3
import sys
import json
import subprocess
import re
def get_named_windows(tree):
ret = []
if tree["name"] and tree["border"] != "none":
s = f"{tree['id']}: {tree['name']}"
if "window_properties" in tree:
# X11/spotify has no nice ID
s += f" - {tree['window_properties']['instance']}"
ret.append(s)
for node in tree["nodes"]:
ret.extend(get_named_windows(node))
return ret
if __name__ == "__main__":
tree = subprocess.run(["swaymsg", "-t", "get_tree"], capture_output=True)
tree = json.loads(tree.stdout)
windows = get_named_windows(tree)
if len(sys.argv) > 1:
# Use arg
for window in windows:
if sys.argv[1] in window and sys.argv[0] not in window:
focus = window
break
if not focus:
sys.exit(1)
else:
# No arguments, display fuzzel
focus = subprocess.run(
["fuzzel", "-d"],
capture_output=True,
input="\n".join(windows).encode("utf-8"),
)
focus = focus.stdout.decode("utf-8")
wid = int(re.match(r"(^\d+):", focus).group(1))
cmd = ["swaymsg", f'[con_id="{wid}"]', "focus"]
subprocess.run(cmd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment