aboutsummaryrefslogtreecommitdiff
path: root/tmuxrdr/plugin/bin/track-focus
blob: 4132891fb8e98640094e93cd548eda155f2067f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/bin/sh
# Event hook for tab.focused and workspace.focused: keeps the current and
# previous tab of each workspace, and the current and previous workspace, so
# `last window` and `last session` know where to go. Hooks run concurrently,
# so updates take a mkdir lock.
. "$(dirname "$0")/../lib.sh"

dir="$(state_dir)"
ev="${HERDR_PLUGIN_EVENT_JSON:-}"
[ -n "$ev" ] || exit 0

field() {
    printf '%s' "$ev" | jq -r --arg k "$1" '[.. | objects | .[$k]? | strings][0] // empty'
}

# record NAME VALUE: VALUE becomes NAME.current, the old one NAME.previous.
record() {
    [ -n "$2" ] || return 0
    cur="$(cat "$dir/$1.current" 2>/dev/null || true)"
    [ "$cur" = "$2" ] && return 0
    [ -n "$cur" ] && printf '%s\n' "$cur" >"$dir/$1.previous"
    printf '%s\n' "$2" >"$dir/$1.current"
}

tries=0
until mkdir "$dir/.lock" 2>/dev/null; do
    tries=$((tries + 1))
    [ "$tries" -gt 40 ] && break
    sleep 0.05
done
trap 'rmdir "$dir/.lock" 2>/dev/null' EXIT

case "${HERDR_PLUGIN_EVENT:-}" in
tab.focused) record "tab.$(key_of "$(field workspace_id)")" "$(field tab_id)" ;;
workspace.focused) record workspace "$(field workspace_id)" ;;
esac