#!/bin/zsh
# Usage:
#
# runon <workspace> <command...>
#
# This will run the given command, then move the resulting window to the
# workspace specified. There are two formats for workspace:
# +n or -n: Move the window n desktops to the right (+) or left (-)
# name: Move the window to the desktop with the given name
#
# Check for the required parameters
if [ $# -lt 2 ]
then
echo 'Workspace and command are required.' >&2
exit 1
fi
# Get the workspace from the arguments, then remove it
workspace=$1; shift 1
# If the workspace starts with a + or a -, assume it's an offset
if [[ "$workspace" =~ '^[+-][[:digit:]]*$' ]]
then
# Get the current desktop id
wmctrl -d | awk "/*/ {print \$1}" | read current
# Add the offset to that id
desk=$((current + workspace))
# If that desktop id does not exist, error out
if ! wmctrl -d | grep -q "^$desk"
then
echo "Offset does not resolve to a valid workspace" >&2
exit 1
fi
else
# Resolve a workspace to desktop id
if ! wmctrl -d | awk "{if (\$9 == \"$workspace\") print \$1}" | read desk
then
# If that fails, error out
echo "Unknown workspace $workspace" >&2
exit 1
fi
fi
# Start the command, capturing its PID
$@ &; pid=$!
# Loop while that command is running
while jobs %1
do
# If it has any windows, move them to the requested workspace then
# terminate the loop
if wmctrl -l -p | awk "{if (\$3 == $pid) print \$1}" | read xid
then
wmctrl -i -r $xid -t $desk
break
fi
# Wait a little while for a window
sleep 1
done &>/dev/null &
# Wait for the command to exit
wait %1 &>/dev/null