bgnotify.plugin.zsh
5314 bytes
1#!/usr/bin/env zsh
2
3## Setup
4
5[[ -o interactive ]] || return # don't load on non-interactive shells
6[[ -z "$SSH_CLIENT" && -z "$SSH_TTY" ]] || return # don't load on a SSH connection
7
8zmodload zsh/datetime # faster than `date`
9
10
11## Zsh Hooks
12
13function bgnotify_begin {
14 bgnotify_timestamp=$EPOCHSECONDS
15 bgnotify_lastcmd="${1:-$2}"
16}
17
18function bgnotify_end {
19 {
20 local exit_status=$?
21 local elapsed=$(( EPOCHSECONDS - bgnotify_timestamp ))
22
23 # check time elapsed
24 [[ $bgnotify_timestamp -gt 0 ]] || return 0
25 [[ $elapsed -ge $bgnotify_threshold ]] || return 0
26
27 # check if Terminal app is not active
28 [[ $(bgnotify_appid) != "$bgnotify_termid" ]] || return 0
29
30 bgnotify_formatted "$exit_status" "$bgnotify_lastcmd" "$elapsed"
31 } always {
32 bgnotify_timestamp=0
33 }
34}
35
36autoload -Uz add-zsh-hook
37add-zsh-hook preexec bgnotify_begin
38add-zsh-hook precmd bgnotify_end
39
40
41## Functions
42
43# allow custom function override
44(( ${+functions[bgnotify_formatted]} )) || \
45function bgnotify_formatted {
46 local exit_status=$1
47 local cmd="$2"
48
49 # humanly readable elapsed time
50 local elapsed="$(( $3 % 60 ))s"
51 (( $3 < 60 )) || elapsed="$((( $3 % 3600) / 60 ))m $elapsed"
52 (( $3 < 3600 )) || elapsed="$(( $3 / 3600 ))h $elapsed"
53
54 [[ $bgnotify_bell = true ]] && printf '\a' # beep sound
55 if [[ $exit_status -eq 0 ]]; then
56 bgnotify "#win (took $elapsed)" "$cmd"
57 else
58 bgnotify "#fail (took $elapsed)" "$cmd"
59 fi
60}
61
62function bgnotify_appid {
63 if (( ${+commands[lsappinfo]} )); then
64 lsappinfo info -only bundleid "$(lsappinfo front)" | awk -F= '{print $2}' | tr -d '"' 2>/dev/null
65 elif (( ${+commands[osascript]} )); then
66 osascript -e "tell application id \"$(bgnotify_programid)\" to get the {id, frontmost, id of front window, visible of front window}" 2>/dev/null
67 elif [[ -n $WAYLAND_DISPLAY ]] && ([[ -n $SWAYSOCK ]] || [[ -n $I3SOCK ]]) && (( ${+commands[swaymsg]} )); then # wayland+sway
68 local app_id=$(bgnotify_find_sway_appid)
69 [[ -n "$app_id" ]] && echo "$app_id" || echo $EPOCHSECONDS
70 elif [[ -n $NIRI_SOCKET ]]; then # niri
71 local app_id=$(bgnotify_find_niri_appid)
72 [[ -n "$app_id" ]] && echo "$app_id" || echo $EPOCHSECONDS
73 elif [[ -z $WAYLAND_DISPLAY ]] && [[ -n $DISPLAY ]] && (( ${+commands[xprop]} )); then
74 xprop -root _NET_ACTIVE_WINDOW 2>/dev/null | cut -d' ' -f5
75 else
76 echo $EPOCHSECONDS
77 fi
78}
79
80
81function bgnotify_find_sway_appid {
82 # output is "app_id,container_id", for example "Alacritty,1694"
83 # see example swaymsg output: https://github.com/ohmyzsh/ohmyzsh/files/13463939/output.json
84 if (( ${+commands[jq]} )); then
85 swaymsg -t get_tree | jq '.. | select(.type?) | select(.focused==true) | {app_id, id} | join(",")'
86 else
87 swaymsg -t get_tree | awk '
88 BEGIN { Id = ""; Appid = ""; FocusNesting = -1; Nesting = 0 }
89 {
90 # Enter a block
91 if ($0 ~ /.*{$/) Nesting++
92
93 # Exit a block. If Nesting is now less than FocusNesting, we have the data we are looking for
94 if ($0 ~ /^[[:blank:]]*}.*/) { Nesting--; if (FocusNesting > 0 && Nesting < FocusNesting) exit 0 }
95
96 # Save the Id, it is potentially what we are looking for
97 if ($0 ~ /^[[:blank:]]*"id": [0-9]*,?$/) { sub(/^[[:blank:]]*"id": /, ""); sub(/,$/, ""); Id = $0 }
98
99 # Save the Appid, it is potentially what we are looking for
100 if ($0 ~ /^[[:blank:]]*"app_id": ".*",?$/) { sub(/^[[:blank:]]*"app_id": "/, ""); sub(/",$/, ""); Appid = $0 }
101
102 # Window is focused, this nesting block contains the Id and Appid we want!
103 if ($0 ~ /^[[:blank:]]*"focused": true,?$/) { FocusNesting = Nesting }
104 }
105 END {
106 if (Appid != "" && Id != "" && FocusNesting != -1) print Appid "," Id
107 else print ""
108 }'
109 fi
110}
111
112function bgnotify_find_niri_appid {
113 if (( ${+commands[jq]} )); then
114 niri msg -j windows | jq '.[] | select(.is_focused) | {app_id, id} | join(",")'
115 fi
116}
117
118function bgnotify_programid {
119 case "$TERM_PROGRAM" in
120 iTerm.app) echo 'com.googlecode.iterm2' ;;
121 Apple_Terminal) echo 'com.apple.terminal' ;;
122 ghostty) echo 'com.mitchellh.ghostty' ;;
123 esac
124}
125
126function bgnotify {
127 local title="$1"
128 local message="$2"
129 local icon="$3"
130 if (( ${+commands[terminal-notifier]} )); then # macOS
131 local term_id=$(bgnotify_programid)
132 terminal-notifier -message "$message" -title "$title" ${=icon:+-appIcon "$icon"} ${=term_id:+-activate "$term_id"} ${=bgnotify_extraargs:-} &>/dev/null
133 elif (( ${+commands[growlnotify]} )); then # macOS growl
134 growlnotify -m "$title" "$message" ${=bgnotify_extraargs:-}
135 elif (( ${+commands[notify-send]} )); then
136 notify-send "$title" "$message" ${=icon:+--icon "$icon"} ${=bgnotify_extraargs:-}
137 elif (( ${+commands[kdialog]} )); then # KDE
138 kdialog --title "$title" --passivepopup "$message" 5 ${=bgnotify_extraargs:-}
139 elif (( ${+commands[notifu]} )); then # cygwin
140 notifu /m "$message" /p "$title" ${=icon:+/i "$icon"} ${=bgnotify_extraargs:-}
141 fi
142}
143
144## Defaults
145
146# enable terminal bell on notify by default
147bgnotify_bell=${bgnotify_bell:-true}
148
149# notify if command took longer than 5s by default
150bgnotify_threshold=${bgnotify_threshold:-5}
151
152# bgnotify_appid is slow in macOS and the terminal ID won't change, so cache it at startup
153bgnotify_termid="$(bgnotify_appid)"