59 lines
1.6 KiB
Python
59 lines
1.6 KiB
Python
|
#!/usr/bin/python3
|
||
|
|
||
|
from Xlib import X, display, Xatom
|
||
|
import subprocess
|
||
|
import time
|
||
|
import Xlib.error
|
||
|
|
||
|
# Establish a connection to the X server
|
||
|
disp = display.Display()
|
||
|
root = disp.screen().root
|
||
|
|
||
|
# Set the mask to receive events
|
||
|
root.change_attributes(event_mask=X.SubstructureNotifyMask | X.StructureNotifyMask)
|
||
|
|
||
|
# Retrieve the Atom for _NET_WM_WINDOW_TYPE
|
||
|
NET_WM_WINDOW_TYPE = disp.intern_atom('_NET_WM_WINDOW_TYPE')
|
||
|
NET_WM_WINDOW_TYPE_NORMAL = disp.intern_atom('_NET_WM_WINDOW_TYPE_NORMAL')
|
||
|
|
||
|
|
||
|
def is_main_window(window):
|
||
|
try:
|
||
|
# Query the _NET_WM_WINDOW_TYPE attribute
|
||
|
window_type = window.get_full_property(NET_WM_WINDOW_TYPE, Xatom.ATOM)
|
||
|
if window_type and NET_WM_WINDOW_TYPE_NORMAL in window_type.value:
|
||
|
return True
|
||
|
|
||
|
except Xlib.error.XError:
|
||
|
pass
|
||
|
|
||
|
return False
|
||
|
|
||
|
|
||
|
def focus_window(window):
|
||
|
try:
|
||
|
# Use xdotool to focus the window
|
||
|
subprocess.run(['xdotool', 'windowactivate', str(window.id)], check=True)
|
||
|
|
||
|
except subprocess.CalledProcessError as e:
|
||
|
print(f"Error focusing window {window.id}: {e}")
|
||
|
|
||
|
|
||
|
while True:
|
||
|
event = root.display.next_event()
|
||
|
|
||
|
if event.type == X.CreateNotify:
|
||
|
window = event.window
|
||
|
# Wait a short time to ensure the window is initialized
|
||
|
time.sleep(0.05)
|
||
|
|
||
|
if is_main_window(window):
|
||
|
focus_window(window)
|
||
|
|
||
|
elif event.type == X.MapNotify:
|
||
|
window = event.window
|
||
|
# Wait a short time to ensure the window is initialized
|
||
|
time.sleep(0.05)
|
||
|
|
||
|
if is_main_window(window):
|
||
|
focus_window(window)
|