#!/bin/sh

# This file is part of xresponse-visualize
#
# Copyright (C) 2005-2008 Nokia Corporation.
#
# Contact: Eero Tamminen <eero.tamminen@nokia.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA

# show help
if [ $# -ne 2 ]; then
	echo "A script to visualize damage areas from the Xresponse log."
	echo
	echo "Usage: $0 <screenshot.png> <xresponse.log>"
	exit
fi

# check tools
if [ -z $(which convert) ] || [ -z $(which identify) ] || [ -z $(which display) ]; then
	echo "ERROR: 'convert', 'identify' and 'display' tools are missing!"
	echo "Please install ImageMagick package first."
	exit
fi

# nicer names for the cli args
shot=$1
log=$2

# check screenshot image
if [ \! -f $shot ]; then
	echo "ERROR: Screenshot image missing!"
	exit
fi

# check whether the screenshot image is correct size
imgsize="800x480"
if [ x$(identify $shot|grep $imgsize|sed 's/^.*\(800x480\).*$/\1/') != x$imgsize ]; then
	echo "ERROR: Screenshot '$shot' is not '$imgsize' sized!"
	exit
fi

# get interesting part of the screenshot name (no path or extension)
name=${shot##*/}
name=${name%%.*}

idx=100
# go through each line in the Xresponse log
for geometry in $(grep "damage" $log|sed 's/^.*event \([0-9x+]*\).*$/\1/'); do
	# ignore lines which didn't match geometry pattern
	if [ -z $geometry ]; then
		continue
	fi
	save=$name-$idx.png
	echo "Processing '$geometry' (saved as '$save')..."
	convert -region $geometry -negate $shot $save
	idx=$(($idx+1))
done
idx=$(($idx-100))

echo
echo "$idx damage events processed to corresponding images."
echo
echo "You can view them with:"
echo "  display -delay 10 $name-*.png"
echo
echo "Or convert them to an animated GIF with:"
echo "  convert -delay 60 -loop 1 -colors 64 -geometry 400x240 '$name-*.png' anim.gif"
echo "so that they can e.g. easily be attached to Bugzilla..."

