#!/bin/bash

#get/set vsync(aka vblank_mode) of xfwm4 without restarting xfwm4(ie. keep the same xfwm4 pid)

#mentioned in:
#https://github.com/LibVNC/x11vnc/issues/102#issuecomment-528337166
#https://bugzilla.xfce.org/show_bug.cgi?id=15927#c3

function reloadGTK(){
#src: https://crunchbang.org/forums/viewtopic.php?pid=428525#p428525
#used here: https://github.com/LibVNC/x11vnc/issues/102#issuecomment-528337166

#required: sudo pacman -S pygtk

  python2 - <<END
import gtk

events=gtk.gdk.Event(gtk.gdk.CLIENT_EVENT)
data=gtk.gdk.atom_intern("_GTK_READ_RCFILES", False)
events.data_format=8
events.send_event=True
events.message_type=data
events.send_clientmessage_toall()

END
}


if ! pacman -Qs pygtk >/dev/null 2>&1; then
  sudo pacman -S pygtk
  #required for reloadGTK
fi

if ! pacman -Qs xfconf >/dev/null 2>&1; then
  sudo pacman -S xfconf
  #required for reloadGTK
fi

if test "$#" -gt "1"; then
  echo "!! too many args" >&2
  exit 1
fi
setto="$1"

if test "$setto" == "auto" -o "$setto" == "off" -o "$setto" == "xpresent" -o "$setto" == "glx"; then
  args=( -s "$setto" )
elif test -z "$setto"; then
  args=()
else
  echo "!! unexpected arg '$setto'" >&2
  exit 2
fi

xfconf-query -c xfwm4 -p /general/vblank_mode "${args[@]}"
if test "${#args[@]}" -gt 0; then
  reloadGTK
  #now cause some xfwm4 event(compositing is picked randomly) so the above reloadGTK is seen by xfwm4:
  xfconf-query -c xfwm4 -p /general/use_compositing -s false
  xfconf-query -c xfwm4 -p /general/use_compositing -s true
fi
