#!/bin/sh
#
# translate.sh (C) 2003 Malte J. Wetz <mail@malte-wetz.de>
#
# Windows-User may know the Babylon Translator. This is basically
# the same for linux, only better :)
#
# This script takes the current content of the X-Selection
# (the "clipboard") and tries to translate it.
# The translation is then displayed in a message box.
#
# The idea behind this is that you can use a hotkey manager
# like xbindkeys, LinEAK or hotkeys to call translate.sh. You
# can then translate the word currently selected in X11
# automagically.
#
# Programs required:
#   o xsel <http://www.niksula.cs.hut.fi/~vherva/xsel>
#   o dict command line client <http://www.dict.org>
#   o Xdialog <http://xdialog.dyns.net>
#   o or, instead of Xdialog: kdialog (part of KDE)
#
# Last change: 12.01.2004
#

TMPFILE=/tmp/translate.$$.tmp

# Get the selected text
WORD=`xsel -p`
[ -z "$WORD" ] && {
  Xdialog --msgbox "You have not selected any text." 6 30
  exit 1
}

# Translate it!
dict -P cat "$WORD" > $TMPFILE

# Now, if the "$WORD" really consisted of two or more words
# (like "fairy tale") and there was no match, try again with
# seperate words
x1=`grep '^No definitions found' $TMPFILE`
x2=`echo $WORD | grep '[[:alpha:]][[:space:]][[:alpha:]]'`
[ -z "$x1" -o -z "$x2" ] || dict -P cat $WORD > $TMPFILE


# recode temp file from utf-8 to latin1
recode -f utf-8..latin1 $TMPFILE

# Show translation
#Xdialog --textbox "$TMPFILE" 20 70
kdialog --textbox "$TMPFILE" 550 250

# remove the temp file
rm -f "$TMPFILE"

