#!/bin/zsh
# vim: sts=2 sw=2 et
setopt no_unset warn_create_global

typeset -gA display_to_container

read_map() {
  local record container display
  for record in /run/display-container-map/*=*(N); do
    record=${record:t}
    display=${record%%=*}
    container=${record#*=}
    display_to_container[$display]=$container
  done
}

process_server() {
  local disp=$1 wid w_desktop w_pid w_host w_title
  (( $+display_to_container[$disp] )) || return
  local -a l cmd=( env DISPLAY=:$disp )
  [[ -e /run/Xauthority.$disp ]] && cmd+=( XAUTHORITY=/run/Xauthority.$disp )
  $cmd wmctrl -lp | while IFS=' ' read -r wid w_desktop w_pid w_host w_title; do
    l=( $disp $display_to_container[$disp] $((wid)) $w_desktop $w_pid $w_host $w_title )
    printf '%s\n' "${(@pj:\t:)l}"
  done
}

main() {
  read_map
  local sock
  for sock in /tmp/.X11-unix/X*; do
    process_server ${sock##*/X}
  done
}
#typeset -f -t main

main "$@"