bgnotify.plugin.zsh 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env zsh
  2. ## setup ##
  3. [[ -o interactive ]] || return #interactive only!
  4. zmodload zsh/datetime || { print "can't load zsh/datetime"; return } # faster than date()
  5. autoload -Uz add-zsh-hook || { print "can't add zsh hook!"; return }
  6. (( ${+bgnotify_threshold} )) || bgnotify_threshold=5 #default 10 seconds
  7. ## definitions ##
  8. if ! (type bgnotify_formatted | grep -q 'function'); then
  9. function bgnotify_formatted {
  10. ## exit_status, command, elapsed_time
  11. [ $1 -eq 0 ] && title="#win (took $3 s)" || title="#fail (took $3 s)"
  12. bgnotify "$title" "$2"
  13. }
  14. fi
  15. currentWindowId () {
  16. if hash osascript 2>/dev/null; then #osx
  17. osascript -e 'tell application (path to frontmost application as text) to id of front window' 2&> /dev/null || echo "0"
  18. elif hash notify-send 2>/dev/null; then #ubuntu!
  19. xprop -root | awk '/NET_ACTIVE_WINDOW/ { print $5; exit }'
  20. else
  21. echo $EPOCHSECONDS #fallback for windows
  22. fi
  23. }
  24. bgnotify () {
  25. if hash terminal-notifier 2>/dev/null; then #osx
  26. terminal-notifier -message "$2" -title "$1"
  27. elif hash growlnotify 2>/dev/null; then #osx growl
  28. growlnotify -m $1 $2
  29. elif hash notify-send 2>/dev/null; then #ubuntu!
  30. notify-send $1 $2
  31. elif hash notifu 2>/dev/null; then #cygwyn support!
  32. notifu /m "$2" /p "$1"
  33. fi
  34. }
  35. ## Zsh hooks ##
  36. bgnotify_begin() {
  37. bgnotify_timestamp=$EPOCHSECONDS
  38. bgnotify_lastcmd=$1
  39. bgnotify_windowid=$(currentWindowId)
  40. }
  41. bgnotify_end() {
  42. didexit=$?
  43. elapsed=$(( EPOCHSECONDS - bgnotify_timestamp ))
  44. past_threshold=$(( elapsed >= bgnotify_threshold ))
  45. if (( bgnotify_timestamp > 0 )) && (( past_threshold )); then
  46. if [ $(currentWindowId) != "$bgnotify_windowid" ]; then
  47. print -n "\a"
  48. bgnotify_formatted "$didexit" "$bgnotify_lastcmd" "$elapsed"
  49. fi
  50. fi
  51. bgnotify_timestamp=0 #reset it to 0!
  52. }
  53. add-zsh-hook preexec bgnotify_begin
  54. add-zsh-hook precmd bgnotify_end