Add existing scripts.
This commit is contained in:
70
focus.py
Normal file
70
focus.py
Normal file
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import os
|
||||
import psutil
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
XDOTOOL_CMD = ["xdotool", "getactivewindow", "getwindowname", "getwindowpid"]
|
||||
|
||||
|
||||
SESSIONS = {
|
||||
"sicp": [
|
||||
"~",
|
||||
"~/dev/sicp",
|
||||
"mit-scheme",
|
||||
"Mozilla Firefox",
|
||||
"[No Name] - VIM",
|
||||
re.compile("sicp-ex-"),
|
||||
re.compile("\.scm"),
|
||||
re.compile("Structure and Interpretation of Computer Programs"),
|
||||
re.compile("SICP-Solutions"),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def is_window_allowed(window_name, allowed):
|
||||
for a in allowed:
|
||||
if type(a) is str and a == window_name:
|
||||
return True
|
||||
elif type(a) is re.Pattern and a.findall(window_name):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def main(session_name):
|
||||
allowed_window_names = SESSIONS[session_name]
|
||||
start_time = time.time()
|
||||
|
||||
while time.time() - start_time < 60 * 60:
|
||||
time.sleep(5)
|
||||
p = subprocess.run(XDOTOOL_CMD, capture_output=True)
|
||||
if p.returncode != 0:
|
||||
continue
|
||||
window_name, window_pid, _ = p.stdout.decode().split("\n")
|
||||
if not is_window_allowed(window_name, allowed_window_names):
|
||||
p = psutil.Process(int(window_pid))
|
||||
p.kill()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
session_name = sys.argv[1]
|
||||
except IndexError:
|
||||
print("Provide a session name as the first argument.")
|
||||
sys.exit(1)
|
||||
if not session_name in SESSIONS:
|
||||
print(f"Session with name {session_name} does not exist.")
|
||||
sys.exit(1)
|
||||
|
||||
if os.geteuid() == 0:
|
||||
newpid = os.fork()
|
||||
if newpid == 0:
|
||||
main(session_name)
|
||||
else:
|
||||
cmd = ["sudo"] + sys.argv
|
||||
subprocess.Popen(cmd, start_new_session=True)
|
||||
|
||||
Reference in New Issue
Block a user