dotfiles/.local/bin/dmenugtranslate

33 lines
1.0 KiB
Bash
Executable File

#!/bin/sh
text=$(xclip -o -selection clipboard)
map=~/.local/share/dabruh/gtranslate-lang-map
# Get user selection via dmenu from language map file.
from=$(cut -d '=' -f1 "$map" | dmenu -i -l 30 -p "Translate from")
[ -z "$from" ] && exit 1
from_code="$(grep "^$from=" "$map" | cut -d '=' -f2)"
to=$(cut -d '=' -f1 "$map" | grep -v Automatic | dmenu -i -l 30 -p "Translate to")
[ -z "$to" ] && exit 1
to_code="$(grep "^$to=" "$map" | cut -d '=' -f2)"
translation="$(curl --silent --get \
--data-urlencode "from=$from_code" \
--data-urlencode "to=$to_code" \
--data-urlencode "text=$text" \
"http://localhost:5000/api")"
rc=$?
if [ $rc -ne 0 ]; then
e="Translation from $from_code to $to_code failed. Input: '$text'"
notify-send "$e" &
echo "ERROR: $e" 1>&2
exit 2
fi
echo "$translation"
printf '%s' "$translation" | xclip -selection clipboard
notify-send "Translation from $from_code to $to_code copied to clipboard." &
alacritty --class translation -e bash -c "echo '$translation' | less" &