dotfiles/bin/d
2020-11-05 12:24:36 +08:00

86 lines
2.4 KiB
Bash
Executable File

#!/bin/sh
# shellcheck disable=2086,2059
# dmenu optional patches: preselect / center
# fzf selector: 'fzf --reverse --height=30%%'
set -e
DIR="$(readlink -f "$(dirname "$0")")"
# compose selector command if not specified
if [ -z "$SELECTOR" ]; then
if command -v dmenu >/dev/null; then
SELECTOR='dmenu -i -fn monospace:13 -nb #626262 -nf #bbbbbb -sb #5b97f7 -sf #eeeeee -l 20'
dmenu -h 2>&1 | grep -qF ' [-n number]' && SELECTOR="$SELECTOR -n %i"
dmenu -h 2>&1 | grep -qP '\[-\w*c\w*\]' && SELECTOR="$SELECTOR -c"
elif command -v fzf >/dev/null; then
SELECTOR='fzf --reverse --height=30%%'
else
echo 'require either dmenu or fzf'
exit 1
fi
fi
EMPTY_RESULT=' 查无结果'
GREETING='﬜ 请输入单词并回车'
request() {
RESULT="$(
curl -SsLG "http://dict.youdao.com/w/eng/$SENTENCE/" \
| awk -v PI=' ' -f "$DIR/dict.awk"
)"
display
}
pronounce() {
PLAY=afplay
! command -v "$PLAY" 2>/dev/null && PLAY="ffplay -nodisp -autoexit"
FP="/tmp/dict/$*.mp3"
mkdir -p /tmp/dict
[ ! -f "$FP" ] && curl -o "$FP" "http://dict.youdao.com/dictvoice?audio=$1&type=$2" 1>/dev/null 2>&1
$PLAY "$FP" 1>/dev/null 2>&1
}
display() {
R="$RESULT"
if [ -z "$R" ]; then
if [ -n "$SENTENCE" ]; then
R="$EMPTY_RESULT : $SENTENCE"
else
R="$GREETING"
fi
fi
SELECT=$(printf "$SELECTOR" "$LINE_NUM")
echo "$R" \
| $SELECT \
| if IFS= read -r INPUT; then
if echo "$INPUT" | grep -qP ' '; then
if echo "$INPUT" | grep -q '美'; then
pronounce "$SENTENCE" 2 &
else
pronounce "$SENTENCE" 1 &
fi
echo awk '"'$INPUT'" { print NR }'
LINE_NUM=$(echo "$RESULT" | awk -v INPUT="$INPUT" '$0==INPUT { print NR - 1 }')
display $LINE_NUM
elif echo "$INPUT" | grep -qF "$EMPTY_RESULT" || echo "$INPUT" | grep -qF "$GREETING"; then
return
elif echo "$INPUT" | grep -qP '^ '; then
printf "%s" "$INPUT" | sed 's/^\s+//' | xsel -b
else
SENTENCE="$INPUT"
request
fi
fi
}
SENTENCE="$*"
if [ -n "$SENTENCE" ]; then
request
else
display
fi
#pronounce "$@"