#!/bin/dash

# fatdog-shortcut-viewer.sh - show keyboard and mouse shortcuts
# Copyright (C) step, 2020-2022
# License: GNU GPL Version 2
Version=1.2.0

export TEXTDOMAIN=fatdog
export OUTPUT_CHARSET=UTF-8

################
#  Initialize  #
################

FONTNAME='Monospace 12' FGCOLOR='#000000' BGCOLOR='#e5eaeb'

# This script always adds itself to the user's Startup folder, and sets its 'x'
# bit according to the value of a gui checkbox. The system Startup folder is
# only looked at if the user's Startup script doesn't exist.
autostart="$HOME/Startup/${0##*/}"
if ! [ -e "$autostart" ]; then
	autostart="/etc/xdg/Startup/${0##*/}"
	[ -e "$autostart" ] || unset autostart
fi
# Initial checkbox value 0/1
[ -x "$autostart" ]; autostart=$((!$?))

# Set traps and create temporary folder
TMPD="${TMPDIR:-/tmp}/$USER-${0##*/}"
mkdir -p "$TMPD"
chmod 700 "$TMPD" || exit 1
trap "rm -rf \"$TMPD\"/* \"$TMPD\"; exit" HUP INT QUIT TERM ABRT 0

. "${0%.sh}"-lib.sh

##############
#  Get data  #
##############{{{

bindingsf="$TMPD/bindings.bsv"
countersf="$TMPD/counters"
ctx_any=''
sep=`printf "\b"`

exec 3> "$bindingsf"

provider="$(gettext 'o|Openbox window manager')"
get_openbox_config "$provider" "$ctx_any" "$sep" >&3
echo "<counter>$provider$sep$OPENBOX_CONFIG" >&3

provider="$(gettext 'd|Dunst notification manager')"
get_dunst_config "$provider" "$ctx_any" "$sep" >&3
echo "<counter>$provider$sep$DUNST_CONFIG" >&3

provider="$(gettext 's|Sven hotkey manager')"
get_sven_config "$provider" "$ctx_any" "$sep" >&3
echo "<counter>$provider$sep$SVEN_CONFIG" >&3

exec 3>&-

## count entries by provider
exec 3> "$countersf"1

prev=1 i=1
while read line; do
	case $line in
		"<counter>"* )
			line="${line#"<counter>"}"
			echo "$(($i - $prev))$sep${line%%|*}$sep${line#*|}" >&3
			prev=$i
			continue
			;;
		* )
			echo "$line"
			;;
	esac
	i=$(($i +1))
done < "$bindingsf" > "$bindingsf"1

exec 3>&-

## sort bindings by device index (0=keyboard 1=mouse)
sort -s -t "$sep" -k1,1n -o "$bindingsf" "$bindingsf"1

## sort providers by descending count
sort -s -t "$sep" -k1,1nr -o "$countersf" "$countersf"1

#############}}}
#  Content  #
#############{{{

exec 3> "$TMPD/text.in"
{
	# column names with '2' in column 1
	echo "2|$(gettext 'PROVIDER|CONTEXT|SHORTCUT|ACTIONS')" | sed -e "s/|/$sep/g"

	# column data with device index ('0', '1') in column 1
	cat "$bindingsf"
} |
	column -t -s "$sep" |
	awk -F"$sep" \
		-v G0="$(gettext "KEYBOARD")" \
		-v G1="$(gettext "MOUSE")" \
		-v G0t="$(gettext "Abbreviated modifiers: A-/Alt   C-/Control   S-/Shift   W-/Window")" \
		-v G0m="$(gettext "C-A-Left means press modifiers Control and Alt, and key Left-arrow together")" \
		-v G0b="$(gettext "For the meaning of ACTIONS refer to PROVIDER's own documentation")" \
		-v G1t="$(gettext "CONTEXT means where to place the pointer before initiating an ACTION")" \
		-v G1m="$(gettext "Then Click, Press, Drag, etc. the SHORTCUT button (and modifier)")" \
		-v G1b="$(gettext "Buttons: Left/primary(1), Middle(2), Right/opposite(3) and more (4, 5,...)")" \
'#{{{awk
# Output group headers and column names
/^2/                { colnames = $0; sub(/2[[:blank:]]+/, "", colnames); next }
/^0/ && group != G0 { group = G0; print box(group, G0t, G0m, G0b) "\n"column_names() }
/^1/ && group != G1 { group = G1; print "\n"box(group, G1t, G1m, G1b) "\n"column_names() }
function box(s, st, sm, sb,   l, t, b, r) {
	l = length(s) +2
	r = sprintf("% "l"s", " ")
	t = "╭" r "╮"
	s = "│ "s" │"
	b = "╰" r "╯"
	r = "│" r "│"
	# ┐┘└┌
	gsub(/ /, "─", t)
	gsub(/ /, "─", b)
	return t"\n" r" "st"\n" s" "sm"\n" r" "sb"\n" b
}

function column_names(   s) {
	s = colnames
	gsub(/[^[:blank:]]/, "=", s)
	return colnames "\n" s
}

# Delete device field
{ sub(/^[[:digit:]]+[[:space:]]+/, "") }

{ print }

#awk}}}' >&3

printf '\n\n' >&3
colnames="$(gettext 'COUNT|PROVIDER|NAME|CONFIGURATION')"
awk -v COLS="$colnames" -v SEP="$sep" '
BEGIN {
	gsub(/\|/, SEP, COLS)
	u = COLS
	gsub("[^ "SEP"]", "=", u)
	{ print COLS; print u }
}
{ print }' "$countersf" |
	column -t -s "$sep" >&3

printf '\n\n%s\n\n%s %s' >&3 \
	"$(gettext 'To save a cheat sheet copy+paste this page to a text file')" \
	"${0##*/}" "$Version" \
	;
exec 3>&-

############}}}
#  Dialog  #
############{{{

# $stock_btn is the prefix of stock buttons; it varies by yad version
yad='yad' stock_btn='gtk' # yad -> yad_gtk2 and yad_gtk3
#yad='yadu' stock_btn='yad'     # yad_ultimate

win_width=$(gettext fatdog_shortcut_viewer_window_width=760); win_width=${win_width#*=}
win_height=$(gettext fatdog_shortcut_viewer_window_height=400); win_height=${win_height#*=}

YAD_OPTIONS="
	--title=\"$(gettext 'Shortcut Viewer')\"
	--window-icon=\"/usr/share/pixmaps/midi-icons/keyboard+mouse48.png\"
	--buttons-layout=center
	--center --width=$win_width --height=$win_height
	--bool-fmt=1
"
YAD_OPTIONS="$YAD_OPTIONS
	--form --separator=
	--field=\"$(gettext 'Load this dialog when X starts'):CHK\" ${autostart:-0}
" $yad --plug=$$ --tabnum=1 > "$TMPD/autostart" &

YAD_OPTIONS="$YAD_OPTIONS
	--text-info
	--fontname=\"$FONTNAME\"
	--fore=\"$FGCOLOR\" --back=\"$BGCOLOR\"
" $yad --plug=$$ --tabnum=2 < "$TMPD/text.in" &
# don't use --filename with yad_gtk2 because it conflicts with --back

YAD_OPTIONS="$YAD_OPTIONS
	--text=\"$(gettext '<b><big>Predefined keyboard and mouse shortcuts</big></b>')\"
	--text-align=center
	--button=$stock_btn-ok
" $yad --key=$$ --paned &

###################}}}
#  Save and exit  #
###################

wait

if [ 0 = $? -a -s "$TMPD"/autostart ] &&
	read autostart < "$TMPD"/autostart
then
	# Create user's autostart
	p="$HOME/Startup/${0##*/}"
	printf "exec '%s'\n" "$(realpath "$0")" > "$p" &&
		[ "$autostart" -eq 1 ] &&
		chmod +x "$p" || chmod -x "$p"
fi

