Fix for input being received by wrong window (qubes.RefocusWin)

I have created a fix for input focus being received by the wrong window in a VM. This happens mainly when opening a file in thunar. When the file opens in mousepad the thunar window still appears to be focused but any keyboard/mouse input is received by mousepad.

To fix this a script of the same application name needs to be created in /usr/local/bin

#!/bin/sh
 
bin='/usr/bin/mousepad'
 
if [ -x "$bin" ]; then
        num="$(pgrep -cf "$bin")"
 
        if [ $# -eq 0 ] && [ $num -eq 0 ]; then
                ("$bin" >/dev/null 2>/dev/null &)
                exit 0
        fi
 
        if [ $num -ne 0 ]; then
                "$bin" "$@" >/dev/null 2>/dev/null
                qrexec-client-vm dom0 qubes.RefocusWin
        else
                (qrexec-client-vm dom0 qubes.RefocusWin+wait &)
                ("$bin" "$@" >/dev/null 2>/dev/null &)
        fi
fi

The script must override the original binary so make sure that /usr/local/bin comes before the original binary’s directory in $PATH. If the program’s full path appears in its .desktop file then it also needs to be updated.

Then in dom0 create a new rpc service in /etc/qubes-rpc called qubes.RefocusWin

#!/bin/bash
IFS=''; set -eu

export DISPLAY=:0

wait_for_window_change() {
	while [ 1 ]; do
		sleep 0.1s
		[ "$(xdotool getactivewindow)" != "$1" ] && break
	done
}

winid="$(xdotool getactivewindow)"
if [ "$QREXEC_SERVICE_ARGUMENT" = 'wait' ]; then
	wait_for_window_change "$winid"
fi
xdotool windowfocus 'Desktop' windowfocus "$winid"

After that add these lines to the policy files in dom0.

qubes.RefocusWin * @anyvm dom0 allow
qubes.RefocusWin * @anyvm @anyvm deny

This fix expects that new files are opened in new tabs in the same application.