Skip to content

Instantly share code, notes, and snippets.

@brookskindle
Last active February 22, 2018 23:06
Show Gist options
  • Save brookskindle/0272f01a090f0c0fb949bd34ceb7e073 to your computer and use it in GitHub Desktop.
Save brookskindle/0272f01a090f0c0fb949bd34ceb7e073 to your computer and use it in GitHub Desktop.
What window and workspaces am I focused on throughout the day?
#!/usr/bin/env python3
from collections import namedtuple
import csv
import datetime
import os
import subprocess
import time
WindowInfo = namedtuple("WindowInfo", ["window_name", "window_class"])
def get_focused_workspace() -> str:
"""Return the name of the currently focused i3 workspace.
Requires i3 and jq to be installed
"""
process = subprocess.run(
"i3-msg -t get_workspaces | jq '.[] | select(.focused).name' -r",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding="utf-8",
)
workspace = process.stdout.strip()
return workspace
def get_current_date() -> str:
now = datetime.datetime.now()
return now.strftime("%Y-%m-%d %H:%M:%S")
def is_locked() -> bool:
"""Return True or False, depending on if i3lock is running"""
process = subprocess.run(
["pgrep", "i3lock"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
i3lock_running = not bool(process.returncode)
return i3lock_running
def get_focused_window() -> WindowInfo:
"""Return a WindowInfo namedtuple about the currently focused window"""
p = subprocess.run(
["xprop", "-root", "_NET_ACTIVE_WINDOW"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding="utf-8",
)
window_id = p.stdout.strip().split()[-1]
p2 = subprocess.run(
["xprop", "-id", window_id, "WM_NAME", "WM_CLASS"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding="utf-8",
)
if not p2.returncode:
# We have a window we're focusing on
stdout = p2.stdout.splitlines()
window_name = stdout[0].split("=")[-1].replace('"', "").strip()
window_class = stdout[1].split("=")[-1].replace('"', "").strip()
else: # We have no focused window - must be in a new workspace?
window_name = None
window_class = None
window = WindowInfo(window_name, window_class)
return window
def write_to_csv(filename="tracking.csv"):
"""Write a row of metadata information to a csv file"""
header = [
"workspace",
"computer_locked",
"focused_window_name",
"focused_window_class",
"timestamp",
]
window = get_focused_window()
row = [
get_focused_workspace(),
is_locked(),
window.window_name,
window.window_class,
get_current_date(),
]
with open(filename, "a") as csvfile:
writer = csv.writer(csvfile)
if csvfile.tell() == 0:
# At beginning of the file, also write a header line
writer.writerow(header)
writer.writerow(row)
if __name__ == "__main__":
while True:
filename = os.path.expanduser("~/tracking.csv")
write_to_csv(filename)
time.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment