#!/usr/bin/env bash # Modified from the script at: # https://gist.github.com/fdietze/6768a0970d7d732b7fbd7930ccceee2a # The next line has been commented because if there's nothing in clipboard the script breaks. # set -Eeuo pipefail # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/#:~:text=set%20%2Du,is%20often%20highly%20desirable%20behavior. shopt -s expand_aliases if [[ $# -ne 2 ]]; then echo "Usage: $0 \"application name\" \"file name\"." exit 1 fi # Wait for the application to start while ! pgrep -u "$USER" ^$1 &> /dev/null ; do sleep 0.05 done fileName="${2,,}" fileName="${fileName//[[:space:]]/-}.sqlite" translationFile="${XDG_CACHE_HOME:-$HOME/.cache}/audiogame-manager/${fileName}" # Make sure the directory exists mkdir -p "$(dirname "$translationFile")" # Initialize database if it doesn't exist if [[ ! -s "$translationFile" ]]; then rm -f "$translationFile" sqlite3 "$translationFile" < /dev/null ; do sleep 0.05 text="$(xclip -d "${DISPLAY:-:0}" -selection clipboard -o 2> /dev/null)" if [[ -f ~/.agmsilent ]]; then continue fi if [[ "${text}" =~ ^[0-9A-Za-z[:space:][:punct:]]+$ ]]; then spd-say -- "$text" echo "" | xclip -d "${DISPLAY:-:0}" -selection clipboard 2> /dev/null continue fi if [[ -z "$text" ]]; then continue fi # https://en.wikipedia.org/wiki/Unicode_equivalence#Combining_and_precomposed_characters # https://www.effectiveperlprogramming.com/2011/09/normalize-your-perl-source/ alias nfc="perl -MUnicode::Normalize -CS -ne 'print NFC(\$_)'" # composed characters # Normalize different unicode space characters to the same space # https://stackoverflow.com/a/43640405 alias normalize_spaces="perl -CSDA -plE 's/[^\\S\\t]/ /g'" alias normalize_unicode="normalize_spaces | nfc" # Normalize text normalized_text="$(echo "$text" | normalize_unicode)" # Create a temporary database for import sqlite3 "$translationFile" "CREATE TABLE IF NOT EXISTS temp_import(text TEXT, translation TEXT);" # Check if we already have a translation translated=$(sqlite3 "$translationFile" "SELECT translation FROM translations WHERE text = '$normalized_text' LIMIT 1;" 2>/dev/null) if [[ -z "$translated" ]]; then # Get translation from the trans utility translated="$(trans -no-autocorrect -no-warn -brief "$normalized_text" | head -1 | sed 's/\s*$//' | normalize_unicode)" if [[ -n "$translated" ]]; then # Insert using echo piping to avoid escaping issues echo "$normalized_text|$translated" | sqlite3 -separator "|" "$translationFile" ".import /dev/stdin temp_import" sqlite3 "$translationFile" "INSERT OR IGNORE INTO translations SELECT * FROM temp_import; DELETE FROM temp_import;" fi fi # If we got a translation, speak it if [[ -n "$translated" ]]; then spd-say -- "$translated" fi # Clear clipboard echo "" | xclip -d "${DISPLAY:-:0}" -selection clipboard 2> /dev/null done exit 0