#!/bin/sh

#	GrabOCR - a frontend utility to OCR screenshots
#
#	Copyright Mikko Rauhala <mjr@iki.fi>, 2008
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar at
# http://sam.zoy.org/wtfpl/COPYING and reproduced here:
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#                    Version 2, December 2004
#
# Copyright (C) 2004 Sam Hocevar
#  14 rue de Plaisance, 75014 Paris, France
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
#  0. You just DO WHAT THE FUCK YOU WANT TO. 

TMPDIR="`mktemp -dt grabocr.XXXXXXXXXX`" || exit 1
PICFILE="$TMPDIR/grabocr.ppm"
TXTFILE="$TMPDIR/grabocr.txt"

PROMPT=1
CLIDUMP=0

suicide()
{
	rm -rf "$TMPDIR"
	exit $1
}

if [ "a$DISPLAY" = "a" ]; then
	echo "No DISPLAY set; grabocr needs an X display." 1>&2
	suicide 1
fi

while [ "a$1" != "a" ]; do
	if [ "a$1" = "a-q" ]; then
		PROMPT=0
		shift
	elif [ "a$1" = "a-t" ]; then
		CLIDUMP=1
		shift
	else
		echo "Usage: grabocr [-q] [-t]" 1>&2
		suicide 1
	fi
done

if [ "a$PROMPT" = "a1" ]; then
	zenity --info --title "GrabOCR" --text "After closing this dialog, choose a window (left button click) or an area (right button drag) to OCR." || suicide 1
fi

# We scale up by 200%, slightly better recognition...
if ! scrot -s --exec 'mogrify -scale 200% $f' "$PICFILE"; then
	zenity --warning --title "GrabOCR aborted" --text "GrabOCR was aborted by a keypress."
	suicide 0
fi

if [ "a$CLIDUMP" = "a1" ]; then
	gocr -f UTF8 "$PICFILE"
else
	gocr -f UTF8 "$PICFILE" > "$TXTFILE"
	zenity --width 800 --height 600 --text-info --editable --title "GrabOCR results" --filename "$TXTFILE" > /dev/null
fi

suicide 0
