#!/usr/bin/env python

#
# Focuses next window matching active WM_CLASS on current workspace
#

import pylon
from Xlib import X

active_window_id = pylon.get_active_window_id()
active_window = pylon.get_window_by_id(active_window_id)
active_wm_class = active_window.get_wm_class()[0]
active_wm_client = active_window.get_wm_client_machine()

#
def window_id_matches(window_id):
  window = pylon.get_window_by_id(window_id)
  attributes = window.get_attributes()

  return (
    attributes.map_state == X.IsViewable
    and not window.get_wm_transient_for()
    and window.get_wm_class()[0] == active_wm_class
    and window.get_wm_client_machine() == active_wm_client
    and pylon.is_window_id_on_current_workspace(window_id)
  )

window_ids = [
  window_id for window_id
  in pylon.get_all_window_ids()
  if window_id_matches(window_id)
]

if active_window_id not in window_ids:
  quit()

next_index = (window_ids.index(active_window_id) + 1) % len(window_ids)
next_window_id = window_ids[next_index]

pylon.activate_window_by_id(next_window_id)
