fuzzel-run-or-search.sh 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/bin/bash
  2. # Fuzzel's normal application launcher, with a web-search escape hatch.
  3. #
  4. # Enter launch the highlighted application
  5. # Alt+Enter search the web for whatever you typed
  6. #
  7. # The script plays two roles. With no arguments it starts fuzzel, passing
  8. # itself as --launch-prefix. Fuzzel then re-invokes it with the argv it was
  9. # about to run, which is where the search fallback happens: Alt+Enter is bound
  10. # to execute-input (see [key-bindings] in fuzzel.ini), which hands over the
  11. # raw input text rather than a desktop entry, and raw text that isn't an
  12. # executable becomes a search.
  13. browser_app_id="google-chrome"
  14. search_url="https://duckduckgo.com/?q="
  15. search_web() {
  16. local query
  17. query=$(jq -rn --arg q "$1" '$q|@uri')
  18. xdg-open "$search_url$query" &
  19. # Wait for the browser window instead of guessing at a fixed sleep: a cold
  20. # start takes well over half a second, while an already-running Chrome is
  21. # ready almost immediately.
  22. local _
  23. for _ in $(seq 40); do
  24. if swaymsg -t get_tree |
  25. jq -e --arg id "$browser_app_id" \
  26. 'recurse(.nodes[]?, .floating_nodes[]?) | select(.app_id == $id)' >/dev/null; then
  27. swaymsg "[app_id=\"$browser_app_id\"] focus" >/dev/null
  28. return 0
  29. fi
  30. sleep 0.05
  31. done
  32. }
  33. # No arguments: we are the keybinding. Start fuzzel with its default list.
  34. if (( $# == 0 )); then
  35. exec fuzzel --launch-prefix="$(realpath -- "$0")"
  36. fi
  37. # Arguments: fuzzel is asking us to launch something. It exports desktop entry
  38. # metadata only for real entries, so DESKTOP_ENTRY_ID tells the two apart -
  39. # checking whether argv looks like a command does not, because "who is alan
  40. # turing" and "test if it works" both start with a real executable.
  41. if [[ -n ${DESKTOP_ENTRY_ID:-} ]]; then
  42. exec "$@"
  43. fi
  44. search_web "$*"