#!/bin/bash
#This script simulates a 2D grid of workspaces with i3.
#all you have to do is add the next line to your i3/config
#bindsym <keys> exec <path>/i3/workspaces.sh <direction> [move win]
#for example,
#bindsym Control+Mod1+Right exec ~/.config/i3/workspaces.sh right
#if you want to move the window with you when you switch workspaces,
#add another argument to the command
#./workspaces.sh right move
#(it doesn't have to be move, any argument at all will work)
#Here's the configuration of columns and rows
MAX_rows=2
MAX_cols=3
#how to get workspaces
#workspaces="$(i3-msg -t get_workspaces)"
#to learn more about using bash to interact with i3, 'man i3-msg'
#Step 1: get current workspace
#get array of workspaces thing. messy array but idk what i'm doing
d=($(i3-msg -t get_workspaces|grep -oP '[,\s"]+\K.*?(?=")'))
#loop through that array
for i in `seq 0 ${#d[@]}`; do
if [ "${d[$i]}" = ":true," ]; then
if [ "${d[$i - 4]}" = "name" ]; then
cur=${d[$i - 2]}; #number of current workspace
fi
fi
done
echo CUR $cur #for the sake of debugging
#Step 2: turn workspace number into vertical and horizontal coordinates
curv=$((($cur - 1) / $MAX_cols + 1));
curh=$(($cur % $MAX_cols));
if [ $curh -eq 0 ]; then
curh=3;
fi
echo CURRCORDS $curh, $curv #for the sake of debugging
#Step 3: Determine direction moving, and create new coordinates
tov=$curv;
toh=$curh;
case "$1" in #$1 is the direction we're moving. change the x|y coord accordingly
"right" ) toh=$(($curh + 1));;
"left" ) toh=$(($curh - 1));;
"up" ) tov=$(($curv - 1));;
"down" ) tov=$(($curv + 1));;
esac
#these IFs give boundaries.
#if x|y is past boundary,
#then value is set to that boundary.
if [ $tov -lt 1 ]; then #x must be >= 1
tov=1
fi
if [ $toh -lt 1 ]; then #y must be >= 1
toh=1;
fi
if [ $toh -gt $MAX_cols ]; then #y must be <= $MAX_cols
toh=$MAX_cols;
fi
if [ $tov -gt $MAX_rows ]; then #x must be <= $MAX_rows
tov=$MAX_rows;
fi
echo TOCOORDS $toh, $tov; #for the sake of debugging
#Step 4: convert x,y coordinate to workspace number
to=$(($toh + ( $tov - 1 ) * $MAX_cols));
echo TO $to #which workspace to switch to
#Step 5: switch to that workspace
if [ $# -gt 1 ];then #if there's a second argument (i.e. 'move') then take window with you
i3-msg -t command move container to workspace $to;
i3-msg -t command workspace $to;
else #else just move the workspace
i3-msg -t command workspace $to;
fi