#!/bin/sh

# read resolution from xrandr: "1920x1080     60.03*+"
RES=$(xrandr | grep "*+" | awk '{print $1}')

# parse xrandr output
RESH=${RES%x*}
RESV=${RES#*x}

# calculate pixel gap that should surround the window
GAP=$(( RESH / 12 ))

# Calculate the horzontal/vertical dimensions of the window
H=$(( RESH - 2 * GAP ))
V=$(( RESV - 2 * GAP ))

# set the quirk in .config/spectrwm/spectrwm.conf
# quirk[scratchpad] = FLOAT + ANYWHERE + FOCUSPREV

# get scratchpad window id
WID=$(wmctrl -x -l scratchpad | fgrep '.scratchpad' | cut -d" " -f1)

if [ -z "$WID" ]
then
    # start terminal (sterm is st.suckless.org)
    sterm -c scratchpad -g 134x29+$GAP+$GAP &
    # XXX we cannot resize with wmctrl here, because the window is not
    # mapped yet. Adding a sleep here and resize then is visually
    # unpleasant. Therefore st is started with hardcoded dimensions
    # and resized when hidden.
else
    # check if window is iconified or on another WS (or both)
    if xwininfo -id $WID | fgrep -q IsUnMapped
    then
        # move window to current workspace
        [ -z $_SWM_WS ] \
            && wmctrl -i -r $WID -t $(xprop -root _NET_CURRENT_DESKTOP | cut -d'=' -f2) \
            || wmctrl -i -r $WID -t $_SWM_WS
        # remove hidden flag
        wmctrl -i -r $WID -b remove,hidden
        # activate (give focus)
        wmctrl -i -a $WID
    else
        # window is visible => hide
        wmctrl -i -r $WID -b add,hidden
        # correct size while hidden
        wmctrl -i -r $WID -e 0,$GAP,$GAP,$H,$V
        # move it beyond the WS limit to completely hide it from the bar
        # XXX could also be skip_pager / skip_taskbar?
        wmctrl -i -r $WID -t 11
    fi
fi
