#!/bin/sh
#
# Workspaces for ratpoison
# Copyright (C) 2003 Shawn Betts
# Author: Shawn Betts
#
# To enable workspaces, put the following lines in your .ratpoisonrc
# file:
#
# exec rpws -i
# exec rpws -b
#
# The first line initializes the workspaces (never call this more than
# once or it will clutter ratpoison with duplicate window groups). The
# second line sets up some keybindings:
#
# C-t M-1 Workspace 1
# C-t M-2 Workspace 2
# ...
# C-t M-7 Workspace 7
#
# You want more workspaces? Edit this script.
#

#
# Code:
#

# This allows outside scripts to tell this script where to find
# ratpoison.
if [ -z "$RATPOISON" ]; then
    RATPOISON=ratpoison
fi

rp_call ()
{
    $RATPOISON -c "$*"
}

ws_init_ws ()
{
    rp_call gnew ws$1
    rp_call setenv fs$1 `rp_call fdump`
}

ws_init ()
{
    # Backup the frames
    FS=`rp_call fdump`
    if [ -z "$FS" ]; then
        exit
    fi
    rp_call select -
    rp_call only

    # Make 6 workspaces
    ws_init_ws 2
    ws_init_ws 3
    ws_init_ws 4
    ws_init_ws 5
    ws_init_ws 6
    ws_init_ws 7

    # Workspace 1 uses the 'default' group.
    # Start in workspace 1.
    rp_call gselect default
    FDUMP=`rp_call fdump`
    if [ -z "$FDUMP" ]; then
        exit
    fi
    rp_call setenv fs1 $FDUMP
    rp_call setenv ws 1

    # restore the frames
    rp_call frestore $FS
}

ws_save ()
{
    WS=`rp_call getenv ws`
    if [ -z "$WS" ]; then
        exit
    fi
    FDUMP=`rp_call fdump`
    if [ -z "$FDUMP" ]; then
        exit
    fi
    rp_call setenv fs$WS $FDUMP
}

ws_restore ()
{
    ws_save
    if [ "X${1}" = X"1" ]; then
	rp_call gselect default
    else
	rp_call gselect ws$1
    fi

    FS=`rp_call getenv fs$1`
    if [ -z "$FS" ]; then
	exit
    fi
    rp_call echo Workspace $1
    rp_call frestore $FS
    rp_call setenv ws $1
}

ws_bindings ()
{
    # Use $0 so we know the name and location of the script to call.
    rp_call bind M-1 exec $0 1
    rp_call bind M-2 exec $0 2
    rp_call bind M-3 exec $0 3
    rp_call bind M-4 exec $0 4
    rp_call bind M-5 exec $0 5
    rp_call bind M-6 exec $0 6
    rp_call bind M-7 exec $0 7
}

if [ -z "$@" ]; then
    echo "Usage:"
    echo "$0 -i      -- initialize the workspaces"
    echo "$0 -b      -- setup some key bindings"
    echo "$0 <n>     -- Switch to workspace n"
else
    if [ "X${1}" = X"-i" ]; then
	ws_init
    elif [ "X$1" = X"-b" ]; then
	ws_bindings
    else
	ws_restore $1
    fi
fi
