#!/bin/sh -f
test $#* '=' 0 || {
	p="$PATH"
	which rc >/dev/null || PATH="$PLAN9:$p"
	which rc >/dev/null || PATH="/usr/local/plan9/bin:$p"
	which rc >/dev/null || PATH="/usr/local/9/bin:$p"
	which rc >/dev/null || PATH="/opt/plan9/bin:$p"
	which rc >/dev/null || PATH="/opt/9/bin:$p"
	which rc >/dev/null || PATH="/usr/plan9/bin:$p"
	which rc >/dev/null || PATH="/usr/9/bin:$p"
	exec rc $0
}

cd
scriptname=$0
oldpath=$path; path=($PLAN9/bin $path)
. wmii.rc wmiirc # Include utility functions

# WMII Configuration

# Keys
MODKEY=Mod4
UP=k
DOWN=j
LEFT=h
RIGHT=l

# Bars
noticetimeout=5
noticebar=/rbar/!notice

# Theme
wmiifont='drift,-*-fixed-*-*-*-*-9-*-*-*-*-*-*-*'
wmiifont='-*-fixed-medium-r-*-*-13-*-*-*-*-*-*-*'
wmiinormcol=('#000000' '#c1c48b' '#81654f')
wmiifocuscol=('#000000' '#81654f' '#000000')
wmiibackground='#333333'
wmiifloatbackground='#222222'
fn setbackground { xsetroot -solid $* }

# Programs
WMII_TERM=(xterm)

# Column Rules
wmiir write /colrules <<!
    /gimp/ -> 17+83+41
    /.*/ -> 62+38 # Golden Ratio
!

# Tagging Rules
wmiir write /rules <<!
    # Apps with system tray icons like to their main windows
    # Give them permission.
    /^Pidgin:/ allow=+activate

    # MPlayer and VLC don't float by default, but should.
    /MPlayer|VLC/ floating=on

    # ROX puts all of its windows in the same group, so they open
    # with the same tags.  Disable grouping for ROX Filer.
    /^ROX-Filer:/ group=0
!

# Status Bar Info
fn status {
	echo -n label `{uptime | sed 's/.*://; s/, / /g'} '|' \
		      `{date} }

# Generic overridable startup details
fn startup { witray & }

# End Configuration

# For the time being, this file follows the lisp bracing
# convention. i.e.:
#  if(frob this) {
#    frob that
#    if(frob theother) {
#      unfrob this
#      unfrob that}}
# Comments welcome.

confpath=`{echo $WMII_CONFPATH | sed 'y/:/ /'}

# Events
fn sigexit {
	rm -f $progs_file
	wi_cleankeys}

fn Event-CreateTag {
	echo colors $wmiinormcol $wi_newline label $* | wmiir create /lbar/$"*}
fn Event-DestroyTag {
	wmiir remove /lbar/$"*}
fn Event-FocusTag {
	wmiir xwrite /lbar/$"* colors $wmiifocuscol}
fn Event-UnfocusTag {
	wmiir xwrite /lbar/$"* colors $wmiinormcol}
fn Event-UrgentTag {
	shift
	wmiir xwrite /lbar/$"* label '*'$"*}
fn Event-NotUrgentTag {
	shift
	wmiir xwrite /lbar/$"* label $"*}
fn Event-AreaFocus {
	if(~ $1 '~')
		setbackground $wmiifloatbackground
	if not
		setbackground $wmiibackground }

fn Event-Unresponsive {
	client = $1; shift
	@{
		msg = 'The following client is not responding. What would you like to do?'
		resp = `{wihack -transient $client \
				xmessage -nearmouse -buttons Kill,Wait -print \
				$msg $wi_newline '' `{wmiir read /client/$client/label}}
		if(~ $resp Kill)
			wmiir xwrite /client/$client/ctl slay
	}&}
fn Event-Notice {
	wmiir xwrite $noticebar label $wi_arg

	/bin/kill $xpid >[2]/dev/null # Let's hope this isn't reused...
	{ sleep $noticetimeout; wmiir xwrite $noticebar ' ' }& # Bug...
	xpid = $apid}

fn Event-LeftBar^(Click DND) {
	shift; wmiir xwrite /ctl view $*}

fn ClientMenu-3-Delete {
	wmiir xwrite /client/$1/ctl kill}
fn ClientMenu-3-Kill {
	wmiir xwrite /client/$1/ctl slay}
fn ClientMenu-3-Fullscreen {
	wmiir xwrite /client/$1/ctl Fullscreen on}
fn Event-ClientMouseDown {
	wi_fnmenu Client $2 $1 &}

fn LBarMenu-3-Delete {
	tag=$1; clients=`{wmiir read /tag/$tag/index | awk '/[^#]/{print $2}'}
	for(c in $clients) {
		if(~ $tag `{wmiir read /client/$c/tags})
			wmiir xwrite /client/$c/ctl kill
		if not
			wmiir xwrite /client/$c/tags -$tag}
	if(~ $tag `{wi_seltag}) {
		newtag = `{wi_tags | awk -v't='$tag '
			$1 == t { if(!l) getline l
				  print l
				  exit }
			{ l = $0 }'}
		wmiir xwrite /ctl view $newtag}}
fn Event-LeftBarMouseDown {
	wi_fnmenu LBar $* &}

# Actions
fn Action-exec {
	wmiir xwrite /ctl exec $*}
fn Action-quit {
	wmiir xwrite /ctl quit}
fn Action-rehash {
	comm -23 <{ls `{namespace}^/proglist.* >[2]/dev/null | awk -F'.' '{print $NF}'} \
		 <{ps | awk '{print $2}'} |
	while(id=`{read})
		rm `{namespace}^/proglist.$id
	wi_proglist $PATH >$progs_file}
fn Action-showkeys {
	echo $wmiikeyhelp | xmessage -file -
}
fn Action-status {
	flag x -; flag r -
	if(wmiir remove /rbar/status >[2]/dev/null)
		sleep 2
	echo colors $wmiinormcol | wmiir create /rbar/status
	while(status | wmiir write /rbar/status)
		sleep 1
}

# Source Variables, &c
if(~ $0 ('' */)wmiirc_local.rc)
	wi_notice This file should not be named wmiirc_local.rc
if not
	. `{wi_script -f wmiirc_local.rc}
echo colors $wmiinormcol | wmiir create $noticebar
startup

# Key Bindings
_keys = `{wi_getfuns Key}
fn keygroup {
	wmiikeyhelp = $wmiikeyhelp ^ $wi_newline ^ '  ' ^ $"* ^ $wi_newline}
fn key {
	help=$1; shift
	key=()
	for(k) {
		if(! ~ $k $_keys) {
			ifs=() { wmiikeyhelp = `{
				printf "%s    %- 20s %s\n" $wmiikeyhelp $k $help}}
			key = ($key Key-$k)}}
	~ $#key 0}

keygroup Moving around
key 'Select the client to the left' $MODKEY-$LEFT || fn $key {
	wmiir xwrite /tag/sel/ctl select left}
key 'Select the client to the right' $MODKEY-$RIGHT || fn $key {
	wmiir xwrite /tag/sel/ctl select right}
key 'Select the client below' $MODKEY-$DOWN || fn $key {
	wmiir xwrite /tag/sel/ctl select down}
key 'Select the client above' $MODKEY-$UP || fn $key {
	wmiir xwrite /tag/sel/ctl select up}

key 'Toggle between floating and managed layers' $MODKEY-space || fn $key {
	wmiir xwrite /tag/sel/ctl select toggle}

keygroup Moving through stacks
key 'Select the stack below' $MODKEY-Control-$DOWN || fn $key {
	wmiir xwrite /tag/sel/ctl select down stack}
key 'Select the stack above' $MODKEY-Control-$UP || fn $key {
	wmiir xwrite /tag/sel/ctl select up stack}

keygroup Moving clients around
key 'Move selected client to the left' $MODKEY-Shift-$LEFT || fn $key {
	wmiir xwrite /tag/sel/ctl send sel left}
key 'Move selected client to the right' $MODKEY-Shift-$RIGHT || fn $key {
	wmiir xwrite /tag/sel/ctl send sel right}
key 'Move selected client down' $MODKEY-Shift-$DOWN || fn $key {
	wmiir xwrite /tag/sel/ctl send sel down}
key 'Move selected client up' $MODKEY-Shift-$UP || fn $key {
	wmiir xwrite /tag/sel/ctl send sel up}

key 'Toggle selected client between floating and managed layers' $MODKEY-Shift-space || fn $key {
	wmiir xwrite /tag/sel/ctl send sel toggle}

keygroup Client actions
key 'Toggle selected client''s fullsceen state' $MODKEY-f || fn $key {
	wmiir xwrite /client/sel/ctl Fullscreen toggle}
key 'Close client' $MODKEY-Shift-c || fn $key {
	wmiir xwrite /client/sel/ctl kill}

keygroup Changing column modes
key 'Set column to default mode' $MODKEY-d || fn $key {
	wmiir xwrite /tag/sel/ctl colmode sel default-max}
key 'Toggle between floating and managed layers' $MODKEY-s || fn $key {
	wmiir xwrite /tag/sel/ctl colmode sel stack-max}
key 'Set column to max mode' $MODKEY-m || fn $key {
	wmiir xwrite /tag/sel/ctl colmode sel stack+max}

keygroup Running programs
key 'Open wmii actions menu' $MODKEY-a || fn $key {
	Action `{wi_actions | wimenu -h $hist.action -n $histlen} &}
key 'Open program menu' $MODKEY-p || fn $key {
	ifs=() { cmd = `{wimenu -h $hist.prog -n $histlen <$progs_file} }
	wi_runcmd $cmd & }

key 'Launch a terminal' $MODKEY-Return || fn $key {
	wi_runcmd $WMII_TERM &}

keygroup Other
key 'Toggle all other key bindings' $MODKEY-Control-t || fn $key {
	switch(`{wmiir read /keys | wc -l}) {
	case 0 1
		wmiir xwrite /keys $keys
		wmiir xwrite /ctl grabmod $MODKEY
	case *
		ifs=() { keys=`{wmiir read /keys} }
		wmiir xwrite /keys $MODKEY-Control-t
		wmiir xwrite /ctl grabmod Mod3
	}}

keygroup Tag actions
key 'Change to another tag' $MODKEY-t || fn $key {
	tag=`{wi_tags | wimenu -h $hist.tag -n 50} && wmiir xwrite /ctl view $tag &}
key 'Retag the selected client' $MODKEY-Shift-t || fn $key {
	sel=`{wi_selclient} {
	tag=`{wi_tags | wimenu -h $hist.tag -n 50} && wmiir xwrite /client/$sel/tags $tag } &}
key 'Move to the next tag' $MODKEY-n || fn $key {
	wmiir xwrite /ctl view `{wi_tags | wi_nexttag}}
key 'Move to the previous tag' $MODKEY-b || fn $key {
	wmiir xwrite /ctl view `{wi_tags | sort -r | wi_nexttag}}

key 'Move to the numbered view' $MODKEY-^`{seq 0 9} || fn $key {
	wmiir xwrite /ctl view `{echo $1 | sed 's/.*-//'}}
key 'Retag selected client with the numbered tag' Shift-$MODKEY-^`{seq 0 9} || fn $key {
	wmiir xwrite /client/sel/tags `{echo $1 | sed 's/.*-//'}}
# WM Configuration
wmiir write /ctl <<!
	grabmod $MODKEY
	border 2
	font $wmiifont
	focuscolors $wmiifocuscol
	normcolors $wmiinormcol
!
setbackground $wmiibackground

# Source Overrides
Action overridekeys

# Misc Setup
progs_file=`{namespace}^/proglist.$pid
hist=`{echo $WMII_CONFPATH | sed 's,:.*,/,'}^/history
histlen=5000
Action status &
Action rehash &

# Tag Bar Setup
ifs=$wi_newline {
	rc -c 'wmiir rm /lbar/^$*' >[2]/dev/null \
		`{comm -23 <{wmiir ls /lbar} \
			   <{wi_tags}}
	seltag=`{wi_seltag}
	for(tag in `{wi_tags}) {{
		if(~ $tag $seltag)
			echo colors $wmiifocuscol $wi_newline label $tag
		if not
			echo colors $wmiinormcol $wi_newline label $tag
		} | wmiir create /lbar/$tag}}
wi_eventloop
